support multiple primary keys
[freeside.git] / FS / FS / part_export / acct_sql.pm
1 package FS::part_export::acct_sql;
2
3 use vars qw(@ISA %info @saltset);
4 use Tie::IxHash;
5 #use Digest::MD5 qw(md5_hex);
6 use FS::Record; #qw(qsearchs);
7 use FS::part_export;
8
9 @ISA = qw(FS::part_export);
10
11 tie my %options, 'Tie::IxHash',
12   'datasrc'            => { label => 'DBI data source' },
13   'username'           => { label => 'Database username' },
14   'password'           => { label => 'Database password' },
15   'table'              => { label => 'Database table' },
16   'schema'             => { label =>
17                               'Database schema mapping to Freeside methods.',
18                             type  => 'textarea',
19                           },
20   'primary_key'        => { label => 'Database primary key' },
21   'crypt'              => { label => 'Password encryption',
22                             type=>'select', options=>[qw(crypt md5)],
23                             default=>'crypt',
24                           },
25 ;
26
27 tie my %vpopmail_map, 'Tie::IxHash',
28   'pw_name'   => 'username',
29   'pw_domain' => 'domain',
30   'pw_passwd' => 'crypt_password',
31   'pw_uid'    => 'uid',
32   'pw_gid'    => 'gid',
33   'pw_gecos'  => 'finger',
34   'pw_dir'    => 'dir',
35   'pw_shell'  => 'shell',
36 ;
37 my $vpopmail_map = join('\n', map "$_ $vpopmail_map{$_}", keys %vpopmail_map );
38
39 tie my %postfix_courierimap_mailbox_map, 'Tie::IxHash',
40   'username' => 'email',
41   'password' => '_password',
42   'crypt'    => 'crypt_password',
43   'name'     => 'finger',
44   'maildir'  => 'virtual_maildir',
45   'domain'   => 'domain',
46   'svcnum'   => 'svcnum',
47 ;
48 my $postfix_courierimap_mailbox_map =
49   join('\n', map "$_ $postfix_courierimap_mailbox_map{$_}",
50                  keys %postfix_courierimap_mailbox_map      );
51
52 tie my %postfix_courierimap_alias_map, 'Tie::IxHash',
53   'address' => 'email',
54   'goto'    => 'email',
55   'domain'  => 'domain',
56   'svcnum'  => 'svcnum',
57 ;
58 my $postfix_courierimap_alias_map =
59   join('\n', map "$_ $postfix_courierimap_alias_map{$_}",
60                  keys %postfix_courierimap_alias_map      );
61
62 %info = (
63   'svc'      => 'svc_acct',
64   'desc'     => 'Real-time export of accounts to SQL databases '.
65                 '(vpopmail, Postfix+Courier IMAP, others?)',
66   'options'  => \%options,
67   'nodomain' => '',
68   'notes'    => <<END
69 Export accounts (svc_acct records) to SQL databases.  Currently has default
70 configurations for vpopmail and Postfix+Courier IMAP but intended to be
71 configurable for other schemas as well.
72
73 <BR><BR>In contrast to sqlmail, this is intended to export just svc_acct
74 records only, rather than a single export for svc_acct, svc_forward and
75 svc_domain records, to export in "default" database schemas rather than
76 configure the MTA or POP/IMAP server for a Freeside-specific schema, and
77 to be configured for different mail server setups.
78
79 <BR><BR>Use these buttons for some useful presets:
80 <UL>
81   <li><INPUT TYPE="button" VALUE="vpopmail" onClick='
82     this.form.table.value = "vpopmail";
83     this.form.schema.value = "$vpopmail_map";
84     this.form.primary_key.value = "pw_name, pw_domain";
85   '>
86   <LI><INPUT TYPE="button" VALUE="postfix_courierimap_mailbox" onClick='
87     this.form.table.value = "mailbox";
88     this.form.schema.value = "$postfix_courierimap_mailbox_map";
89     this.form.primary_key.value = "username";
90   '>
91   <LI><INPUT TYPE="button" VALUE="postfix_courierimap_alias" onClick='
92     this.form.table.value = "alias";
93     this.form.schema.value = "$postfix_courierimap_alias_map";
94     this.form.primary_key.value = "address";
95   '>
96 </UL>
97 END
98 );
99
100 sub _map {
101   my $self = shift;
102   map { /^\s*(\S+)\s*(\S+)\s*$/ } split("\n", $self->option('schema') );
103 }
104
105 sub rebless { shift; }
106
107 sub _export_insert {
108   my($self, $svc_acct) = (shift, shift);
109
110   my %map = $self->_map;
111
112   my %record = map { my $value = $map{$_};
113                      my @arg = ();
114                      push @arg, $self->option('crypt')
115                        if $value eq 'crypt_password' && $self->option('crypt');
116                      $_ => $svc_acct->$value(@arg);
117                    } keys %map;
118
119   my $err_or_queue =
120     $self->acct_sql_queue(
121       $svc_acct->svcnum,
122       'insert',
123       $self->option('table'),
124       %record
125     );
126   return $err_or_queue unless ref($err_or_queue);
127
128   '';
129
130 }
131
132 sub _export_replace {
133   my($self, $new, $old) = (shift, shift, shift);
134
135   my %map = $self->_map;
136
137   my @primary_key = ();
138   if ( $self->option('primary_key') =~ /,/ ) {
139     foreach my $key ( split(/\s*,\s*/, $self->option('primary_key') ) ) {
140       my $keymap = $map{$key};
141       push @primary_key, $old->$keymap();
142     }
143   } else {
144     my $keymap = $map{$self->option('primary_key')};
145     push @primary_key, $old->$keymap();
146   }
147
148   my %record = map { my $value = $map{$_};
149                      my @arg = ();
150                      push @arg, $self->option('crypt')
151                        if $_ eq 'crypt_password' && $self->option('crypt');
152                      $_ => $new->$value(@arg);
153                    } keys %map;
154
155   my $err_or_queue = $self->acct_sql_queue(
156     $new->svcnum,
157     'replace',
158     $self->option('table'),
159     $self->option('primary_key'), @primary_key, 
160     %record,
161   );
162   return $err_or_queue unless ref($err_or_queue);
163   '';
164 }
165
166 sub _export_delete {
167   my ( $self, $svc_acct ) = (shift, shift);
168
169   my %map = $self->_map;
170
171   my %primary_key = ();
172   if ( $self->option('primary_key') =~ /,/ ) {
173     foreach my $key ( split(/\s*,\s*/, $self->option('primary_key') ) ) {
174       my $keymap = $map{$key};
175       $primary_key{ $key } = $svc_acct->$keymap();
176     }
177   } else {
178     my $keymap = $map{$self->option('primary_key')};
179     $primary_key{ $self->option('primary_key') } = $svc_acct->$keymap(),
180   }
181
182   my $err_or_queue = $self->acct_sql_queue(
183     $svc_acct->svcnum,
184     'delete',
185     $self->option('table'),
186     %primary_key,
187     #$self->option('primary_key') => $svc_acct->$keymap(),
188   );
189   return $err_or_queue unless ref($err_or_queue);
190   '';
191 }
192
193 sub acct_sql_queue {
194   my( $self, $svcnum, $method ) = (shift, shift, shift);
195   my $queue = new FS::queue {
196     'svcnum' => $svcnum,
197     'job'    => "FS::part_export::acct_sql::acct_sql_$method",
198   };
199   $queue->insert(
200     $self->option('datasrc'),
201     $self->option('username'),
202     $self->option('password'),
203     @_,
204   ) or $queue;
205 }
206
207 sub acct_sql_insert { #subroutine, not method
208   my $dbh = acct_sql_connect(shift, shift, shift);
209   my( $table, %record ) = @_;
210
211   my $sth = $dbh->prepare(
212     "INSERT INTO $table ( ". join(", ", keys %record).
213     " ) VALUES ( ". join(", ", map '?', keys %record ). " )"
214   ) or die $dbh->errstr;
215
216   $sth->execute( values(%record) )
217     or die "can't insert into $table table: ". $sth->errstr;
218
219   $dbh->disconnect;
220 }
221
222 sub acct_sql_delete { #subroutine, not method
223   my $dbh = acct_sql_connect(shift, shift, shift);
224   my( $table, %record ) = @_;
225
226   my $sth = $dbh->prepare(
227     "DELETE FROM $table WHERE ". join(' AND ', map "$_ = ? ", keys %record )
228   ) or die $dbh->errstr;
229
230   $sth->execute( map $record{$_}, keys %record )
231     or die "can't delete from $table table: ". $sth->errstr;
232
233   $dbh->disconnect;
234 }
235
236 sub acct_sql_replace { #subroutine, not method
237   my $dbh = acct_sql_connect(shift, shift, shift);
238
239   my( $table, $pkey ) = ( shift, shift );
240
241   my %primary_key = ();
242   if ( $pkey =~ /,/ ) {
243     foreach my $key ( split(/\s*,\s*/, $pkey ) ) {
244       $primary_key{$key} = shift;
245     }
246   } else {
247     $primary_key{$pkey} = shift;
248   }
249
250   my %record = @_;
251
252   my $sth = $dbh->prepare(
253     "UPDATE $table".
254     ' SET '.   join(', ',    map "$_ = ?", keys %record      ).
255     ' WHERE '. join(' AND ', map "$_ = ?", keys %primary_key )
256   ) or die $dbh->errstr;
257
258   $sth->execute( values(%record), values(%primary_key) );
259
260   $dbh->disconnect;
261 }
262
263 sub acct_sql_connect {
264   #my($datasrc, $username, $password) = @_;
265   #DBI->connect($datasrc, $username, $password) or die $DBI::errstr;
266   DBI->connect(@_) or die $DBI::errstr;
267 }
268
269 1;
270