Wrap all close() calls in "ensure" blocks and simplify DB connection-making.
[mailshears.git] / lib / common / davical_plugin.rb
1 require 'common/plugin'
2 require 'common/user'
3
4 # Code that all DAViCal plugins ({DavicalPrune}, {DavicalRm}, and
5 # {DavicalMv}) will share.
6 #
7 module DavicalPlugin
8
9 # We implement the Plugin "interface."
10 include Plugin
11
12 # Initialize this DAViCal {Plugin} with values in *cfg*.
13 #
14 # @param cfg [Configuration] the configuration for this plugin.
15 #
16 def initialize(cfg)
17 @db_hash = {
18 :host => cfg.davical_dbhost,
19 :port => cfg.davical_dbport,
20 :options => cfg.davical_dbopts,
21 :tty => cfg.davical_dbtty,
22 :dbname => cfg.davical_dbname,
23 :user => cfg.davical_dbuser,
24 :password => cfg.davical_dbpass }
25 end
26
27
28 # Describe the given DAViCal user who is assumed to exist.
29 #
30 # @param user [User] the {User} object whose description we want.
31 #
32 # @return [String] a String describing the given *user* in terms
33 # of his DAViCal "Principal ID".
34 #
35 def describe_user(user)
36 principal_id = self.get_principal_id(user)
37 return "Principal ID: #{principal_id}"
38 end
39
40
41 #
42 # Produce a list of DAViCal users.
43 #
44 # This method remains public for use in testing.
45 #
46 # @return [Array<User>] an array of {User} objects, one for each
47 # user found in the DAViCal database.
48 #
49 def list_users()
50 usernames = []
51
52 connection = PG::Connection.new(@db_hash)
53
54 # User #1 is the super-user, and not tied to an email address.
55 sql_query = 'SELECT username FROM usr WHERE user_no > 1;'
56
57 begin
58 connection.query(sql_query) do |result|
59 usernames = result.field_values('username')
60 end
61 ensure
62 # Make sure the connection gets closed even if the query explodes.
63 connection.close()
64 end
65
66 return usernames.map{ |u| User.new(u) }
67 end
68
69
70 protected;
71
72
73 # Find the "Principal ID" of the given user.
74 #
75 # @param user [User] the user whose Principal ID we want.
76 #
77 # @return [Fixnum] an integer representing the user's Principal ID
78 # that we obtained from the DAViCal database.
79 #
80 def get_principal_id(user)
81 principal_id = nil
82
83 connection = PG::Connection.new(@db_hash)
84
85 sql_query = 'SELECT principal.principal_id '
86 sql_query += 'FROM (principal INNER JOIN usr '
87 sql_query += ' ON principal.user_no = usr.user_no) '
88 sql_query += 'WHERE usr.username = $1;'
89
90 begin
91 connection.query(sql_query, [user.to_s()]) do |result|
92 if result.num_tuples > 0
93 principal_id = result[0]['principal_id']
94 end
95 end
96 ensure
97 # Make sure the connection gets closed even if the query explodes.
98 connection.close()
99 end
100
101 return principal_id
102 end
103
104 end