1 package DBIx::Class::Version::Table;
2 use base 'DBIx::Class';
6 __PACKAGE__->load_components(qw/ Core/);
7 __PACKAGE__->table('dbix_class_schema_versions');
9 __PACKAGE__->add_columns
11 'data_type' => 'VARCHAR',
12 'is_auto_increment' => 0,
13 'default_value' => undef,
14 'is_foreign_key' => 0,
20 'data_type' => 'VARCHAR',
21 'is_auto_increment' => 0,
22 'default_value' => undef,
23 'is_foreign_key' => 0,
24 'name' => 'installed',
29 __PACKAGE__->set_primary_key('version');
31 package DBIx::Class::Version::TableCompat;
32 use base 'DBIx::Class';
33 __PACKAGE__->load_components(qw/ Core/);
34 __PACKAGE__->table('SchemaVersions');
36 __PACKAGE__->add_columns
38 'data_type' => 'VARCHAR',
41 'data_type' => 'VARCHAR',
44 __PACKAGE__->set_primary_key('Version');
46 package DBIx::Class::Version;
47 use base 'DBIx::Class::Schema';
51 __PACKAGE__->register_class('Table', 'DBIx::Class::Version::Table');
53 package DBIx::Class::VersionCompat;
54 use base 'DBIx::Class::Schema';
58 __PACKAGE__->register_class('TableCompat', 'DBIx::Class::Version::TableCompat');
61 # ---------------------------------------------------------------------------
65 DBIx::Class::Schema::Versioned - DBIx::Class::Schema plugin for Schema upgrades
69 package Library::Schema;
70 use base qw/DBIx::Class::Schema/;
71 # load Library::Schema::CD, Library::Schema::Book, Library::Schema::DVD
72 __PACKAGE__->load_classes(qw/CD Book DVD/);
74 __PACKAGE__->load_components(qw/+DBIx::Class::Schema::Versioned/);
75 __PACKAGE__->upgrade_directory('/path/to/upgrades/');
76 __PACKAGE__->backup_directory('/path/to/backups/');
81 This module is a component designed to extend L<DBIx::Class::Schema>
82 classes, to enable them to upgrade to newer schema layouts. To use this
83 module, you need to have called C<create_ddl_dir> on your Schema to
84 create your upgrade files to include with your delivery.
86 A table called I<dbix_class_schema_versions> is created and maintained by the
87 module. This contains two fields, 'Version' and 'Installed', which
88 contain each VERSION of your Schema, and the date+time it was installed.
90 The actual upgrade is called manually by calling C<upgrade> on your
91 schema object. Code is run at connect time to determine whether an
92 upgrade is needed, if so, a warning "Versions out of sync" is
95 So you'll probably want to write a script which generates your DDLs and diffs
96 and another which executes the upgrade.
98 NB: At the moment, only SQLite and MySQL are supported. This is due to
99 spotty behaviour in the SQL::Translator producers, please help us by
104 =head2 upgrade_directory
106 Use this to set the directory your upgrade files are stored in.
108 =head2 backup_directory
110 Use this to set the directory you want your backups stored in.
114 package DBIx::Class::Schema::Versioned;
118 use base 'DBIx::Class';
119 use POSIX 'strftime';
122 __PACKAGE__->mk_classdata('_filedata');
123 __PACKAGE__->mk_classdata('upgrade_directory');
124 __PACKAGE__->mk_classdata('backup_directory');
125 __PACKAGE__->mk_classdata('do_backup');
126 __PACKAGE__->mk_classdata('do_diff_on_init');
128 =head2 schema_version
130 Returns the current schema class' $VERSION; does -not- use $schema->VERSION
131 since that varies in results depending on if version.pm is installed, and if
132 so the perl or XS versions. If you want this to change, bug the version.pm
133 author to make vpp and vxs behave the same.
139 my $class = ref($self)||$self;
143 $version = ${"${class}::VERSION"};
148 =head2 get_db_version
150 Returns the version that your database is currently at. This is determined by the values in the
151 dbix_class_schema_versions table that $self->upgrade writes to.
157 my ($self, $rs) = @_;
159 my $vtable = $self->{vschema}->resultset('Table');
162 my $stamp = $vtable->get_column('installed')->max;
163 $version = $vtable->search({ installed => $stamp })->first->version;
170 my ($self, $rs) = @_;
173 $rs->search({ 1, 0 })->count;
175 return 0 if $@ || !defined $c;
182 This is an overwritable method which is called just before the upgrade, to
183 allow you to make a backup of the database. Per default this method attempts
184 to call C<< $self->storage->backup >>, to run the standard backup on each
187 This method should return the name of the backup file, if appropriate..
194 ## Make each ::DBI::Foo do this
195 $self->storage->backup($self->backup_directory());
198 # is this just a waste of time? if not then merge with DBI.pm
199 sub _create_db_to_schema_diff {
202 my %driver_to_db_map = (
206 my $db = $driver_to_db_map{$self->storage->dbh->{Driver}->{Name}};
208 print "Sorry, this is an unsupported DB\n";
212 eval 'require SQL::Translator "0.09"';
214 $self->throw_exception("SQL::Translator 0.09 required");
217 my $db_tr = SQL::Translator->new({
220 parser_args => { dbh => $self->storage->dbh }
223 $db_tr->producer($db);
224 my $dbic_tr = SQL::Translator->new;
225 $dbic_tr->parser('SQL::Translator::Parser::DBIx::Class');
226 $dbic_tr = $self->storage->configure_sqlt($dbic_tr, $db);
227 $dbic_tr->data($self);
228 $dbic_tr->producer($db);
230 $db_tr->schema->name('db_schema');
231 $dbic_tr->schema->name('dbic_schema');
233 # is this really necessary?
234 foreach my $tr ($db_tr, $dbic_tr) {
235 my $data = $tr->data;
236 $tr->parser->($tr, $$data);
239 my $diff = SQL::Translator::Diff::schema_diff($db_tr->schema, $db,
240 $dbic_tr->schema, $db,
241 { ignore_constraint_names => 1, ignore_index_names => 1, caseopt => 1 });
243 my $filename = $self->ddl_filename(
245 $self->upgrade_directory,
246 $self->schema_version,
250 if(!open($file, ">$filename"))
252 $self->throw_exception("Can't open $filename for writing ($!)");
258 print "WARNING: There may be differences between your DB and your DBIC schema. Please review and if necessary run the SQL in $filename to sync your DB.\n";
263 Call this to attempt to upgrade your database from the version it is at to the version
264 this DBIC schema is at.
266 It requires an SQL diff file to exist in $schema->upgrade_directory, normally you will
267 have created this using $schema->create_ddl_dir.
274 my $db_version = $self->get_db_version();
277 unless ($db_version) {
278 # set version in dbix_class_schema_versions table, can't actually upgrade as we don 't know what version the DB is at
279 $self->_create_db_to_schema_diff() if ($self->do_diff_on_init);
281 # create versions table and version row
282 $self->{vschema}->deploy;
283 $self->_set_db_version;
287 # db and schema at same version. do nothing
288 if ($db_version eq $self->schema_version) {
289 print "Upgrade not necessary\n";
293 # strangely the first time this is called can
294 # differ to subsequent times. so we call it
297 $self->storage->sqlt_type;
299 my $upgrade_file = $self->ddl_filename(
300 $self->storage->sqlt_type,
301 $self->upgrade_directory,
302 $self->schema_version,
306 unless (-f $upgrade_file) {
307 warn "Upgrade not possible, no upgrade file found ($upgrade_file), please create one\n";
311 # backup if necessary then apply upgrade
312 $self->_filedata($self->_read_sql_file($upgrade_file));
313 $self->backup() if($self->do_backup);
314 $self->txn_do(sub { $self->do_upgrade() });
316 # set row in dbix_class_schema_versions table
317 $self->_set_db_version;
320 sub _set_db_version {
323 my $vtable = $self->{vschema}->resultset('Table');
324 $vtable->create({ version => $self->schema_version,
325 installed => strftime("%Y-%m-%d %H:%M:%S", gmtime())
332 my $file = shift || return;
335 open $fh, "<$file" or warn("Can't open upgrade file, $file ($!)");
336 my @data = split(/\n/, join('', <$fh>));
337 @data = grep(!/^--/, @data);
338 @data = split(/;/, join('', @data));
340 @data = grep { $_ && $_ !~ /^-- / } @data;
341 @data = grep { $_ !~ /^(BEGIN TRANACTION|COMMIT)/m } @data;
347 This is an overwritable method used to run your upgrade. The freeform method
348 allows you to run your upgrade any way you please, you can call C<run_upgrade>
349 any number of times to run the actual SQL commands, and in between you can
350 sandwich your data upgrading. For example, first run all the B<CREATE>
351 commands, then migrate your data from old to new tables/formats, then
352 issue the DROP commands when you are finished.
354 Will run the whole file as it is by default.
362 ## overridable sub, per default just run all the commands.
363 $self->run_upgrade(qr/create/i);
364 $self->run_upgrade(qr/alter table .*? add/i);
365 $self->run_upgrade(qr/alter table .*? (?!drop)/i);
366 $self->run_upgrade(qr/alter table .*? drop/i);
367 $self->run_upgrade(qr/drop/i);
372 $self->run_upgrade(qr/create/i);
374 Runs a set of SQL statements matching a passed in regular expression. The
375 idea is that this method can be called any number of times from your
376 C<upgrade> method, running whichever commands you specify via the
377 regex in the parameter. Probably won't work unless called from the overridable
384 my ($self, $stm) = @_;
386 return unless ($self->_filedata);
387 my @statements = grep { $_ =~ $stm } @{$self->_filedata};
388 $self->_filedata([ grep { $_ !~ /$stm/i } @{$self->_filedata} ]);
392 $self->storage->debugobj->query_start($_) if $self->storage->debug;
393 $self->storage->dbh->do($_) or warn "SQL was:\n $_";
394 $self->storage->debugobj->query_end($_) if $self->storage->debug;
402 Overloaded method. This checks the DBIC schema version against the DB version and
403 warns if they are not the same or if the DB is unversioned. It also provides
404 compatibility between the old versions table (SchemaVersions) and the new one
405 (dbix_class_schema_versions).
407 To avoid the checks on connect, set the env var DBIC_NO_VERSION_CHECK. This can be
414 $self->next::method(@_);
422 $self->{vschema} = DBIx::Class::Version->connect(@{$self->storage->connect_info()});
423 my $vtable = $self->{vschema}->resultset('Table');
425 # check for legacy versions table and move to new if exists
426 my $vschema_compat = DBIx::Class::VersionCompat->connect(@{$self->storage->connect_info()});
427 unless ($self->_source_exists($vtable)) {
428 my $vtable_compat = $vschema_compat->resultset('TableCompat');
429 if ($self->_source_exists($vtable_compat)) {
430 $self->{vschema}->deploy;
431 map { $vtable->create({ installed => $_->Installed, version => $_->Version }) } $vtable_compat->all;
432 $self->storage->dbh->do("DROP TABLE " . $vtable_compat->result_source->from);
436 # useful when connecting from scripts etc
437 return if ($ENV{DBIC_NO_VERSION_CHECK});
439 my $pversion = $self->get_db_version();
441 if($pversion eq $self->schema_version)
443 # warn "This version is already installed\n";
449 warn "Your DB is currently unversioned. Please call upgrade on your schema to sync the DB.\n";
453 warn "Versions out of sync. This is " . $self->schema_version .
454 ", your database contains version $pversion, please call upgrade on your Schema.\n";
462 Jess Robinson <castaway@desert-island.demon.co.uk>
463 Luke Saunders <luke@shadowcatsystems.co.uk>
467 You may distribute this code under the same terms as Perl itself.