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