better error reporting for schema load failures, hopefully...
[DBIx-DBSchema.git] / DBSchema.pm
1 package DBIx::DBSchema;
2
3 use strict;
4 use vars qw(@ISA $VERSION $DEBUG $errstr);
5 #use Exporter;
6 use Storable;
7 use DBIx::DBSchema::_util qw(_load_driver _dbh);
8 use DBIx::DBSchema::Table 0.03;
9 use DBIx::DBSchema::Column;
10 use DBIx::DBSchema::ColGroup::Unique;
11 use DBIx::DBSchema::ColGroup::Index;
12
13 #@ISA = qw(Exporter);
14 @ISA = ();
15
16 $VERSION = "0.32";
17 $DEBUG = 0;
18
19 =head1 NAME
20
21 DBIx::DBSchema - Database-independent schema objects
22
23 =head1 SYNOPSIS
24
25   use DBIx::DBSchema;
26
27   $schema = new DBIx::DBSchema @dbix_dbschema_table_objects;
28   $schema = new_odbc DBIx::DBSchema $dbh;
29   $schema = new_odbc DBIx::DBSchema $dsn, $user, $pass;
30   $schema = new_native DBIx::DBSchema $dbh;
31   $schema = new_native DBIx::DBSchema $dsn, $user, $pass;
32
33   $schema->save("filename");
34   $schema = load DBIx::DBSchema "filename" or die $DBIx::DBSchema::errstr;
35
36   $schema->addtable($dbix_dbschema_table_object);
37
38   @table_names = $schema->tables;
39
40   $DBIx_DBSchema_table_object = $schema->table("table_name");
41
42   @sql = $schema->sql($dbh);
43   @sql = $schema->sql($dsn, $username, $password);
44   @sql = $schema->sql($dsn); #doesn't connect to database - less reliable
45
46   $perl_code = $schema->pretty_print;
47   %hash = eval $perl_code;
48   use DBI qw(:sql_types); $schema = pretty_read DBIx::DBSchema \%hash;
49
50 =head1 DESCRIPTION
51
52 DBIx::DBSchema objects are collections of DBIx::DBSchema::Table objects and
53 represent a database schema.
54
55 This module implements an OO-interface to database schemas.  Using this module,
56 you can create a database schema with an OO Perl interface.  You can read the
57 schema from an existing database.  You can save the schema to disk and restore
58 it a different process.  Most importantly, DBIx::DBSchema can write SQL
59 CREATE statements statements for different databases from a single source.
60
61 Currently supported databases are MySQL and PostgreSQL.  Sybase support is
62 partially implemented.  DBIx::DBSchema will attempt to use generic SQL syntax
63 for other databases.  Assistance adding support for other databases is
64 welcomed.  See L<DBIx::DBSchema::DBD>, "Driver Writer's Guide and Base Class".
65
66 =head1 METHODS
67
68 =over 4
69
70 =item new TABLE_OBJECT, TABLE_OBJECT, ...
71
72 Creates a new DBIx::DBSchema object.
73
74 =cut
75
76 sub new {
77   my($proto, @tables) = @_;
78   my %tables = map  { $_->name, $_ } @tables; #check for duplicates?
79
80   my $class = ref($proto) || $proto;
81   my $self = {
82     'tables' => \%tables,
83   };
84
85   bless ($self, $class);
86
87 }
88
89 =item new_odbc DATABASE_HANDLE | DATA_SOURCE USERNAME PASSWORD [ ATTR ]
90
91 Creates a new DBIx::DBSchema object from an existing data source, which can be
92 specified by passing an open DBI database handle, or by passing the DBI data
93 source name, username, and password.  This uses the experimental DBI type_info
94 method to create a schema with standard (ODBC) SQL column types that most
95 closely correspond to any non-portable column types.  Use this to import a
96 schema that you wish to use with many different database engines.  Although
97 primary key and (unique) index information will only be read from databases
98 with DBIx::DBSchema::DBD drivers (currently MySQL and PostgreSQL), import of
99 column names and attributes *should* work for any database.  Note that this
100 method only uses "ODBC" column types; it does not require or use an ODBC
101 driver.
102
103 =cut
104
105 sub new_odbc {
106   my($proto, $dbh) = ( shift, _dbh(@_) );
107   $proto->new(
108     map { new_odbc DBIx::DBSchema::Table $dbh, $_ } _tables_from_dbh($dbh)
109   );
110 }
111
112 =item new_native DATABASE_HANDLE | DATA_SOURCE USERNAME PASSWORD [ ATTR ]
113
114 Creates a new DBIx::DBSchema object from an existing data source, which can be
115 specified by passing an open DBI database handle, or by passing the DBI data
116 source name, username and password.  This uses database-native methods to read
117 the schema, and will preserve any non-portable column types.  The method is
118 only available if there is a DBIx::DBSchema::DBD for the corresponding database engine (currently, MySQL and PostgreSQL).
119
120 =cut
121
122 sub new_native {
123   my($proto, $dbh) = (shift, _dbh(@_) );
124   $proto->new(
125     map { new_native DBIx::DBSchema::Table ( $dbh, $_ ) } _tables_from_dbh($dbh)
126   );
127 }
128
129 =item load FILENAME
130
131 Loads a DBIx::DBSchema object from a file.  If there is an error, returns
132 false and puts an error message in $DBIx::DBSchema::errstr;
133
134 =cut
135
136 sub load {
137   my($proto,$file)=@_; #use $proto ?
138
139   my $self;
140
141   #first try Storable
142   eval { $self = Storable::retrieve($file); };
143
144   if ( $@ && $@ =~ /not.*storable/i ) { #then try FreezeThaw
145     my $olderror = $@;
146
147     eval "use FreezeThaw;";
148     if ( $@ ) {
149       $@ = $olderror;
150     } else { 
151       open(FILE,"<$file")
152         or do { $errstr = "Can't open $file: $!"; return ''; };
153       my $string = join('',<FILE>);
154       close FILE
155         or do { $errstr = "Can't close $file: $!"; return ''; };
156       ($self) = FreezeThaw::thaw($string);
157     }
158   }
159
160   unless ( $self ) {
161     $errstr = $@;
162   }
163
164   $self;
165
166 }
167
168 =item save FILENAME
169
170 Saves a DBIx::DBSchema object to a file.
171
172 =cut
173
174 sub save {
175   #my($self, $file) = @_;
176   Storable::nstore(@_);
177 }
178
179 =item addtable TABLE_OBJECT
180
181 Adds the given DBIx::DBSchema::Table object to this DBIx::DBSchema.
182
183 =cut
184
185 sub addtable {
186   my($self,$table)=@_;
187   $self->{'tables'}->{$table->name} = $table; #check for dupliates?
188 }
189
190 =item tables 
191
192 Returns a list of the names of all tables.
193
194 =cut
195
196 sub tables {
197   my($self)=@_;
198   keys %{$self->{'tables'}};
199 }
200
201 =item table TABLENAME
202
203 Returns the specified DBIx::DBSchema::Table object.
204
205 =cut
206
207 sub table {
208   my($self,$table)=@_;
209   $self->{'tables'}->{$table};
210 }
211
212 =item sql [ DATABASE_HANDLE | DATA_SOURCE [ USERNAME PASSWORD [ ATTR ] ] ]
213
214 Returns a list of SQL `CREATE' statements for this schema.
215
216 The data source can be specified by passing an open DBI database handle, or by
217 passing the DBI data source name, username and password.  
218
219 Although the username and password are optional, it is best to call this method
220 with a database handle or data source including a valid username and password -
221 a DBI connection will be opened and the quoting and type mapping will be more
222 reliable.
223
224 If passed a DBI data source (or handle) such as `DBI:mysql:database' or
225 `DBI:Pg:dbname=database', will use syntax specific to that database engine.
226 Currently supported databases are MySQL and PostgreSQL.
227
228 If not passed a data source (or handle), or if there is no driver for the
229 specified database, will attempt to use generic SQL syntax.
230
231 =cut
232
233 sub sql {
234   my($self, $dbh) = ( shift, _dbh(@_) );
235   map { $self->table($_)->sql_create_table($dbh); } $self->tables;
236 }
237
238 =item sql_update_schema PROTOTYPE_SCHEMA [ DATABASE_HANDLE | DATA_SOURCE [ USERNAME PASSWORD [ ATTR ] ] ]
239
240 Returns a list of SQL statements to update this schema so that it is idential
241 to the provided prototype schema, also a DBIx::DBSchema object.
242
243  #Optionally, the data source can be specified by passing an open DBI database
244  #handle, or by passing the DBI data source name, username and password.  
245  #
246  #If passed a DBI data source (or handle) such as `DBI:mysql:database' or
247  #`DBI:Pg:dbname=database', will use syntax specific to that database engine.
248  #Currently supported databases are MySQL and PostgreSQL.
249  #
250  #If not passed a data source (or handle), or if there is no driver for the
251  #specified database, will attempt to use generic SQL syntax.
252
253 Right now this method knows how to add new tables and alter existing tables.
254 It doesn't know how to drop tables yet.
255
256 See L<DBIx::DBSchema::Table/sql_alter_table>,
257 L<DBIx::DBSchema::Column/sql_add_coumn> and
258 L<DBIx::DBSchema::Column/sql_alter_column> for additional specifics and
259 limitations.
260
261 =cut
262
263 #gosh, false laziness w/DBSchema::Table::sql_alter_schema
264
265 sub sql_update_schema {
266   my($self, $new, $dbh) = ( shift, shift, _dbh(@_) );
267
268   my @r = ();
269
270   foreach my $table ( $new->tables ) {
271   
272     if ( $self->table($table) ) {
273   
274       warn "$table exists\n" if $DEBUG > 1;
275
276       push @r,
277         $self->table($table)->sql_alter_table( $new->table($table), $dbh );
278
279     } else {
280   
281       warn "table $table does not exist.\n" if $DEBUG;
282
283       push @r, 
284         $new->table($table)->sql_create_table( $dbh );
285   
286     }
287   
288   }
289
290   # should eventually drop tables not in $new
291
292   warn join("\n", @r). "\n"
293     if $DEBUG;
294
295   @r;
296   
297 }
298
299 =item update_schema PROTOTYPE_SCHEMA, DATABASE_HANDLE | DATA_SOURCE [ USERNAME PASSWORD [ ATTR ] ]
300
301 Same as sql_update_schema, except actually runs the SQL commands to update
302 the schema.  Throws a fatal error if any statement fails.
303
304 =cut
305
306 sub update_schema {
307   my($self, $new, $dbh) = ( shift, shift, _dbh(@_) );
308
309   foreach my $statement ( $self->sql_update_schema( $new, $dbh ) ) {
310     $dbh->do( $statement )
311       or die "Error: ". $dbh->errstr. "\n executing: $statement";
312   }
313
314 }
315
316 =item pretty_print
317
318 Returns the data in this schema as Perl source, suitable for assigning to a
319 hash.
320
321 =cut
322
323 sub pretty_print {
324   my($self) = @_;
325   join("},\n\n",
326     map {
327       my $table = $_;
328       "'$table' => {\n".
329         "  'columns' => [\n".
330           join("", map { 
331                          #cant because -w complains about , in qw()
332                          # (also biiiig problems with empty lengths)
333                          #"    qw( $_ ".
334                          #$self->table($table)->column($_)->type. " ".
335                          #( $self->table($table)->column($_)->null ? 'NULL' : 0 ). " ".
336                          #$self->table($table)->column($_)->length. " ),\n"
337                          "    '$_', ".
338                          "'". $self->table($table)->column($_)->type. "', ".
339                          "'". $self->table($table)->column($_)->null. "', ". 
340                          "'". $self->table($table)->column($_)->length. "', ".
341                          "'". $self->table($table)->column($_)->default. "', ".
342                          "'". $self->table($table)->column($_)->local. "',\n"
343                        } $self->table($table)->columns
344           ).
345         "  ],\n".
346         "  'primary_key' => '". $self->table($table)->primary_key. "',\n".
347         "  'unique' => [ ". join(', ',
348           map { "[ '". join("', '", @{$_}). "' ]" }
349             @{$self->table($table)->unique->lol_ref}
350           ).  " ],\n".
351         "  'index' => [ ". join(', ',
352           map { "[ '". join("', '", @{$_}). "' ]" }
353             @{$self->table($table)->index->lol_ref}
354           ). " ],\n"
355         #"  'index' => [ ".    " ],\n"
356     } $self->tables
357   ). "}\n";
358 }
359
360 =cut
361
362 =item pretty_read HASHREF
363
364 Creates a schema as specified by a data structure such as that created by
365 B<pretty_print> method.
366
367 =cut
368
369 sub pretty_read {
370   my($proto, $href) = @_;
371   my $schema = $proto->new( map {  
372     my(@columns);
373     while ( @{$href->{$_}{'columns'}} ) {
374       push @columns, DBIx::DBSchema::Column->new(
375         splice @{$href->{$_}{'columns'}}, 0, 6
376       );
377     }
378     DBIx::DBSchema::Table->new(
379       $_,
380       $href->{$_}{'primary_key'},
381       DBIx::DBSchema::ColGroup::Unique->new($href->{$_}{'unique'}),
382       DBIx::DBSchema::ColGroup::Index->new($href->{$_}{'index'}),
383       @columns,
384     );
385   } (keys %{$href}) );
386 }
387
388 # private subroutines
389
390 sub _tables_from_dbh {
391   my($dbh) = @_;
392   my $driver = _load_driver($dbh);
393   my $db_catalog =
394     scalar(eval "DBIx::DBSchema::DBD::$driver->default_db_catalog");
395   my $db_schema  =
396     scalar(eval "DBIx::DBSchema::DBD::$driver->default_db_schema");
397   my $sth = $dbh->table_info($db_catalog, $db_schema, '', 'TABLE')
398     or die $dbh->errstr;
399   #map { $_->{TABLE_NAME} } grep { $_->{TABLE_TYPE} eq 'TABLE' }
400   #  @{ $sth->fetchall_arrayref({ TABLE_NAME=>1, TABLE_TYPE=>1}) };
401   map { $_->[0] } grep { $_->[1] =~ /^TABLE$/i }
402     @{ $sth->fetchall_arrayref([2,3]) };
403 }
404
405 =back
406
407 =head1 AUTHORS
408
409 Ivan Kohler <ivan-dbix-dbschema@420.am>
410
411 Charles Shapiro <charles.shapiro@numethods.com> and Mitchell Friedman
412 <mitchell.friedman@numethods.com> contributed the start of a Sybase driver.
413
414 Daniel Hanks <hanksdc@about-inc.com> contributed the Oracle driver.
415
416 Jesse Vincent contributed the SQLite driver.
417
418 =head1 CONTRIBUTIONS
419
420 Contributions are welcome!  I'm especially keen on any interest in the first
421 three items/projects below under BUGS.
422
423 =head1 COPYRIGHT
424
425 Copyright (c) 2000-2006 Ivan Kohler
426 Copyright (c) 2000 Mail Abuse Prevention System LLC
427 All rights reserved.
428 This program is free software; you can redistribute it and/or modify it under
429 the same terms as Perl itself.
430
431 =head1 BUGS
432
433 Indices are not stored by name.  Index representation could use an overhaul.
434
435 Multiple primary keys are not yet supported.
436
437 Foreign keys and other constraints are not yet supported.
438
439 Eventually it would be nice to have additional transformations (deleted,
440 modified columns, added/modified/indices (probably need em named first),
441 added/deleted tables
442
443 Need to port and test with additional databases
444
445 Each DBIx::DBSchema object should have a name which corresponds to its name
446 within the SQL database engine (DBI data source).
447
448 pretty_print is actually pretty ugly.
449
450 Perhaps pretty_read should eval column types so that we can use DBI
451 qw(:sql_types) here instead of externally.
452
453 sql CREATE TABLE output should convert integers
454 (i.e. use DBI qw(:sql_types);) to local types using DBI->type_info plus a hash
455 to fudge things
456
457 sql_update_schema doesn't drop tables yet.
458
459 =head1 SEE ALSO
460
461 L<DBIx::DBSchema::Table>, L<DBIx::DBSchema::ColGroup>,
462 L<DBIx::DBSchema::ColGroup::Unique>, L<DBIx::DBSchema::ColGroup::Index>,
463 L<DBIx::DBSchema::Column>, L<DBIx::DBSchema::DBD>,
464 L<DBIx::DBSchema::DBD::mysql>, L<DBIx::DBSchema::DBD::Pg>, L<FS::Record>,
465 L<DBI>
466
467 =cut
468
469 1;
470