adding DBD::Pg and DBIx::DBSchema for 5.005. argh freebsd and solaris!
[freeside.git] / install / 5.005 / DBIx-DBSchema-0.23-5.005kludge / DBSchema.pm
1 package DBIx::DBSchema;
2
3 use strict;
4 use vars qw(@ISA $VERSION);
5 #use Exporter;
6 use Carp qw(confess);
7 use DBI;
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;
13
14 #@ISA = qw(Exporter);
15 @ISA = ();
16
17 $VERSION = "0.23";
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   open(FILE,"<$file") or die "Can't open $file: $!";
140   my($string)=join('',<FILE>); #can $string have newlines?  pry not?
141   close FILE or die "Can't close $file: $!";
142   my($self)=thaw $string;
143   #no bless needed?
144   $self;
145 }
146
147 =item save FILENAME
148
149 Saves a DBIx::DBSchema object to a file.
150
151 =cut
152
153 sub save {
154   my($self,$file)=@_;
155   my($string)=freeze $self;
156   open(FILE,">$file") or die "Can't open $file: $!";
157   print FILE $string;
158   close FILE or die "Can't close file: $!";
159   my($check_self)=thaw $string;
160   die "Verify error: Can't freeze and thaw dbdef $self"
161     if (cmpStr($self,$check_self));
162 }
163
164 =item addtable TABLE_OBJECT
165
166 Adds the given DBIx::DBSchema::Table object to this DBIx::DBSchema.
167
168 =cut
169
170 sub addtable {
171   my($self,$table)=@_;
172   $self->{'tables'}->{$table->name} = $table; #check for dupliates?
173 }
174
175 =item tables 
176
177 Returns a list of the names of all tables.
178
179 =cut
180
181 sub tables {
182   my($self)=@_;
183   keys %{$self->{'tables'}};
184 }
185
186 =item table TABLENAME
187
188 Returns the specified DBIx::DBSchema::Table object.
189
190 =cut
191
192 sub table {
193   my($self,$table)=@_;
194   $self->{'tables'}->{$table};
195 }
196
197 =item sql [ DATABASE_HANDLE | DATA_SOURCE [ USERNAME PASSWORD [ ATTR ] ] ]
198
199 Returns a list of SQL `CREATE' statements for this schema.
200
201 The data source can be specified by passing an open DBI database handle, or by
202 passing the DBI data source name, username and password.  
203
204 Although the username and password are optional, it is best to call this method
205 with a database handle or data source including a valid username and password -
206 a DBI connection will be opened and the quoting and type mapping will be more
207 reliable.
208
209 If passed a DBI data source (or handle) such as `DBI:mysql:database' or
210 `DBI:Pg:dbname=database', will use syntax specific to that database engine.
211 Currently supported databases are MySQL and PostgreSQL.
212
213 If not passed a data source (or handle), or if there is no driver for the
214 specified database, will attempt to use generic SQL syntax.
215
216 =cut
217
218 sub sql {
219   my($self, $dbh) = (shift, shift);
220   my $created_dbh = 0;
221   unless ( ref($dbh) || ! @_ ) {
222     $dbh = DBI->connect( $dbh, @_ ) or die $DBI::errstr;
223     $created_dbh = 1;
224   }
225   my @r = map { $self->table($_)->sql_create_table($dbh); } $self->tables;
226   $dbh->disconnect if $created_dbh;
227   @r;
228 }
229
230 =item pretty_print
231
232 Returns the data in this schema as Perl source, suitable for assigning to a
233 hash.
234
235 =cut
236
237 sub pretty_print {
238   my($self) = @_;
239   join("},\n\n",
240     map {
241       my $table = $_;
242       "'$table' => {\n".
243         "  'columns' => [\n".
244           join("", map { 
245                          #cant because -w complains about , in qw()
246                          # (also biiiig problems with empty lengths)
247                          #"    qw( $_ ".
248                          #$self->table($table)->column($_)->type. " ".
249                          #( $self->table($table)->column($_)->null ? 'NULL' : 0 ). " ".
250                          #$self->table($table)->column($_)->length. " ),\n"
251                          "    '$_', ".
252                          "'". $self->table($table)->column($_)->type. "', ".
253                          "'". $self->table($table)->column($_)->null. "', ". 
254                          "'". $self->table($table)->column($_)->length. "', ".
255                          "'". $self->table($table)->column($_)->default. "', ".
256                          "'". $self->table($table)->column($_)->local. "',\n"
257                        } $self->table($table)->columns
258           ).
259         "  ],\n".
260         "  'primary_key' => '". $self->table($table)->primary_key. "',\n".
261         "  'unique' => [ ". join(', ',
262           map { "[ '". join("', '", @{$_}). "' ]" }
263             @{$self->table($table)->unique->lol_ref}
264           ).  " ],\n".
265         "  'index' => [ ". join(', ',
266           map { "[ '". join("', '", @{$_}). "' ]" }
267             @{$self->table($table)->index->lol_ref}
268           ). " ],\n"
269         #"  'index' => [ ".    " ],\n"
270     } $self->tables
271   ), "}\n";
272 }
273
274 =cut
275
276 =item pretty_read HASHREF
277
278 Creates a schema as specified by a data structure such as that created by
279 B<pretty_print> method.
280
281 =cut
282
283 sub pretty_read {
284   my($proto, $href) = @_;
285   my $schema = $proto->new( map {  
286     my(@columns);
287     while ( @{$href->{$_}{'columns'}} ) {
288       push @columns, DBIx::DBSchema::Column->new(
289         splice @{$href->{$_}{'columns'}}, 0, 6
290       );
291     }
292     DBIx::DBSchema::Table->new(
293       $_,
294       $href->{$_}{'primary_key'},
295       DBIx::DBSchema::ColGroup::Unique->new($href->{$_}{'unique'}),
296       DBIx::DBSchema::ColGroup::Index->new($href->{$_}{'index'}),
297       @columns,
298     );
299   } (keys %{$href}) );
300 }
301
302 # private subroutines
303
304 sub _load_driver {
305   my($dbh) = @_;
306   my $driver;
307   if ( ref($dbh) ) {
308     $driver = $dbh->{Driver}->{Name};
309   } else {
310     $dbh =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i #nicked from DBI->connect
311                         or '' =~ /()/; # ensure $1 etc are empty if match fails
312     $driver = $1 or confess "can't parse data source: $dbh";
313   }
314
315   #require "DBIx/DBSchema/DBD/$driver.pm";
316   #$driver;
317   eval 'require "DBIx/DBSchema/DBD/$driver.pm"' and $driver or die $@;
318 }
319
320 sub _tables_from_dbh {
321   my($dbh) = @_;
322   my $sth = $dbh->table_info or die $dbh->errstr;
323   #map { $_->{TABLE_NAME} } grep { $_->{TABLE_TYPE} eq 'TABLE' }
324   #  @{ $sth->fetchall_arrayref({ TABLE_NAME=>1, TABLE_TYPE=>1}) };
325   map { $_->[0] } grep { $_->[1] =~ /^TABLE$/i }
326     @{ $sth->fetchall_arrayref([2,3]) };
327 }
328
329 =back
330
331 =head1 AUTHOR
332
333 Ivan Kohler <ivan-dbix-dbschema@420.am>
334
335 Charles Shapiro <charles.shapiro@numethods.com> and Mitchell Friedman
336 <mitchell.friedman@numethods.com> contributed the start of a Sybase driver.
337
338 =head1 COPYRIGHT
339
340 Copyright (c) 2000 Ivan Kohler
341 Copyright (c) 2000 Mail Abuse Prevention System LLC
342 All rights reserved.
343 This program is free software; you can redistribute it and/or modify it under
344 the same terms as Perl itself.
345
346 =head1 BUGS
347
348 Each DBIx::DBSchema object should have a name which corresponds to its name
349 within the SQL database engine (DBI data source).
350
351 pretty_print is actually pretty ugly.
352
353 Perhaps pretty_read should eval column types so that we can use DBI
354 qw(:sql_types) here instead of externally.
355
356 =head1 SEE ALSO
357
358 L<DBIx::DBSchema::Table>, L<DBIx::DBSchema::ColGroup>,
359 L<DBIx::DBSchema::ColGroup::Unique>, L<DBIx::DBSchema::ColGroup::Index>,
360 L<DBIx::DBSchema::Column>, L<DBIx::DBSchema::DBD>,
361 L<DBIx::DBSchema::DBD::mysql>, L<DBIx::DBSchema::DBD::Pg>, L<FS::Record>,
362 L<DBI>
363
364 =cut
365
366 1;
367