Jifty/Script/Schema.pm

filter: Statementstmt 100% 9 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 100% 12 / 12 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Jifty/Manual.pm ↑ Summary
1 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
2 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 package Jifty::Script::Schema;
5 1 ▶use base qw/Jifty::Script/;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 use version;
8 use Jifty::DBI::SchemaGenerator;
9 use Jifty::Config;
10 use Jifty::Schema;
11  
12 =head1 NAME
13  
14 Jifty::Script::Schema - Create SQL to update or create your Jifty application's tables
15  
16 =head1 SYNOPSIS
17  
18 jifty schema --setup Creates or updates your application's database tables
19  
20 Options:
21 --print Print SQL, rather than executing commands
22  
23 --setup Upgrade or install the database, creating it if need be
24 --create-database Only creates the database
25 --drop-database Drops the database
26 --ignore-reserved-words Ignore any SQL reserved words in schema definition
27 --no-bootstrap don't run bootstrap
28  
29 --help brief help message
30 --man full documentation
31  
32 =head1 DESCRIPTION
33  
34 Manages your database.
35  
36 =head2 options
37  
38 =over 8
39  
40 =item B<--print>
41  
42 Rather than actually running the database create/update/drop commands,
43 Prints the commands to standard output
44  
45 =item B<--create-database>
46  
47 Send a CREATE DATABASE command. Note that B<--setup>, below, will
48 automatically send a CREATE DATABASE if it needs one. This option is
49 useful if you wish to create the database without creating any tables
50 in it.
51  
52 =item B<--drop-database>
53  
54 Send a DROP DATABASE command. Use this in conjunction with B<--setup>
55 to wipe and re-install the database.
56  
57 =item B<--setup>
58  
59 Actually set up your app's tables. This creates the database if need
60 be, and runs any commands needed to bring the tables up to date; these
61 may include CREATE TABLE or ALTER TABLE commands. This option is
62 assumed if the database does not exist, or the database version is not
63 the same as the application's version.
64  
65 =item B<--ignore-reserved-words>
66  
67 Ignore any SQL reserved words used in table or column definitions, if
68 this option is not used and a reserved word is found it will cause an error.
69  
70 =item B<--no-bootstrap>
71  
72 don't run Bootstrap, mostly to get rid of creating initial data
73  
74 =item B<--help>
75  
76 Print a brief help message and exits.
77  
78 =item B<--man>
79  
80 Prints the manual page and exits.
81  
82 =back
83  
84 =cut
85  
86 sub options {
87 my $self = shift;
88 return (
89 $self->SUPER::options,
90 "setup" => "setup_tables",
91 "print|p" => "print",
92 "create-database|c" => "create_database",
93 "ignore-reserved-words" => "ignore_reserved",
94 "drop-database" => "drop_database",
95 "no-bootstrap" => "no_bootstrap",
96 );
97 }
98  
99 =head1 DESCRIPTION
100  
101 Looks for all model classes of your Jifty application and generates
102 SQL statements to create or update database tables for all of the
103 models. It either prints the SQL to standard output (B<--print>) or
104 actually issues the C<CREATE TABLE> or C<ALTER TABLE> statements on
105 Jifty's database.
106  
107 (Note that even if you are just displaying the SQL, you need to have
108 correctly configured your Jifty database in
109 I<ProjectRoot>C</etc/config.yml>, because the SQL generated may depend
110 on the database type.)
111  
112 By default checks for SQL reserved words in your table names and
113 column definitions, throwing an error if any are found.
114  
115 If you want to permanently turn this behaviour off you can set
116 CheckSchema to 0 in the database section of your applications config
117 file.
118  
119 =head1 BUGS
120  
121 Due to limitations of L<DBIx::DBSchema>, this probably only works with
122 PostgreSQL, MySQL and SQLite.
123  
124 It is possible that some of this functionality should be rolled into
125 L<Jifty::DBI::SchemaGenerator>
126  
127 =cut
128  
129 =head1 METHODS
130  
131 =head2 run
132  
133 Prints a help message if the users want it. If not, goes about its
134 business.
135  
136 Sets up the environment, checks current database state, creates or deletes
137 a database as necessary and then creates or updates your models' schema.
138  
139 =cut
140  
141 sub run {
142 my $self = shift;
143  
144 $self->print_help();
145 $self->setup_environment();
146 $self->probe_database_existence();
147 $self->manage_database_existence();
148 if ( $self->{create_all_tables} ) {
149 $self->create_all_tables();
150 } elsif ( $self->{'setup_tables'} ) {
151 $self->run_upgrades();
152 } else {
153 print "Done.\n";
154 }
155 }
156  
157 =head2 run_upgrades
158  
159 Take the actions we need in order to bring an existing database up to current.
160  
161 =cut
162  
163 sub run_upgrades {
164 my $self = shift;
165 $self->upgrade_jifty_tables();
166 $self->upgrade_plugin_tables();
167 $self->upgrade_application_tables();
168 }
169  
170 =head2 setup_environment
171  
172 Sets up a minimal Jifty environment.
173  
174 =cut
175  
176 sub setup_environment {
177 my $self = shift;
178  
179 # Import Jifty
180 Jifty::Util->require("Jifty");
181 Jifty::Util->require("Jifty::Model::Metadata");
182 Jifty->new( no_handle => 1, logger_component => 'SchemaTool', )
183 unless Jifty->class_loader;
184 }
185  
186 =head2 schema
187  
188 Returns a Jifty::Schema object.
189  
190 =cut
191  
192 sub schema {
193 my $self = shift;
194  
195 $self->{'SCHEMA'} ||= Jifty::Schema->new();
196 return $self->{'SCHEMA'};
197 }
198  
199 =head2 probe_database_existence
200  
201 Probes our database to see if it exists and is up to date.
202  
203 =cut
204  
205 sub probe_database_existence {
206 my $self = shift;
207 my $no_handle = 0;
208 if ( $self->{'create_database'} or $self->{'drop_database'} ) {
209 $no_handle = 1;
210 }
211  
212 # Now try to connect. We trap expected errors and deal with them.
213 eval {
214 Jifty->setup_database_connection(
215 no_handle => $no_handle,
216 logger_component => 'SchemaTool',
217 check_opts => { pretend => $self->{'print'} ? 1 : 0 }
218 );
219 };
220 my $error = $@;
221  
222 if ( $error =~ /doesn't match (application schema|running jifty|running plugin) version/i
223 or $error =~ /plugin isn't installed in database/i ) {
224  
225 # We found an out-of-date DB. Upgrade it
226 $self->{setup_tables} = 1;
227 } elsif ( $error =~ /no version in the database/i ) {
228  
229 # No version table. Assume the DB is empty.
230 $self->{create_all_tables} = 1;
231 } elsif ( $error =~ /(database .*? (?:does not|doesn't) exist|unknown database)/i) {
232  
233 # No database exists; we'll need to make one and fill it up
234 $self->{drop_database} = 0;
235 $self->{create_database} = 1;
236 $self->{create_all_tables} = 1;
237 } elsif ($error) {
238  
239 # Some other unexpected error; rethrow it
240 die $error;
241 }
242  
243 # Setting up tables requires creating the DB if we just dropped it
244 $self->{create_database} = 1
245 if $self->{drop_database} and $self->{setup_tables};
246  
247 # Setting up tables on a just-created DB is the same as setting them all up
248 $self->{create_all_tables} = 1
249 if $self->{create_database} and $self->{setup_tables};
250  
251 # Give us some kind of handle if we don't have one by now
252 Jifty->handle( Jifty::Handle->new() ) unless Jifty->handle;
253 }
254  
255 =head2 create_all_tables
256  
257 Create all tables for this application's models. Generally, this
258 happens on installation.
259  
260 =cut
261  
262 sub create_all_tables {
263 my $self = shift;
264  
265 my $log = Log::Log4perl->get_logger("SchemaTool");
266 $log->info("Generating SQL for application @{[Jifty->app_class]}...");
267  
268 my $appv
269 = version->new( Jifty->config->framework('Database')->{'Version'} );
270 my $jiftyv = version->new($Jifty::VERSION);
271  
272 # Start a transaction
273 Jifty->handle->begin_transaction;
274  
275 $self->create_tables_for_models( grep { $_->isa('Jifty::DBI::Record') }
276 $self->schema->models );
277  
278 # Update the versions in the database
279 Jifty::Model::Metadata->store( application_db_version => $appv );
280 Jifty::Model::Metadata->store( jifty_db_version => $jiftyv );
281  
282 # For each plugin, update the plugin version
283 for my $plugin ( Jifty->plugins ) {
284 my $pluginv = version->new( $plugin->version );
285 Jifty::Model::Metadata->store(
286 ( ref $plugin ) . '_db_version' => $pluginv );
287 }
288  
289 unless ( $self->{'no_bootstrap'} ) {
290  
291 # Load initial data
292 eval {
293 my $bootstrapper = Jifty->app_class("Bootstrap");
294 Jifty::Util->require($bootstrapper);
295 $bootstrapper->run() if $bootstrapper->can('run');
296  
297 for my $plugin ( Jifty->plugins ) {
298 my $plugin_bootstrapper = $plugin->bootstrapper;
299 Jifty::Util->require($plugin_bootstrapper);
300 $plugin_bootstrapper->run() if $plugin_bootstrapper->can('run');
301 }
302 };
303 die $@ if $@;
304 }
305  
306 # Commit it all
307 Jifty->handle->commit or exit 1;
308  
309 $log->info("Set up version $appv, jifty version $jiftyv");
310 }
311  
312 =head2 create_tables_for_models TABLEs
313  
314 Given a list of items that are the scalar names of subclasses of Jifty::Record,
315 either prints SQL or creates all those models in your database.
316  
317 =cut
318  
319 sub create_tables_for_models {
320 my $self = shift;
321 my @models = (@_);
322  
323 my $log = Log::Log4perl->get_logger("SchemaTool");
324 my $appv
325 = version->new( Jifty->config->framework('Database')->{'Version'} );
326 my $jiftyv = version->new($Jifty::VERSION);
327  
328 my %pluginvs;
329 for my $plugin ( Jifty->plugins ) {
330 my $plugin_class = ref $plugin;
331 $pluginvs{$plugin_class} = version->new( $plugin->version );
332 }
333  
334 MODEL:
335 for my $model (@models) {
336  
337 # Skip autogenerated models; that is, those that are overridden by plugins.
338 next MODEL if Jifty::ClassLoader->autogenerated($model);
339 my $plugin_root = Jifty->app_class('Plugin') . '::';
340  
341 # TODO XXX FIXME:
342 # This *will* try to generate SQL for abstract base classes you might
343 # stick in $AC::Model::.
344 if ( $model->can('since') ) {
345 my $app_class = Jifty->app_class;
346  
347 my $installed_version = 0;
348  
349 # Is it a Jifty core model?
350 if ( $model =~ /^Jifty::Model::/ ) {
351 $installed_version = $jiftyv;
352 }
353  
354 # Is it a Jifty or application plugin model?
355 elsif ( $model =~ /^(?:Jifty::Plugin::|$plugin_root)/ ) {
356 my $plugin_class = $model;
357 $plugin_class =~ s/::Model::(.*)$//;
358  
359 $installed_version = $pluginvs{$plugin_class};
360 }
361  
362 # Otherwise, an application model
363 else {
364 $installed_version = $appv;
365 }
366  
367 if ( $installed_version < $model->since ) {
368  
369 # XXX Is this message correct?
370 $log->info(
371 "Skipping $model, as it should already be in the database"
372 );
373 next MODEL;
374 }
375 }
376  
377 if ( $model =~ /^(?:Jifty::Plugin::|$plugin_root)/
378 and $model =~ /::Model::(.*)$/ )
379 {
380 my $model_name = $1;
381  
382 # Check to make sure this model is not overridden in the app,
383 # in such cases we don't want to try to create the same table
384 # twice, so let the app model do it rather than the plugin
385 my $app_model = Jifty->app_class( "Model", $model_name );
386 $app_model->require;
387 next MODEL unless Jifty::ClassLoader->autogenerated($app_model);
388 }
389  
390 $log->info("Using $model, as it appears to be new.");
391  
392 $self->schema->_check_reserved($model)
393 unless ( $self->{'ignore_reserved'}
394 or !Jifty->config->framework('Database')->{'CheckSchema'} );
395  
396 if ( $self->{'print'} ) {
397 print $model->printable_table_schema;
398 } else {
399 $model->create_table_in_db;
400 }
401 }
402 }
403  
404 =head2 upgrade_jifty_tables
405  
406 Upgrade Jifty's internal tables.
407  
408 =cut
409  
410 sub upgrade_jifty_tables {
411 my $self = shift;
412 my $dbv = Jifty::Model::Metadata->load('jifty_db_version');
413 unless ($dbv) {
414  
415 # Backwards combatibility -- it usd to be 'key' not 'data_key';
416 eval {
417 local $SIG{__WARN__} = sub { };
418 $dbv
419 = Jifty->handle->fetch_result(
420 "SELECT value FROM _jifty_metadata WHERE key = 'jifty_db_version'"
421 );
422 };
423 }
424  
425 $dbv = version->new( $dbv || '0.60426' );
426 my $appv = version->new($Jifty::VERSION);
427  
428 return
429 unless $self->upgrade_tables(
430 "Jifty" => $dbv,
431 $appv, "Jifty::Upgrade::Internal"
432 );
433 if ( $self->{print} ) {
434 warn "Need to upgrade jifty_db_version to $appv here!\n";
435 } else {
436 Jifty::Model::Metadata->store( jifty_db_version => $appv );
437 }
438 }
439  
440 =head2 upgrade_application_tables
441  
442 Upgrade the application's tables.
443  
444 =cut
445  
446 sub upgrade_application_tables {
447 my $self = shift;
448 my $dbv = version->new(
449 Jifty::Model::Metadata->load('application_db_version') );
450 my $appv
451 = version->new( Jifty->config->framework('Database')->{'Version'} );
452  
453 return unless $self->upgrade_tables( Jifty->app_class, $dbv, $appv );
454 if ( $self->{print} ) {
455 warn "Need to upgrade application_db_version to $appv here!\n";
456 } else {
457 Jifty::Model::Metadata->store( application_db_version => $appv );
458 }
459 }
460  
461 =head2 upgrade_plugin_tables
462  
463 Upgrade the tables for each plugin.
464  
465 =cut
466  
467 sub upgrade_plugin_tables {
468 my $self = shift;
469  
470 for my $plugin ( Jifty->plugins ) {
471 my $plugin_class = ref $plugin;
472  
473 my $dbv
474 = Jifty::Model::Metadata->load( $plugin_class . '_db_version' );
475 my $appv = version->new( $plugin->version );
476  
477 # Upgrade this plugin from dbv -> appv
478 if ( defined $dbv ) {
479 $dbv = version->new($dbv);
480  
481 next
482 unless $self->upgrade_tables( $plugin_class, $dbv, $appv,
483 $plugin->upgrade_class );
484 if ( $self->{print} ) {
485 warn
486 "Need to upgrade ${plugin_class}_db_version to $appv here!\n";
487 } else {
488 Jifty::Model::Metadata->store(
489 $plugin_class . '_db_version' => $appv );
490 }
491 }
492  
493 # Install this plugin
494 else {
495 my $log = Log::Log4perl->get_logger("SchemaTool");
496 $log->info("Generating SQL to set up $plugin_class...");
497 Jifty->handle->begin_transaction;
498  
499 # Create the tables
500 $self->create_tables_for_models(
501 grep {
502 $_->isa('Jifty::DBI::Record')
503 and /^\Q$plugin_class\E::Model::/
504 } $self->schema->models
505 );
506  
507 # Save the plugin version to the database
508 Jifty::Model::Metadata->store(
509 $plugin_class . '_db_version' => $appv )
510 unless $self->{print};
511  
512 # Run the bootstrapper for initial data
513 unless ( $self->{print} ) {
514 eval {
515 my $bootstrapper = $plugin->bootstrapper;
516 Jifty::Util->require($bootstrapper);
517 $bootstrapper->run if $bootstrapper->can('run');
518 };
519 die $@ if $@;
520 }
521  
522 # Save them records
523 Jifty->handle->commit;
524 $log->info("Set up $plugin_class version $appv");
525 }
526 }
527 }
528  
529 =head2 upgrade_tables BASECLASS, FROM, TO, [UPGRADECLASS]
530  
531 Given a C<BASECLASS> to upgrade, and two L<version> objects, C<FROM>
532 and C<TO>, performs the needed transforms to the database.
533 C<UPGRADECLASS>, if not specified, defaults to C<BASECLASS>::Upgrade
534  
535 =cut
536  
537 sub upgrade_tables {
538 my $self = shift;
539 my ( $baseclass, $dbv, $appv, $upgradeclass ) = @_;
540 $upgradeclass ||= $baseclass . "::Upgrade";
541  
542 my $log = Log::Log4perl->get_logger("SchemaTool");
543  
544 # Find current versions
545  
546 if ( $appv < $dbv ) {
547 print
548 "$baseclass version $appv from module older than $dbv in database!\n";
549 return;
550 } elsif ( $appv == $dbv ) {
551  
552 # Shouldn't happen
553 print "$baseclass database version $appv up to date.\n";
554 return;
555 }
556 $log->info("Generating SQL to upgrade $baseclass $dbv database to $appv");
557  
558 # Figure out what versions the upgrade knows about.
559 Jifty::Util->require($upgradeclass) or return;
560 my %UPGRADES;
561 eval {
562 $UPGRADES{$_} = [ $upgradeclass->upgrade_to($_) ]
563 for grep { $appv >= version->new($_) and $dbv < version->new($_) }
564 $upgradeclass->versions();
565 };
566  
567 if ($@) {
568 $log->error("Error collecting upgrade steps: $@");
569 return;
570 }
571  
572 for my $model_class ( grep {/^\Q$baseclass\E::Model::/}
573 $self->schema->models )
574 {
575  
576 # We don't want to get the Collections, for example.
577 next unless $model_class->isa('Jifty::DBI::Record');
578  
579 # Set us up the table
580 my $model = $model_class->new;
581  
582 # If this whole table is new Create it
583 if ( $model->can('since')
584 and defined $model->since
585 and $appv >= $model->since
586 and $model->since > $dbv )
587 {
588 unshift @{ $UPGRADES{ $model->since } },
589 $model->table_schema_statements();
590 } else {
591 # Go through the columns
592 for my $col ( grep { not $_->virtual and not $_->computed } $model->all_columns ) {
593  
594 # If they're old, drop them
595 if ( defined $col->till and $appv >= $col->till and $col->till > $dbv ) {
596 push @{ $UPGRADES{ $col->till } }, sub {
597 my $renamed = $upgradeclass->just_renamed || {};
598  
599 # skip it if this was dropped by a rename
600 $model->drop_column_in_db($col->name)
601 unless defined $renamed->{ $model->table }->{'drop'}->{ $col->name };
602 };
603 }
604  
605 # If they're new, add them
606 if ( $col->can('since')
607 and defined $col->since
608 and $appv >= $col->since
609 and $col->since > $dbv )
610 {
611 unshift @{ $UPGRADES{ $col->since } }, sub {
612 my $renamed = $upgradeclass->just_renamed || {};
613  
614 # skip it if this was added by a rename
615 $model->add_column_in_db( $col->name ) unless
616 defined $renamed->{ $model->table }->{'add'}
617 ->{ $col->name };
618 };
619 }
620 }
621 }
622 }
623  
624 if ( $self->{'print'} ) {
625 $self->_print_upgrades(%UPGRADES);
626  
627 } else {
628 eval {
629 $self->_execute_upgrades(%UPGRADES);
630 $log->info("Upgraded to version $appv");
631 };
632 die $@ if $@;
633 }
634 return 1;
635 }
636  
637 sub _execute_upgrades {
638 my $self = shift;
639 my %UPGRADES = (@_);
640 Jifty->handle->begin_transaction;
641 my $log = Log::Log4perl->get_logger("SchemaTool");
642 for my $version ( sort { version->new($a) <=> version->new($b) }
643 keys %UPGRADES )
644 {
645 $log->info("Upgrading through $version");
646 for my $thing ( @{ $UPGRADES{$version} } ) {
647 if ( ref $thing ) {
648 $log->info("Running upgrade script");
649 $thing->();
650 } else {
651 _exec_sql($thing);
652 }
653 }
654 }
655 Jifty->handle->commit;
656 }
657  
658 sub _print_upgrades {
659 my $self = shift;
660 my %UPGRADES = (@_);
661 for (
662 map { @{ $UPGRADES{$_} } }
663 sort { version->new($a) <=> version->new($b) }
664 keys %UPGRADES
665 )
666 {
667 if ( ref $_ ) {
668 print "-- Upgrade subroutine:\n";
669 require Data::Dumper;
670 $Data::Dumper::Pad = "-- ";
671 $Data::Dumper::Deparse = 1;
672 $Data::Dumper::Indent = 1;
673 $Data::Dumper::Terse = 1;
674 print Data::Dumper::Dumper($_);
675 } else {
676 print "$_;\n";
677 }
678 }
679 }
680  
681 =head2 manage_database_existence
682  
683 If the user wants the database created, creates the database. If the
684 user wants the old database deleted, does that too. Exits with a
685 return value of 1 if the database drop or create fails.
686  
687 =cut
688  
689 sub manage_database_existence {
690 my $self = shift;
691  
692 my $handle = Jifty::Schema->connect_to_db_for_management();
693  
694 if ( $self->{print} ) {
695 $handle->drop_database('print') if ( $self->{'drop_database'} );
696 $handle->create_database('print') if ( $self->{'create_database'} );
697 } else {
698 if ( $self->{'drop_database'} ) {
699 my $ret = $handle->drop_database('execute');
700 die "Error dropping database: ". $ret->error_message
701 unless $ret or $ret->error_message =~ /database .*?(?:does not|doesn't) exist|unknown database/i;
702 }
703  
704 if ( $self->{'create_database'} ) {
705 my $ret = $handle->create_database('execute');
706 die "Error creating database: ". $ret->error_message unless $ret;
707 }
708  
709 $handle->disconnect;
710 $self->_reinit_handle() if ( $self->{'create_database'} );
711 }
712 }
713  
714 sub _reinit_handle {
715 Jifty->handle( Jifty::Handle->new() );
716 Jifty->handle->connect();
717 }
718  
719 sub _exec_sql {
720 my $sql = shift;
721 my $ret = Jifty->handle->simple_query($sql);
722 die "error updating a table: " . $ret->error_message unless $ret;
723 }
724  
725 1;
« Jifty/Manual.pm ↑ Summary