b821d16ac2383f9a4f4d09d9c4eb9bad12f4b989
[DBIx-DBSchema.git] / DBSchema.pm
1 package DBIx::DBSchema;
2
3 use strict;
4 use vars qw($VERSION $DEBUG $errstr);
5 use Storable;
6 use DBIx::DBSchema::_util qw(_load_driver _dbh);
7 use DBIx::DBSchema::Table 0.05;
8 use DBIx::DBSchema::Index;
9 use DBIx::DBSchema::Column;
10 use DBIx::DBSchema::ColGroup::Unique;
11 use DBIx::DBSchema::ColGroup::Index;
12
13 $VERSION = "0.34_01";
14 $VERSION = eval $VERSION; # modperlstyle: convert the string into a number
15
16 $DEBUG = 0;
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 and tables
60 (and, as of 0.33, indices).
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 the quoting and type mapping will be more
224 reliable.
225
226 If passed a DBI data source (or handle) such as `DBI:mysql:database' or
227 `DBI:Pg:dbname=database', will use syntax specific to that database engine.
228 Currently supported databases are MySQL and PostgreSQL.
229
230 If not passed a data source (or handle), or if there is no driver for the
231 specified database, will attempt to use generic SQL syntax.
232
233 =cut
234
235 sub sql {
236   my($self, $dbh) = ( shift, _dbh(@_) );
237   map { $self->table($_)->sql_create_table($dbh); } $self->tables;
238 }
239
240 =item sql_update_schema PROTOTYPE_SCHEMA [ DATABASE_HANDLE | DATA_SOURCE [ USERNAME PASSWORD [ ATTR ] ] ]
241
242 Returns a list of SQL statements to update this schema so that it is idential
243 to the provided prototype schema, also a DBIx::DBSchema object.
244
245  #Optionally, the data source can be specified by passing an open DBI database
246  #handle, or by passing the DBI data source name, username and password.  
247  #
248  #If passed a DBI data source (or handle) such as `DBI:mysql:database' or
249  #`DBI:Pg:dbname=database', will use syntax specific to that database engine.
250  #Currently supported databases are MySQL and PostgreSQL.
251  #
252  #If not passed a data source (or handle), or if there is no driver for the
253  #specified database, will attempt to use generic SQL syntax.
254
255 Right now this method knows how to add new tables and alter existing tables.
256 It doesn't know how to drop tables yet.
257
258 See L<DBIx::DBSchema::Table/sql_alter_table>,
259 L<DBIx::DBSchema::Column/sql_add_coumn> and
260 L<DBIx::DBSchema::Column/sql_alter_column> for additional specifics and
261 limitations.
262
263 =cut
264
265 #gosh, false laziness w/DBSchema::Table::sql_alter_schema
266
267 sub sql_update_schema {
268   my($self, $new, $dbh) = ( shift, shift, _dbh(@_) );
269
270   my @r = ();
271
272   foreach my $table ( $new->tables ) {
273   
274     if ( $self->table($table) ) {
275   
276       warn "$table exists\n" if $DEBUG > 1;
277
278       push @r,
279         $self->table($table)->sql_alter_table( $new->table($table), $dbh );
280
281     } else {
282   
283       warn "table $table does not exist.\n" if $DEBUG;
284
285       push @r, 
286         $new->table($table)->sql_create_table( $dbh );
287   
288     }
289   
290   }
291
292   # drop tables not in $new
293   foreach my $table ( $self->tables ) {
294
295     if ( !$new->table($table) ) {
296
297       warn "table $table should be dropped.\n" if $DEBUG;
298
299       push @r,
300        $self->table($table)->sql_drop_table( $dbh );
301     }
302   }
303
304   warn join("\n", @r). "\n"
305     if $DEBUG > 1;
306
307   @r;
308   
309 }
310
311 =item update_schema PROTOTYPE_SCHEMA, DATABASE_HANDLE | DATA_SOURCE [ USERNAME PASSWORD [ ATTR ] ]
312
313 Same as sql_update_schema, except actually runs the SQL commands to update
314 the schema.  Throws a fatal error if any statement fails.
315
316 =cut
317
318 sub update_schema {
319   my($self, $new, $dbh) = ( shift, shift, _dbh(@_) );
320
321   foreach my $statement ( $self->sql_update_schema( $new, $dbh ) ) {
322     $dbh->do( $statement )
323       or die "Error: ". $dbh->errstr. "\n executing: $statement";
324   }
325
326 }
327
328 =item pretty_print
329
330 Returns the data in this schema as Perl source, suitable for assigning to a
331 hash.
332
333 =cut
334
335 sub pretty_print {
336   my($self) = @_;
337
338   join("},\n\n",
339     map {
340       my $tablename = $_;
341       my $table = $self->table($tablename);
342       my %indices = $table->indices;
343
344       "'$tablename' => {\n".
345         "  'columns' => [\n".
346           join("", map { 
347                          #cant because -w complains about , in qw()
348                          # (also biiiig problems with empty lengths)
349                          #"    qw( $_ ".
350                          #$table->column($_)->type. " ".
351                          #( $table->column($_)->null ? 'NULL' : 0 ). " ".
352                          #$table->column($_)->length. " ),\n"
353                          "    '$_', ".
354                          "'". $table->column($_)->type. "', ".
355                          "'". $table->column($_)->null. "', ". 
356                          "'". $table->column($_)->length. "', ".
357                          "'". $table->column($_)->default. "', ".
358                          "'". $table->column($_)->local. "',\n"
359                        } $table->columns
360           ).
361         "  ],\n".
362         "  'primary_key' => '". $table->primary_key. "',\n".
363
364         #old style index representation..
365
366         ( 
367           $table->{'unique'} # $table->unique
368             ? "  'unique' => [ ". join(', ',
369                 map { "[ '". join("', '", @{$_}). "' ]" }
370                     @{$table->unique->lol_ref}
371               ).  " ],\n"
372             : ''
373         ).
374
375         ( $table->{'index'} # $table->index
376             ? "  'index' => [ ". join(', ',
377                 map { "[ '". join("', '", @{$_}). "' ]" }
378                     @{$table->index->lol_ref}
379               ). " ],\n"
380             : ''
381         ).
382
383         #new style indices
384         "  'indices' => { ". join( ",\n                 ",
385
386           map { my $iname = $_;
387                 my $index = $indices{$iname};
388                 "'$iname' => { \n".
389                   ( $index->using
390                       ? "              'using'  => '". $index->using ."',\n"
391                       : ''
392                   ).
393                   "                   'unique'  => ". $index->unique .",\n".
394                   "                   'columns' => [ '".
395                                               join("', '", @{$index->columns} ).
396                                               "' ],\n".
397                 "                 },\n";
398               }
399               keys %indices
400
401         ). "\n               }, \n"
402
403     } $self->tables
404   ). "}\n";
405 }
406
407 =cut
408
409 =item pretty_read HASHREF
410
411 Creates a schema as specified by a data structure such as that created by
412 B<pretty_print> method.
413
414 =cut
415
416 sub pretty_read {
417   my($proto, $href) = @_;
418
419   my $schema = $proto->new( map {  
420
421     my $tablename = $_;
422     my $info = $href->{$tablename};
423
424     my @columns;
425     while ( @{$info->{'columns'}} ) {
426       push @columns, DBIx::DBSchema::Column->new(
427         splice @{$info->{'columns'}}, 0, 6
428       );
429     }
430
431     DBIx::DBSchema::Table->new({
432       'name'        => $tablename,
433       'primary_key' => $info->{'primary_key'},
434       'columns'     => \@columns,
435
436       #old-style indices 
437       'unique'      => DBIx::DBSchema::ColGroup::Unique->new($info->{'unique'}),
438       'index'       => DBIx::DBSchema::ColGroup::Index->new($info->{'index'}),
439
440       #new-style indices
441       'indices'     => [ map { my $idx_info = $info->{'indices'}{$_};
442                                DBIx::DBSchema::Index->new({
443                                  'name'    => $_,
444                                  #'using'   =>
445                                  'unique'  => $idx_info->{'unique'},
446                                  'columns' => $idx_info->{'columns'},
447                                });
448                              }
449                              keys %{ $info->{'indices'} }
450                        ],
451     } );
452
453   } (keys %{$href}) );
454
455 }
456
457 # private subroutines
458
459 sub _tables_from_dbh {
460   my($dbh) = @_;
461   my $driver = _load_driver($dbh);
462   my $db_catalog =
463     scalar(eval "DBIx::DBSchema::DBD::$driver->default_db_catalog");
464   my $db_schema  =
465     scalar(eval "DBIx::DBSchema::DBD::$driver->default_db_schema");
466   my $sth = $dbh->table_info($db_catalog, $db_schema, '', 'TABLE')
467     or die $dbh->errstr;
468   #map { $_->{TABLE_NAME} } grep { $_->{TABLE_TYPE} eq 'TABLE' }
469   #  @{ $sth->fetchall_arrayref({ TABLE_NAME=>1, TABLE_TYPE=>1}) };
470   map { $_->[0] } grep { $_->[1] =~ /^TABLE$/i }
471     @{ $sth->fetchall_arrayref([2,3]) };
472 }
473
474 =back
475
476 =head1 AUTHORS
477
478 Ivan Kohler <ivan-dbix-dbschema@420.am>
479
480 Charles Shapiro <charles.shapiro@numethods.com> and Mitchell Friedman
481 <mitchell.friedman@numethods.com> contributed the start of a Sybase driver.
482
483 Daniel Hanks <hanksdc@about-inc.com> contributed the Oracle driver.
484
485 Jesse Vincent contributed the SQLite driver.
486
487 =head1 CONTRIBUTIONS
488
489 Contributions are welcome!  I'm especially keen on any interest in the top
490 items/projects below under BUGS.
491
492 =head1 COPYRIGHT
493
494 Copyright (c) 2000-2007 Ivan Kohler
495 Copyright (c) 2000 Mail Abuse Prevention System LLC
496 Copyright (c) 2007 Freeside Internet Services, Inc.
497 All rights reserved.
498 This program is free software; you can redistribute it and/or modify it under
499 the same terms as Perl itself.
500
501 =head1 BUGS AND TODO
502
503 Multiple primary keys are not yet supported.
504
505 Foreign keys and other constraints are not yet supported.
506
507 Eventually it would be nice to have additional transformations (deleted,
508 modified columns, deleted tables).  sql_update_schema doesn't drop tables
509 or deal with deleted or modified columns yet.
510
511 Need to port and test with additional databases
512
513 Each DBIx::DBSchema object should have a name which corresponds to its name
514 within the SQL database engine (DBI data source).
515
516 pretty_print is actually pretty ugly.
517
518 pretty_print isn't so good about quoting values...  save/load is a much better
519 alternative to using pretty_print/pretty_read
520
521 pretty_read is pretty ugly too.
522
523 pretty_read should *not* create and pass in old-style unique/index indices
524 when nothing is given in the read.
525
526 Perhaps pretty_read should eval column types so that we can use DBI
527 qw(:sql_types) here instead of externally.
528
529 Need to support "using" index attribute in pretty_read and in reverse
530 engineering
531
532 perhaps we should just get rid of pretty_read entirely.  pretty_print is useful
533 for debugging, but pretty_read is pretty bunk.
534
535 sql CREATE TABLE output should convert integers
536 (i.e. use DBI qw(:sql_types);) to local types using DBI->type_info plus a hash
537 to fudge things
538
539 =head1 SEE ALSO
540
541 L<DBIx::DBSchema::Table>, L<DBIx::DBSchema::Index>,
542 L<DBIx::DBSchema::Column>, L<DBIx::DBSchema::DBD>,
543 L<DBIx::DBSchema::DBD::mysql>, L<DBIx::DBSchema::DBD::Pg>, L<FS::Record>,
544 L<DBI>
545
546 =cut
547
548 1;
549