remove some debugging cruft, oops
[DBIx-DBSchema.git] / DBSchema.pm
1 package DBIx::DBSchema;
2
3 use strict;
4 use vars qw(@ISA $VERSION);
5 #use Exporter;
6 #use Carp qw(verbose);
7 use DBI;
8 use FreezeThaw qw(freeze thaw cmpStr);
9 use DBIx::DBSchema::Table;
10
11 #@ISA = qw(Exporter);
12 @ISA = ();
13
14 $VERSION = "0.1";
15
16 =head1 NAME
17
18 DBIx::DBSchema - Database-independent schema objects
19
20 =head1 SYNOPSIS
21
22   use DBIx::DBSchema;
23
24   $schema = new DBIx::DBSchema @dbix_dbschema_table_objects;
25   $schema = new_odbc DBIx::DBSchema $dbh;
26   $schema = new_odbc DBIx::DBSchema $dsn, $user, $pass;
27   $schema = new_native DBIx::DBSchema $dbh;
28   $schema = new_native DBIx::DBSchema $dsn, $user, $pass;
29
30   $schema->save("filename");
31   $schema = load DBIx::DBSchema "filename";
32
33   $schema->addtable($dbix_dbschema_table_object);
34
35   @table_names = $schema->tables;
36
37   $DBIx_DBSchema_table_object = $schema->table("table_name");
38
39   $sql_string = $schema->sql($dsn);
40
41   $perl_code = $schema->pretty_print;
42   %hash = eval $perl_code;
43   $schema = pretty_read DBIx::DBSchema \%hash;
44
45 =head1 DESCRIPTION
46
47 DBIx::DBSchema objects are collections of DBIx::DBSchema::Table objects and
48 represent a database schema.
49
50 =head1 METHODS
51
52 =over 4
53
54 =item new TABLE_OBJECT, TABLE_OBJECT, ...
55
56 Creates a new DBIx::DBSchema object.
57
58 =cut
59
60 sub new {
61   my($proto, @tables) = @_;
62   my %tables = map  { $_->name, $_ } @tables; #check for duplicates?
63
64   my $class = ref($proto) || $proto;
65   my $self = {
66     'tables' => \%tables,
67   };
68
69   bless ($self, $class);
70
71 }
72
73 =item new_odbc DATABASE_HANDLE || DATA_SOURCE USERNAME PASSWORD [ ATTR ]
74
75 Creates a new DBIx::DBSchema object from an existing data source, which can be
76 specified by passing an open DBI database handle, or by passing the DBI data
77 source name, username, and password.  This uses the experimental DBI type_info
78 method to create a schema with standard (ODBC) SQL column types that most
79 closely correspond to any non-portable column types.  Use this to import a
80 schema that you wish to use with many different database engines.  Although
81 primary key and (unique) index information will only be read from databases
82 with DBIx::DBSchema::DBD drivers (currently MySQL and PostgreSQL), import of
83 column names and attributes *should* work for any database.
84
85 =cut
86
87 sub new_odbc {
88   my($proto, $dbh) = (shift, shift);
89   $dbh = DBI->connect( $dbh, @_ ) or die $DBI::errstr unless ref($dbh);
90   $proto->new(
91     map { new_odbc DBIx::DBSchema::Table $dbh, $_ } _tables_from_dbh($dbh)
92   );
93 }
94
95 =item new_native DATABASE_HANDLE || DATA_SOURCE USERNAME PASSWORD [ ATTR ]
96
97 Creates a new DBIx::DBSchema object from an existing data source, which can be
98 specified by passing an open DBI database handle, or by passing the DBI data
99 source name, username and password.  This uses database-native methods to read
100 the schema, and will preserve any non-portable column types.  The method is
101 only available if there is a DBIx::DBSchema::DBD for the corresponding database engine (currently, MySQL and PostgreSQL).
102
103 =cut
104
105 sub new_native {
106   my($proto, $dbh) = (shift, shift);
107   $dbh = DBI->connect( $dbh, @_ ) or die $DBI::errstr unless ref($dbh);
108   $proto->new(
109     map { new_native DBIx::DBSchema::Table ( $dbh, $_ ) } _tables_from_dbh($dbh)
110   );
111 }
112
113 =item load FILENAME
114
115 Loads a DBIx::DBSchema object from a file.
116
117 =cut
118
119 sub load {
120   my($proto,$file)=@_; #use $proto ?
121   open(FILE,"<$file") or die "Can't open $file: $!";
122   my($string)=join('',<FILE>); #can $string have newlines?  pry not?
123   close FILE or die "Can't close $file: $!";
124   my($self)=thaw $string;
125   #no bless needed?
126   $self;
127 }
128
129 =item save FILENAME
130
131 Saves a DBIx::DBSchema object to a file.
132
133 =cut
134
135 sub save {
136   my($self,$file)=@_;
137   my($string)=freeze $self;
138   open(FILE,">$file") or die "Can't open $file: $!";
139   print FILE $string;
140   close FILE or die "Can't close file: $!";
141   my($check_self)=thaw $string;
142   die "Verify error: Can't freeze and thaw dbdef $self"
143     if (cmpStr($self,$check_self));
144 }
145
146 =item addtable TABLE_OBJECT
147
148 Adds the given DBIx::DBSchema::Table object to this DBIx::DBSchema.
149
150 =cut
151
152 sub addtable {
153   my($self,$table)=@_;
154   $self->{'tables'}->{$table->name} = $table; #check for dupliates?
155 }
156
157 =item tables 
158
159 Returns a list of the names of all tables.
160
161 =cut
162
163 sub tables {
164   my($self)=@_;
165   keys %{$self->{'tables'}};
166 }
167
168 =item table TABLENAME
169
170 Returns the specified DBIx::DBSchema::Table object.
171
172 =cut
173
174 sub table {
175   my($self,$table)=@_;
176   $self->{'tables'}->{$table};
177 }
178
179 =item sql_string [ DATASRC ]
180
181 Returns a list of SQL `CREATE' statements for this schema.
182
183 If passed a DBI data source such as `DBI:mysql:database' or
184 `DBI:Pg:dbname=database', will use syntax specific to that database engine.
185 Currently supported databases are MySQL and PostgreSQL.
186
187 If not passed a data source, or if there is no driver for the specified
188 database, will attempt to use generic SQL syntax.
189
190 =cut
191
192 sub sql_string {
193   my($self, $datasrc) = @_;
194   map { $self->table($_)->sql_create_table($datasrc); } $self->tables;
195 }
196
197 =item pretty_print
198
199 Returns the data in this schema as Perl source, suitable for assigning to a
200 hash.
201
202 =cut
203
204 sub pretty_print {
205   my($self) = @_;
206   join("},\n\n",
207     map {
208       my $table = $_;
209       "'$table' => {\n".
210         "  'columns' => [\n".
211           join("", map { 
212                          #cant because -w complains about , in qw()
213                          # (also biiiig problems with empty lengths)
214                          #"    qw( $_ ".
215                          #$self->table($table)->column($_)->type. " ".
216                          #( $self->table($table)->column($_)->null ? 'NULL' : 0 ). " ".
217                          #$self->table($table)->column($_)->length. " ),\n"
218                          "    '$_', ".
219                          "'". $self->table($table)->column($_)->type. "', ".
220                          "'". $self->table($table)->column($_)->null. "', ". 
221                          "'". $self->table($table)->column($_)->length. "'\n"
222                        } $self->table($table)->columns
223           ).
224         "  ],\n".
225         "  'primary_key' => '". $self->table($table)->primary_key. "',\n".
226         "  'unique' => [ ". join(', ',
227           map { "[ '". join("', '", @{$_}). "' ]" }
228             @{$self->table($table)->unique->lol_ref}
229           ).  " ],\n".
230         "  'index' => [ ". join(', ',
231           map { "[ '". join("', '", @{$_}). "' ]" }
232             @{$self->table($table)->index->lol_ref}
233           ). " ],\n"
234         #"  'index' => [ ".    " ],\n"
235     } $self->tables
236   ), "}\n";
237 }
238
239 =cut
240
241 =item pretty_read HASHREF
242
243 Creates a schema as specified by a data structure such as that created by
244 B<pretty_print> method.
245
246 =cut
247
248 sub pretty_read {
249   die "unimplemented (pull from fs-setup)";
250   my($proto) = @_;
251 }
252
253 # private subroutines
254
255 sub _load_driver {
256   my($dbh) = @_;
257   my $driver = $dbh->{Driver}->{Name};
258   #require "DBIx/DBSchema/DBD/$driver.pm";
259   #$driver;
260   eval 'require "DBIx/DBSchema/DBD/$driver.pm"' and $driver;
261 }
262
263 sub _tables_from_dbh {
264   my($dbh) = @_;
265   my $sth = $dbh->table_info or die $dbh->errstr;
266   #map { $_->{TABLE_NAME} } grep { $_->{TABLE_TYPE} eq 'TABLE' }
267   #  @{ $sth->fetchall_arrayref({ TABLE_NAME=>1, TABLE_TYPE=>1}) };
268   map { $_->[0] } grep { $_->[1] =~ /^TABLE$/i }
269     @{ $sth->fetchall_arrayref([2,3]) };
270 }
271
272 =back
273
274 =head1 AUTHOR
275
276 Ivan Kohler <ivan-dbix-dbschema@420.am>
277
278 =head1 COPYRIGHT
279
280 Copyright (c) 2000 Ivan Kohler
281 Copyright (c) 2000 Mail Abuse Prevention System LLC
282 All rights reserved.
283 This program is free software; you can redistribute it and/or modify it under
284 the same terms as Perl itself.
285
286 =head1 BUGS
287
288 Each DBIx::DBSchema object should have a name which corresponds to its name
289 within the SQL database engine (DBI data source).
290
291 pretty_print is actually pretty ugly.
292
293 =head1 SEE ALSO
294
295 L<DBIx::DBSchema::Table>, L<DBIx::DBSchema::ColGroup>,
296 L<DBIx::DBSchema::ColGroup::Unique>, L<DBIx::DBSchema::ColGroup::Index>,
297 L<DBIx::DBSchema::Column>, L<DBIx::DBSchema::DBD>, L<DBIx::DBSchema::mysql>,
298 L<DBIx::DBSchema::Pg>, L<FS::Record>, L<DBI>
299
300 =cut
301
302 1;
303