1 package DBIx::DBSchema;
4 use vars qw(@ISA $VERSION);
8 use FreezeThaw qw(freeze thaw cmpStr);
9 use DBIx::DBSchema::Table;
10 use DBIx::DBSchema::Column;
11 use DBIx::DBSchema::ColGroup::Unique;
12 use DBIx::DBSchema::ColGroup::Index;
21 DBIx::DBSchema - Database-independent schema objects
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;
33 $schema->save("filename");
34 $schema = load DBIx::DBSchema "filename";
36 $schema->addtable($dbix_dbschema_table_object);
38 @table_names = $schema->tables;
40 $DBIx_DBSchema_table_object = $schema->table("table_name");
42 @sql = $schema->sql($dbh);
43 @sql = $schema->sql($dsn, $username, $password);
44 @sql = $schema->sql($dsn); #doesn't connect to database - less reliable
46 $perl_code = $schema->pretty_print;
47 %hash = eval $perl_code;
48 use DBI qw(:sql_types); $schema = pretty_read DBIx::DBSchema \%hash;
52 DBIx::DBSchema objects are collections of DBIx::DBSchema::Table objects and
53 represent a database schema.
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.
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".
70 =item new TABLE_OBJECT, TABLE_OBJECT, ...
72 Creates a new DBIx::DBSchema object.
77 my($proto, @tables) = @_;
78 my %tables = map { $_->name, $_ } @tables; #check for duplicates?
80 my $class = ref($proto) || $proto;
85 bless ($self, $class);
89 =item new_odbc DATABASE_HANDLE | DATA_SOURCE USERNAME PASSWORD [ ATTR ]
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.
104 my($proto, $dbh) = (shift, shift);
105 $dbh = DBI->connect( $dbh, @_ ) or die $DBI::errstr unless ref($dbh);
107 map { new_odbc DBIx::DBSchema::Table $dbh, $_ } _tables_from_dbh($dbh)
111 =item new_native DATABASE_HANDLE | DATA_SOURCE USERNAME PASSWORD [ ATTR ]
113 Creates a new DBIx::DBSchema object from an existing data source, which can be
114 specified by passing an open DBI database handle, or by passing the DBI data
115 source name, username and password. This uses database-native methods to read
116 the schema, and will preserve any non-portable column types. The method is
117 only available if there is a DBIx::DBSchema::DBD for the corresponding database engine (currently, MySQL and PostgreSQL).
122 my($proto, $dbh) = (shift, shift);
123 $dbh = DBI->connect( $dbh, @_ ) or die $DBI::errstr unless ref($dbh);
125 map { new_native DBIx::DBSchema::Table ( $dbh, $_ ) } _tables_from_dbh($dbh)
131 Loads a DBIx::DBSchema object from a file.
136 my($proto,$file)=@_; #use $proto ?
137 open(FILE,"<$file") or die "Can't open $file: $!";
138 my($string)=join('',<FILE>); #can $string have newlines? pry not?
139 close FILE or die "Can't close $file: $!";
140 my($self)=thaw $string;
147 Saves a DBIx::DBSchema object to a file.
153 my($string)=freeze $self;
154 open(FILE,">$file") or die "Can't open $file: $!";
156 close FILE or die "Can't close file: $!";
157 my($check_self)=thaw $string;
158 die "Verify error: Can't freeze and thaw dbdef $self"
159 if (cmpStr($self,$check_self));
162 =item addtable TABLE_OBJECT
164 Adds the given DBIx::DBSchema::Table object to this DBIx::DBSchema.
170 $self->{'tables'}->{$table->name} = $table; #check for dupliates?
175 Returns a list of the names of all tables.
181 keys %{$self->{'tables'}};
184 =item table TABLENAME
186 Returns the specified DBIx::DBSchema::Table object.
192 $self->{'tables'}->{$table};
195 =item sql [ DATABASE_HANDLE | DATA_SOURCE [ USERNAME PASSWORD [ ATTR ] ] ]
197 Returns a list of SQL `CREATE' statements for this schema.
199 The data source can be specified by passing an open DBI database handle, or by
200 passing the DBI data source name, username and password.
202 Although the username and password are optional, it is best to call this method
203 with a database handle or data source including a valid username and password -
204 a DBI connection will be opened and the quoting and type mapping will be more
207 If passed a DBI data source (or handle) such as `DBI:mysql:database' or
208 `DBI:Pg:dbname=database', will use syntax specific to that database engine.
209 Currently supported databases are MySQL and PostgreSQL.
211 If not passed a data source (or handle), or if there is no driver for the
212 specified database, will attempt to use generic SQL syntax.
217 my($self, $dbh) = (shift, shift);
219 unless ( ref($dbh) || ! @_ ) {
220 $dbh = DBI->connect( $dbh, @_ ) or die $DBI::errstr;
223 my @r = map { $self->table($_)->sql_create_table($dbh); } $self->tables;
224 $dbh->disconnect if $created_dbh;
230 Returns the data in this schema as Perl source, suitable for assigning to a
243 #cant because -w complains about , in qw()
244 # (also biiiig problems with empty lengths)
246 #$self->table($table)->column($_)->type. " ".
247 #( $self->table($table)->column($_)->null ? 'NULL' : 0 ). " ".
248 #$self->table($table)->column($_)->length. " ),\n"
250 "'". $self->table($table)->column($_)->type. "', ".
251 "'". $self->table($table)->column($_)->null. "', ".
252 "'". $self->table($table)->column($_)->length. "', ".
253 "'". $self->table($table)->column($_)->default. "', ".
254 "'". $self->table($table)->column($_)->local. "',\n"
255 } $self->table($table)->columns
258 " 'primary_key' => '". $self->table($table)->primary_key. "',\n".
259 " 'unique' => [ ". join(', ',
260 map { "[ '". join("', '", @{$_}). "' ]" }
261 @{$self->table($table)->unique->lol_ref}
263 " 'index' => [ ". join(', ',
264 map { "[ '". join("', '", @{$_}). "' ]" }
265 @{$self->table($table)->index->lol_ref}
267 #" 'index' => [ ". " ],\n"
274 =item pretty_read HASHREF
276 Creates a schema as specified by a data structure such as that created by
277 B<pretty_print> method.
282 my($proto, $href) = @_;
283 my $schema = $proto->new( map {
285 while ( @{$href->{$_}{'columns'}} ) {
286 push @columns, DBIx::DBSchema::Column->new(
287 splice @{$href->{$_}{'columns'}}, 0, 6
290 DBIx::DBSchema::Table->new(
292 $href->{$_}{'primary_key'},
293 DBIx::DBSchema::ColGroup::Unique->new($href->{$_}{'unique'}),
294 DBIx::DBSchema::ColGroup::Index->new($href->{$_}{'index'}),
300 # private subroutines
306 $driver = $dbh->{Driver}->{Name};
308 $dbh =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i #nicked from DBI->connect
309 or '' =~ /()/; # ensure $1 etc are empty if match fails
310 $driver = $1 or confess "can't parse data source: $dbh";
313 #require "DBIx/DBSchema/DBD/$driver.pm";
315 eval 'require "DBIx/DBSchema/DBD/$driver.pm"' and $driver;
318 sub _tables_from_dbh {
320 my $sth = $dbh->table_info or die $dbh->errstr;
321 #map { $_->{TABLE_NAME} } grep { $_->{TABLE_TYPE} eq 'TABLE' }
322 # @{ $sth->fetchall_arrayref({ TABLE_NAME=>1, TABLE_TYPE=>1}) };
323 map { $_->[0] } grep { $_->[1] =~ /^TABLE$/i }
324 @{ $sth->fetchall_arrayref([2,3]) };
331 Ivan Kohler <ivan-dbix-dbschema@420.am>
333 Charles Shapiro <charles.shapiro@numethods.com> and Mitchell Friedman
334 <mitchell.friedman@numethods.com> contributed the start of a Sybase driver.
338 Copyright (c) 2000 Ivan Kohler
339 Copyright (c) 2000 Mail Abuse Prevention System LLC
341 This program is free software; you can redistribute it and/or modify it under
342 the same terms as Perl itself.
346 Each DBIx::DBSchema object should have a name which corresponds to its name
347 within the SQL database engine (DBI data source).
349 pretty_print is actually pretty ugly.
351 Perhaps pretty_read should eval column types so that we can use DBI
352 qw(:sql_types) here instead of externally.
356 L<DBIx::DBSchema::Table>, L<DBIx::DBSchema::ColGroup>,
357 L<DBIx::DBSchema::ColGroup::Unique>, L<DBIx::DBSchema::ColGroup::Index>,
358 L<DBIx::DBSchema::Column>, L<DBIx::DBSchema::DBD>,
359 L<DBIx::DBSchema::DBD::mysql>, L<DBIx::DBSchema::DBD::Pg>, L<FS::Record>,