9207bb53b9bcea0948928f031786a97d253a0dde
[DBIx-DBSchema.git] / DBSchema.pm
1 package DBIx::DBSchema;
2
3 use strict;
4 use Storable;
5 use DBIx::DBSchema::_util qw(_load_driver _dbh _parse_opt);
6 use DBIx::DBSchema::Table 0.08;
7 use DBIx::DBSchema::Index;
8 use DBIx::DBSchema::Column;
9 use DBIx::DBSchema::ForeignKey;
10
11 our $VERSION = '0.42';
12 $VERSION = eval $VERSION; # modperlstyle: convert the string into a number
13
14 our $DEBUG = 0;
15
16 our $errstr;
17
18 =head1 NAME
19
20 DBIx::DBSchema - Database-independent schema objects
21
22 =head1 SYNOPSIS
23
24   use DBIx::DBSchema;
25
26   $schema = new DBIx::DBSchema @dbix_dbschema_table_objects;
27   $schema = new_odbc DBIx::DBSchema $dbh;
28   $schema = new_odbc DBIx::DBSchema $dsn, $user, $pass;
29   $schema = new_native DBIx::DBSchema $dbh;
30   $schema = new_native DBIx::DBSchema $dsn, $user, $pass;
31
32   $schema->save("filename");
33   $schema = load DBIx::DBSchema "filename" or die $DBIx::DBSchema::errstr;
34
35   $schema->addtable($dbix_dbschema_table_object);
36
37   @table_names = $schema->tables;
38
39   $DBIx_DBSchema_table_object = $schema->table("table_name");
40
41   @sql = $schema->sql($dbh);
42   @sql = $schema->sql($dsn, $username, $password);
43   @sql = $schema->sql($dsn); #doesn't connect to database - less reliable
44
45   $perl_code = $schema->pretty_print;
46   %hash = eval $perl_code;
47   use DBI qw(:sql_types); $schema = pretty_read DBIx::DBSchema \%hash;
48
49 =head1 DESCRIPTION
50
51 DBIx::DBSchema objects are collections of DBIx::DBSchema::Table objects and
52 represent a database schema.
53
54 This module implements an OO-interface to database schemas.  Using this module,
55 you can create a database schema with an OO Perl interface.  You can read the
56 schema from an existing database.  You can save the schema to disk and restore
57 it in a different process.  You can write SQL CREATE statements statements for
58 different databases from a single source.  In recent versions, you can
59 transform one schema to another, adding any necessary new columns, tables,
60 indices and foreign keys.
61
62 Currently supported databases are MySQL, PostgreSQL and SQLite.  Sybase and
63 Oracle drivers are partially implemented.  DBIx::DBSchema will attempt to use
64 generic SQL syntax for other databases.  Assistance adding support for other
65 databases is welcomed.  See L<DBIx::DBSchema::DBD>, "Driver Writer's Guide and
66 Base Class".
67
68 =head1 METHODS
69
70 =over 4
71
72 =item new TABLE_OBJECT, TABLE_OBJECT, ...
73
74 Creates a new DBIx::DBSchema object.
75
76 =cut
77
78 sub new {
79   my($proto, @tables) = @_;
80   my %tables = map  { $_->name, $_ } @tables; #check for duplicates?
81
82   my $class = ref($proto) || $proto;
83   my $self = {
84     'tables' => \%tables,
85   };
86
87   bless ($self, $class);
88
89 }
90
91 =item new_odbc DATABASE_HANDLE | DATA_SOURCE USERNAME PASSWORD [ ATTR ]
92
93 Creates a new DBIx::DBSchema object from an existing data source, which can be
94 specified by passing an open DBI database handle, or by passing the DBI data
95 source name, username, and password.  This uses the experimental DBI type_info
96 method to create a schema with standard (ODBC) SQL column types that most
97 closely correspond to any non-portable column types.  Use this to import a
98 schema that you wish to use with many different database engines.  Although
99 primary key and (unique) index information will only be read from databases
100 with DBIx::DBSchema::DBD drivers (currently MySQL and PostgreSQL), import of
101 column names and attributes *should* work for any database.  Note that this
102 method only uses "ODBC" column types; it does not require or use an ODBC
103 driver.
104
105 =cut
106
107 sub new_odbc {
108   my($proto, $dbh) = ( shift, _dbh(@_) );
109   $proto->new(
110     map { new_odbc DBIx::DBSchema::Table $dbh, $_ } _tables_from_dbh($dbh)
111   );
112 }
113
114 =item new_native DATABASE_HANDLE | DATA_SOURCE USERNAME PASSWORD [ ATTR ]
115
116 Creates a new DBIx::DBSchema object from an existing data source, which can be
117 specified by passing an open DBI database handle, or by passing the DBI data
118 source name, username and password.  This uses database-native methods to read
119 the schema, and will preserve any non-portable column types.  The method is
120 only available if there is a DBIx::DBSchema::DBD for the corresponding database engine (currently, MySQL and PostgreSQL).
121
122 =cut
123
124 sub new_native {
125   my($proto, $dbh) = (shift, _dbh(@_) );
126   $proto->new(
127     map { new_native DBIx::DBSchema::Table ( $dbh, $_ ) } _tables_from_dbh($dbh)
128   );
129 }
130
131 =item load FILENAME
132
133 Loads a DBIx::DBSchema object from a file.  If there is an error, returns
134 false and puts an error message in $DBIx::DBSchema::errstr;
135
136 =cut
137
138 sub load {
139   my($proto,$file)=@_; #use $proto ?
140
141   my $self;
142
143   #first try Storable
144   eval { $self = Storable::retrieve($file); };
145
146   if ( $@ && $@ =~ /not.*storable/i ) { #then try FreezeThaw
147     my $olderror = $@;
148
149     eval "use FreezeThaw;";
150     if ( $@ ) {
151       $@ = $olderror;
152     } else { 
153       open(FILE,"<$file")
154         or do { $errstr = "Can't open $file: $!"; return ''; };
155       my $string = join('',<FILE>);
156       close FILE
157         or do { $errstr = "Can't close $file: $!"; return ''; };
158       ($self) = FreezeThaw::thaw($string);
159     }
160   }
161
162   unless ( $self ) {
163     $errstr = $@;
164   }
165
166   $self;
167
168 }
169
170 =item save FILENAME
171
172 Saves a DBIx::DBSchema object to a file.
173
174 =cut
175
176 sub save {
177   #my($self, $file) = @_;
178   Storable::nstore(@_);
179 }
180
181 =item addtable TABLE_OBJECT
182
183 Adds the given DBIx::DBSchema::Table object to this DBIx::DBSchema.
184
185 =cut
186
187 sub addtable {
188   my($self,$table)=@_;
189   $self->{'tables'}->{$table->name} = $table; #check for dupliates?
190 }
191
192 =item tables 
193
194 Returns a list of the names of all tables.
195
196 =cut
197
198 sub tables {
199   my($self)=@_;
200   keys %{$self->{'tables'}};
201 }
202
203 =item table TABLENAME
204
205 Returns the specified DBIx::DBSchema::Table object.
206
207 =cut
208
209 sub table {
210   my($self,$table)=@_;
211   $self->{'tables'}->{$table};
212 }
213
214 =item sql [ DATABASE_HANDLE | DATA_SOURCE [ USERNAME PASSWORD [ ATTR ] ] ]
215
216 Returns a list of SQL `CREATE' statements for this schema.
217
218 The data source can be specified by passing an open DBI database handle, or by
219 passing the DBI data source name, username and password.  
220
221 Although the username and password are optional, it is best to call this method
222 with a database handle or data source including a valid username and password -
223 a DBI connection will be opened and used to check the database version as well
224 as for more reliable quoting and type mapping.  Note that the database
225 connection will be used passively, B<not> to actually run the CREATE
226 statements.
227
228 If passed a DBI data source (or handle) such as `DBI:mysql:database' or
229 `DBI:Pg:dbname=database', will use syntax specific to that database engine.
230 Currently supported databases are MySQL and PostgreSQL.
231
232 If not passed a data source (or handle), or if there is no driver for the
233 specified database, will attempt to use generic SQL syntax.
234
235 =cut
236
237 sub sql {
238   my($self, $dbh) = ( shift, _dbh(@_) );
239   map { $self->table($_)->sql_create_table($dbh); } $self->tables;
240 }
241
242 =item sql_update_schema [ OPTIONS_HASHREF, ] PROTOTYPE_SCHEMA [ DATABASE_HANDLE | DATA_SOURCE [ USERNAME PASSWORD [ ATTR ] ] ]
243
244 Returns a list of SQL statements to update this schema so that it is idential
245 to the provided prototype schema, also a DBIx::DBSchema object.
246
247 Right now this method knows how to add new tables and alter existing tables,
248 including indices.  If specifically requested by passing an options hashref
249 with B<drop_tables> set true before all other arguments, it will also drop
250 tables.
251
252 See L<DBIx::DBSchema::Table/sql_alter_table>,
253 L<DBIx::DBSchema::Column/sql_add_column> and
254 L<DBIx::DBSchema::Column/sql_alter_column> for additional specifics and
255 limitations.
256
257 The data source can be specified by passing an open DBI database handle, or by
258 passing the DBI data source name, username and password.  
259
260 Although the username and password are optional, it is best to call this method
261 with a database handle or data source including a valid username and password -
262 a DBI connection will be opened and used to check the database version as well
263 as for more reliable quoting and type mapping.  Note that the database
264 connection will be used passively, B<not> to actually run the CREATE
265 statements.
266
267 If passed a DBI data source (or handle) such as `DBI:mysql:database' or
268 `DBI:Pg:dbname=database', will use syntax specific to that database engine.
269 Currently supported databases are MySQL and PostgreSQL.
270
271 If not passed a data source (or handle), or if there is no driver for the
272 specified database, will attempt to use generic SQL syntax.
273
274 =cut
275
276 #gosh, false laziness w/DBSchema::Table::sql_alter_schema
277
278 sub sql_update_schema {
279   my($self, $opt, $new, $dbh) = ( shift, _parse_opt(\@_), shift, _dbh(@_) );
280
281   my @r = ();
282
283   foreach my $table ( $new->tables ) {
284   
285     if ( $self->table($table) ) {
286   
287       warn "$table exists\n" if $DEBUG > 1;
288
289       push @r, $self->table($table)->sql_alter_table( $new->table($table),
290                                                       $dbh,
291                                                       $opt
292                                                     );
293
294     } else {
295   
296       warn "table $table does not exist.\n" if $DEBUG;
297
298       push @r, 
299         $new->table($table)->sql_create_table( $dbh );
300   
301     }
302   
303   }
304
305   if ( $opt->{'drop_tables'} ) {
306
307     warn "drop_tables enabled\n" if $DEBUG;
308
309     # drop tables not in $new
310     foreach my $table ( grep !$new->table($_), $self->tables ) {
311
312       warn "table $table should be dropped.\n" if $DEBUG;
313
314       push @r, $self->table($table)->sql_drop_table( $dbh );
315
316     }
317
318   }
319
320   warn join("\n", @r). "\n"
321     if $DEBUG > 1;
322
323   @r;
324   
325 }
326
327 =item update_schema [ OPTIONS_HASHREF, ] PROTOTYPE_SCHEMA, DATABASE_HANDLE | DATA_SOURCE [ USERNAME PASSWORD [ ATTR ] ]
328
329 Same as sql_update_schema, except actually runs the SQL commands to update
330 the schema.  Throws a fatal error if any statement fails.
331
332 =cut
333
334 sub update_schema {
335   #my($self, $new, $dbh) = ( shift, shift, _dbh(@_) );
336   my($self, $opt, $new, $dbh) = ( shift, _parse_opt(\@_), shift, _dbh(@_) );
337
338   foreach my $statement ( $self->sql_update_schema( $opt, $new, $dbh ) ) {
339     $dbh->do( $statement )
340       or die "Error: ". $dbh->errstr. "\n executing: $statement";
341   }
342
343 }
344
345 =item pretty_print
346
347 Returns the data in this schema as Perl source, suitable for assigning to a
348 hash.
349
350 =cut
351
352 sub pretty_print {
353   my($self) = @_;
354
355   join("},\n\n",
356     map {
357       my $tablename = $_;
358       my $table = $self->table($tablename);
359       my %indices = $table->indices;
360
361       "'$tablename' => {\n".
362         "  'columns' => [\n".
363           join("", map { 
364                          #cant because -w complains about , in qw()
365                          # (also biiiig problems with empty lengths)
366                          #"    qw( $_ ".
367                          #$table->column($_)->type. " ".
368                          #( $table->column($_)->null ? 'NULL' : 0 ). " ".
369                          #$table->column($_)->length. " ),\n"
370                          "    '$_', ".
371                          "'". $table->column($_)->type. "', ".
372                          "'". $table->column($_)->null. "', ". 
373                          "'". $table->column($_)->length. "', ".
374
375                          ( ref($table->column($_)->default)
376                              ? "\\'". ${ $table->column($_)->default }. "'"
377                              : "'". $table->column($_)->default. "'"
378                          ).', '.
379
380                          "'". $table->column($_)->local. "',\n"
381                        } $table->columns
382           ).
383         "  ],\n".
384         "  'primary_key' => '". $table->primary_key. "',\n".
385
386         #old style index representation..
387
388         ( 
389           $table->{'unique'} # $table->_unique
390             ? "  'unique' => [ ". join(', ',
391                 map { "[ '". join("', '", @{$_}). "' ]" }
392                     @{$table->_unique->lol_ref}
393               ).  " ],\n"
394             : ''
395         ).
396
397         ( $table->{'index'} # $table->_index
398             ? "  'index' => [ ". join(', ',
399                 map { "[ '". join("', '", @{$_}). "' ]" }
400                     @{$table->_index->lol_ref}
401               ). " ],\n"
402             : ''
403         ).
404
405         #new style indices
406         "  'indices' => { ". join( ",\n                 ",
407
408           map { my $iname = $_;
409                 my $index = $indices{$iname};
410                 "'$iname' => { \n".
411                   ( $index->using
412                       ? "              'using'  => '". $index->using ."',\n"
413                       : ''
414                   ).
415                   "                   'unique'  => ". $index->unique .",\n".
416                   "                   'columns' => [ '".
417                                               join("', '", @{$index->columns} ).
418                                               "' ],\n".
419                 "                 },\n";
420               }
421               keys %indices
422
423         ). "\n               }, \n".
424
425         #foreign_keys
426         "  'foreign_keys' => [ ". join( ",\n                 ",
427
428           map { my $name = $_->constraint;
429                 "'$name' => { \n".
430                 "                 },\n";
431               }
432             $table->foreign_keys
433
434         ). "\n               ], \n"
435
436       ;
437
438     } $self->tables
439   ). "}\n";
440 }
441
442 =cut
443
444 =item pretty_read HASHREF
445
446 This method is B<not> recommended.  If you need to load and save your schema
447 to a file, see the L</load|load> and L</save|save> methods.
448
449 Creates a schema as specified by a data structure such as that created by
450 B<pretty_print> method.
451
452 =cut
453
454 sub pretty_read {
455   my($proto, $href) = @_;
456
457   my $schema = $proto->new( map {  
458
459     my $tablename = $_;
460     my $info = $href->{$tablename};
461
462     my @columns;
463     while ( @{$info->{'columns'}} ) {
464       push @columns, DBIx::DBSchema::Column->new(
465         splice @{$info->{'columns'}}, 0, 6
466       );
467     }
468
469     DBIx::DBSchema::Table->new({
470       'name'        => $tablename,
471       'primary_key' => $info->{'primary_key'},
472       'columns'     => \@columns,
473
474       #indices
475       'indices'     => [ map { my $idx_info = $info->{'indices'}{$_};
476                                DBIx::DBSchema::Index->new({
477                                  'name'    => $_,
478                                  #'using'   =>
479                                  'unique'  => $idx_info->{'unique'},
480                                  'columns' => $idx_info->{'columns'},
481                                });
482                              }
483                              keys %{ $info->{'indices'} }
484                        ],
485     } );
486
487   } (keys %{$href}) );
488
489 }
490
491 # private subroutines
492
493 sub _tables_from_dbh {
494   my($dbh) = @_;
495   my $driver = _load_driver($dbh);
496   my $db_catalog =
497     scalar(eval "DBIx::DBSchema::DBD::$driver->default_db_catalog");
498   my $db_schema  =
499     scalar(eval "DBIx::DBSchema::DBD::$driver->default_db_schema");
500   my $sth = $dbh->table_info($db_catalog, $db_schema, '', 'TABLE')
501     or die $dbh->errstr;
502   #map { $_->{TABLE_NAME} } grep { $_->{TABLE_TYPE} eq 'TABLE' }
503   #  @{ $sth->fetchall_arrayref({ TABLE_NAME=>1, TABLE_TYPE=>1}) };
504   map { $_->[0] } grep { $_->[1] =~ /^TABLE$/i }
505     @{ $sth->fetchall_arrayref([2,3]) };
506 }
507
508 =back
509
510 =head1 AUTHORS
511
512 Ivan Kohler <ivan-dbix-dbschema@420.am>
513
514 Charles Shapiro <charles.shapiro@numethods.com> and Mitchell Friedman
515 <mitchell.friedman@numethods.com> contributed the start of a Sybase driver.
516
517 Daniel Hanks <hanksdc@about-inc.com> contributed the Oracle driver.
518
519 Jesse Vincent contributed the SQLite driver and fixes to quiet down
520 internal usage of the old API.
521
522 Slaven Rezic <srezic@cpan.org> contributed column and table dropping, Pg
523 bugfixes and more.
524
525 =head1 CONTRIBUTIONS
526
527 Contributions are welcome!  I'm especially keen on any interest in the top
528 items/projects below under BUGS.
529
530 =head1 COPYRIGHT
531
532 Copyright (c) 2000-2007 Ivan Kohler
533 Copyright (c) 2000 Mail Abuse Prevention System LLC
534 Copyright (c) 2007-2013 Freeside Internet Services, Inc.
535 All rights reserved.
536 This program is free software; you can redistribute it and/or modify it under
537 the same terms as Perl itself.
538
539 =head1 BUGS AND TODO
540
541 Multiple primary keys are not yet supported.
542
543 Foreign keys: need to support dropping, NOT VALID, reverse engineering w/mysql
544
545 Need to port and test with additional databases
546
547 Each DBIx::DBSchema object should have a name which corresponds to its name
548 within the SQL database engine (DBI data source).
549
550 Need to support "using" index attribute in pretty_read and in reverse
551 engineering
552
553 sql CREATE TABLE output should convert integers
554 (i.e. use DBI qw(:sql_types);) to local types using DBI->type_info plus a hash
555 to fudge things
556
557 =head2 PRETTY_ BUGS
558
559 pretty_print is actually pretty ugly.
560
561 pretty_print isn't so good about quoting values...  save/load is a much better
562 alternative to using pretty_print/pretty_read
563
564 pretty_read is pretty ugly too.
565
566 pretty_read should *not* create and pass in old-style unique/index indices
567 when nothing is given in the read.
568
569 Perhaps pretty_read should eval column types so that we can use DBI
570 qw(:sql_types) here instead of externally.
571
572 perhaps we should just get rid of pretty_read entirely.  pretty_print is useful
573 for debugging, but pretty_read is pretty bunk.
574
575 =head1 SEE ALSO
576
577 L<DBIx::DBSchema::Table>, L<DBIx::DBSchema::Index>,
578 L<DBIx::DBSchema::Column>, L<DBIx::DBSchema::DBD>,
579 L<DBIx::DBSchema::DBD::mysql>, L<DBIx::DBSchema::DBD::Pg>, L<FS::Record>,
580 L<DBI>
581
582 =cut
583
584 1;
585