]> gitweb.michael.orlitzky.com - mailshears.git/blob - lib/mv/plugins/postfixadmin.rb
lib,test: replace connection query() method with sync_exec{,_params}.
[mailshears.git] / lib / mv / plugins / postfixadmin.rb
1 require 'pg'
2
3 require 'common/postfixadmin_plugin'
4 require 'mv/mv_plugin'
5
6
7 # Handle moving (renaming) of users in the Postfixadmin database.
8 #
9 class PostfixadminMv
10
11 include PostfixadminPlugin
12 include MvPlugin
13
14
15 # Move the user *src* to *dst* within the Postfixadmin
16 # database. This should "rename" him in _every_ table where he is
17 # referenced. Unfortunately that must be done manually.
18 #
19 # This can fail is *src* does not exist, or if *dst* already exists
20 # before the move. It will also fail if the domain associated with
21 # the user *dst* does not exist.
22 #
23 # @param src [User] the source user to be moved.
24 #
25 # @param dst [User] the destination user being moved to.
26 #
27 def mv_user(src, dst)
28 raise NonexistentUserError.new(src.to_s()) if not user_exists(src)
29
30 if not domain_exists(dst.domain())
31 raise NonexistentDomainError.new(dst.domain.to_s())
32 end
33
34 raise UserAlreadyExistsError.new(dst.to_s()) if user_exists(dst)
35
36 mailbox_query = 'UPDATE mailbox SET '
37 mailbox_query += ' username=$1,'
38 mailbox_query += ' domain=$2,'
39 mailbox_query += " maildir=CONCAT($2, '/', $3, '/'),"
40 mailbox_query += ' local_part=$3 '
41 mailbox_query += 'WHERE username=$4;'
42
43 alias_query1 = 'UPDATE alias SET '
44 alias_query1 += ' address=$1,'
45 alias_query1 += ' domain=$2,'
46 alias_query1 += ' goto=REPLACE(goto, $4, $1) '
47 alias_query1 += 'WHERE address=$4;'
48
49 alias_query2 = 'UPDATE alias SET '
50 alias_query2 += 'goto=REPLACE(goto, $4, $1);'
51
52 sql_queries = [mailbox_query, alias_query1, alias_query2]
53
54 connection = PG::Connection.new(@db_hash)
55 begin
56 sql_queries.each do |sql_query|
57 varchar = 1043 # from pg_type.h
58 params = [{:value => dst.to_s(), :type => varchar},
59 {:value => dst.domainpart(), :type => varchar},
60 {:value => dst.localpart(), :type => varchar},
61 {:value => src.to_s(), :type => varchar}]
62 connection.sync_exec_params(sql_query, params)
63 end
64 ensure
65 # Make sure the connection gets closed even if a query explodes.
66 connection.close()
67 end
68 end
69
70 end