brainfart! 0.30
[DBIx-DBSchema.git] / DBSchema.pm
1 package DBIx::DBSchema;
2
3 use strict;
4 use vars qw(@ISA $VERSION);
5 #use Exporter;
6 use DBI;
7 use Storable;
8 use DBIx::DBSchema::_util qw(_load_driver);
9 use DBIx::DBSchema::Table;
10 use DBIx::DBSchema::Column;
11 use DBIx::DBSchema::ColGroup::Unique;
12 use DBIx::DBSchema::ColGroup::Index;
13
14 #@ISA = qw(Exporter);
15 @ISA = ();
16
17 $VERSION = "0.29";
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";
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, shift);
107   $dbh = DBI->connect( $dbh, @_ ) or die $DBI::errstr unless ref($dbh);
108   $proto->new(
109     map { new_odbc DBIx::DBSchema::Table $dbh, $_ } _tables_from_dbh($dbh)
110   );
111 }
112
113 =item new_native DATABASE_HANDLE | DATA_SOURCE USERNAME PASSWORD [ ATTR ]
114
115 Creates a new DBIx::DBSchema object from an existing data source, which can be
116 specified by passing an open DBI database handle, or by passing the DBI data
117 source name, username and password.  This uses database-native methods to read
118 the schema, and will preserve any non-portable column types.  The method is
119 only available if there is a DBIx::DBSchema::DBD for the corresponding database engine (currently, MySQL and PostgreSQL).
120
121 =cut
122
123 sub new_native {
124   my($proto, $dbh) = (shift, shift);
125   $dbh = DBI->connect( $dbh, @_ ) or die $DBI::errstr unless ref($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.
134
135 =cut
136
137 sub load {
138   my($proto,$file)=@_; #use $proto ?
139
140   my $self;
141
142   #first try Storable
143   eval { $self = Storable::retrieve($file); };
144
145   if ( $@ && $@ =~ /not.*storable/i ) { #then try FreezeThaw
146     eval "use FreezeThaw;";
147     die $@ if $@;
148     open(FILE,"<$file") or die "Can't open $file: $!";
149     my $string = join('',<FILE>);
150     close FILE or die "Can't close $file: $!";
151     ($self) = FreezeThaw::thaw($string);
152   }
153
154   $self;
155
156 }
157
158 =item save FILENAME
159
160 Saves a DBIx::DBSchema object to a file.
161
162 =cut
163
164 sub save {
165   #my($self, $file) = @_;
166   Storable::nstore(@_);
167 }
168
169 =item addtable TABLE_OBJECT
170
171 Adds the given DBIx::DBSchema::Table object to this DBIx::DBSchema.
172
173 =cut
174
175 sub addtable {
176   my($self,$table)=@_;
177   $self->{'tables'}->{$table->name} = $table; #check for dupliates?
178 }
179
180 =item tables 
181
182 Returns a list of the names of all tables.
183
184 =cut
185
186 sub tables {
187   my($self)=@_;
188   keys %{$self->{'tables'}};
189 }
190
191 =item table TABLENAME
192
193 Returns the specified DBIx::DBSchema::Table object.
194
195 =cut
196
197 sub table {
198   my($self,$table)=@_;
199   $self->{'tables'}->{$table};
200 }
201
202 =item sql [ DATABASE_HANDLE | DATA_SOURCE [ USERNAME PASSWORD [ ATTR ] ] ]
203
204 Returns a list of SQL `CREATE' statements for this schema.
205
206 The data source can be specified by passing an open DBI database handle, or by
207 passing the DBI data source name, username and password.  
208
209 Although the username and password are optional, it is best to call this method
210 with a database handle or data source including a valid username and password -
211 a DBI connection will be opened and the quoting and type mapping will be more
212 reliable.
213
214 If passed a DBI data source (or handle) such as `DBI:mysql:database' or
215 `DBI:Pg:dbname=database', will use syntax specific to that database engine.
216 Currently supported databases are MySQL and PostgreSQL.
217
218 If not passed a data source (or handle), or if there is no driver for the
219 specified database, will attempt to use generic SQL syntax.
220
221 =cut
222
223 sub sql {
224   my($self, $dbh) = (shift, shift);
225   my $created_dbh = 0;
226   unless ( ref($dbh) || ! @_ ) {
227     $dbh = DBI->connect( $dbh, @_ ) or die $DBI::errstr;
228     $created_dbh = 1;
229   }
230   my @r = map { $self->table($_)->sql_create_table($dbh); } $self->tables;
231   $dbh->disconnect if $created_dbh;
232   @r;
233 }
234
235 =item pretty_print
236
237 Returns the data in this schema as Perl source, suitable for assigning to a
238 hash.
239
240 =cut
241
242 sub pretty_print {
243   my($self) = @_;
244   join("},\n\n",
245     map {
246       my $table = $_;
247       "'$table' => {\n".
248         "  'columns' => [\n".
249           join("", map { 
250                          #cant because -w complains about , in qw()
251                          # (also biiiig problems with empty lengths)
252                          #"    qw( $_ ".
253                          #$self->table($table)->column($_)->type. " ".
254                          #( $self->table($table)->column($_)->null ? 'NULL' : 0 ). " ".
255                          #$self->table($table)->column($_)->length. " ),\n"
256                          "    '$_', ".
257                          "'". $self->table($table)->column($_)->type. "', ".
258                          "'". $self->table($table)->column($_)->null. "', ". 
259                          "'". $self->table($table)->column($_)->length. "', ".
260                          "'". $self->table($table)->column($_)->default. "', ".
261                          "'". $self->table($table)->column($_)->local. "',\n"
262                        } $self->table($table)->columns
263           ).
264         "  ],\n".
265         "  'primary_key' => '". $self->table($table)->primary_key. "',\n".
266         "  'unique' => [ ". join(', ',
267           map { "[ '". join("', '", @{$_}). "' ]" }
268             @{$self->table($table)->unique->lol_ref}
269           ).  " ],\n".
270         "  'index' => [ ". join(', ',
271           map { "[ '". join("', '", @{$_}). "' ]" }
272             @{$self->table($table)->index->lol_ref}
273           ). " ],\n"
274         #"  'index' => [ ".    " ],\n"
275     } $self->tables
276   ). "}\n";
277 }
278
279 =cut
280
281 =item pretty_read HASHREF
282
283 Creates a schema as specified by a data structure such as that created by
284 B<pretty_print> method.
285
286 =cut
287
288 sub pretty_read {
289   my($proto, $href) = @_;
290   my $schema = $proto->new( map {  
291     my(@columns);
292     while ( @{$href->{$_}{'columns'}} ) {
293       push @columns, DBIx::DBSchema::Column->new(
294         splice @{$href->{$_}{'columns'}}, 0, 6
295       );
296     }
297     DBIx::DBSchema::Table->new(
298       $_,
299       $href->{$_}{'primary_key'},
300       DBIx::DBSchema::ColGroup::Unique->new($href->{$_}{'unique'}),
301       DBIx::DBSchema::ColGroup::Index->new($href->{$_}{'index'}),
302       @columns,
303     );
304   } (keys %{$href}) );
305 }
306
307 # private subroutines
308
309 sub _tables_from_dbh {
310   my($dbh) = @_;
311   my $driver = _load_driver($dbh);
312   my $db_catalog =
313     scalar(eval "DBIx::DBSchema::DBD::$driver->default_db_catalog");
314   my $db_schema  =
315     scalar(eval "DBIx::DBSchema::DBD::$driver->default_db_schema");
316   my $sth = $dbh->table_info($db_catalog, $db_schema, '', 'TABLE')
317     or die $dbh->errstr;
318   #map { $_->{TABLE_NAME} } grep { $_->{TABLE_TYPE} eq 'TABLE' }
319   #  @{ $sth->fetchall_arrayref({ TABLE_NAME=>1, TABLE_TYPE=>1}) };
320   map { $_->[0] } grep { $_->[1] =~ /^TABLE$/i }
321     @{ $sth->fetchall_arrayref([2,3]) };
322 }
323
324 =back
325
326 =head1 AUTHORS
327
328 Ivan Kohler <ivan-dbix-dbschema@420.am>
329
330 Charles Shapiro <charles.shapiro@numethods.com> and Mitchell Friedman
331 <mitchell.friedman@numethods.com> contributed the start of a Sybase driver.
332
333 Daniel Hanks <hanksdc@about-inc.com> contributed the Oracle driver.
334
335 Jesse Vincent contributed the SQLite driver.
336
337 =head1 CONTRIBUTIONS
338
339 Contributions are welcome!  I'm especially keen on any interest in the first
340 three items/projects below under BUGS.
341
342 =head1 COPYRIGHT
343
344 Copyright (c) 2000-2006 Ivan Kohler
345 Copyright (c) 2000 Mail Abuse Prevention System LLC
346 All rights reserved.
347 This program is free software; you can redistribute it and/or modify it under
348 the same terms as Perl itself.
349
350 =head1 BUGS
351
352 Indices are not stored by name.  Index representation could use an overhaul.
353
354 Multiple primary keys are not yet supported.
355
356 Foreign keys and other constraints are not yet supported.
357
358 Eventually it would be nice to have additional transformations (deleted,
359 modified columns, added/modified/indices (probably need em named first),
360 added/deleted tables
361
362 Need to port and test with additional databases
363
364 Each DBIx::DBSchema object should have a name which corresponds to its name
365 within the SQL database engine (DBI data source).
366
367 pretty_print is actually pretty ugly.
368
369 Perhaps pretty_read should eval column types so that we can use DBI
370 qw(:sql_types) here instead of externally.
371
372 sql CREATE TABLE output should convert integers
373 (i.e. use DBI qw(:sql_types);) to local types using DBI->type_info plus a hash
374 to fudge things
375
376 =head1 SEE ALSO
377
378 L<DBIx::DBSchema::Table>, L<DBIx::DBSchema::ColGroup>,
379 L<DBIx::DBSchema::ColGroup::Unique>, L<DBIx::DBSchema::ColGroup::Index>,
380 L<DBIx::DBSchema::Column>, L<DBIx::DBSchema::DBD>,
381 L<DBIx::DBSchema::DBD::mysql>, L<DBIx::DBSchema::DBD::Pg>, L<FS::Record>,
382 L<DBI>
383
384 =cut
385
386 1;
387