Wrap all close() calls in "ensure" blocks and simplify DB connection-making.
[mailshears.git] / lib / mv / plugins / roundcube.rb
1 require 'pg'
2
3 require 'common/roundcube_plugin'
4 require 'mv/mv_plugin'
5
6 # Handle moving (renaming) of users in the Roundcube
7 # database. Roundcube has no concept of domains.
8 #
9 class RoundcubeMv
10
11 include RoundcubePlugin
12 include MvPlugin
13
14
15 # Move the user *src* to *dst* within the Roundcube database. This
16 # should "rename" him in _every_ table where he is referenced.
17 # Roundcube uses foreign keys properly, so we let the ON UPDATE
18 # CASCADE trigger handle most of the work.
19 #
20 # This can fail is *src* does not exist, or if *dst* already exists
21 # before the move. It should also be an error if the destination
22 # domain doesn't exist. But Roundcube doesn't know about domains, so
23 # we let that slide.
24 #
25 # @param src [User] the source user to be moved.
26 #
27 # @param dst [User] the destination user being moved to.
28 #
29 def mv_user(src, dst)
30 raise NonexistentUserError.new(src.to_s()) if not user_exists(src)
31 raise UserAlreadyExistsError.new(dst.to_s()) if user_exists(dst)
32
33 sql_query = 'UPDATE users SET username = $1 WHERE username = $2;'
34
35 connection = PG::Connection.new(@db_hash)
36 begin
37 connection.query(sql_query, [dst.to_s(), src.to_s()])
38 ensure
39 # Make sure the connection gets closed even if the query explodes.
40 connection.close()
41 end
42 end
43
44 end