Wrap all close() calls in "ensure" blocks and simplify DB connection-making.
[mailshears.git] / lib / common / agendav_plugin.rb
1 require 'common/plugin'
2 require 'common/user'
3
4 # Code that all Agendav plugins ({AgendavPrune}, {AgendavRm},
5 # {AgendavMv}) share.
6 module AgendavPlugin
7
8 # We implement the Plugin "interface."
9 include Plugin
10
11
12 # Initialize this Agendav {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.agendav_dbhost,
19 :port => cfg.agendav_dbport,
20 :options => cfg.agendav_dbopts,
21 :tty => cfg.agendav_dbtty,
22 :dbname => cfg.agendav_dbname,
23 :user => cfg.agendav_dbuser,
24 :password => cfg.agendav_dbpass }
25 end
26
27
28 # Return a list of Agendav users.
29 #
30 # @return [Array<User>] a list of users contained in the
31 # Agendav database.
32 #
33 def list_users()
34 users = []
35
36 connection = PG::Connection.new(@db_hash)
37
38 sql_query = '(SELECT username FROM prefs)'
39 sql_query += 'UNION'
40 sql_query += '(SELECT user_from FROM shared);'
41
42 begin
43 connection.query(sql_query) do |result|
44 users = result.field_values('username')
45 end
46 ensure
47 # Make sure the connection gets closed even if the query explodes.
48 connection.close()
49 end
50
51 return users.map{ |u| User.new(u) }
52 end
53
54 end