2 ###############################################################################
7 mig-init - This will add or recreate tracking tables for the B<mig> toolset to
8 the migration schema specified by the MIGSCHEMA environment variable, in the
9 PostgreSQL database specified by various PG environment variables.
11 In practice, you should invoke 'mig env use schema_name' prior to calling
22 ###############################################################################
27 HOME PGHOST PGPORT PGUSER PGDATABASE MIGSCHEMA
28 MIGBASEWORKDIR MIGBASEGITDIR MIGGITDIR MIGWORKDIR
33 my $mig_bin = "$FindBin::Bin/";
34 my $mig_sql = $mig_bin . "../mig-sql/init/";
35 use lib "$FindBin::Bin/";
38 pod2usage(-verbose => 2) if $ARGV[0];
40 Mig::die_if_no_env_migschema();
42 if (! Mig::check_for_db_migschema()) {
43 try_to_create_schema();
46 if (! Mig::check_db_migschema_for_migration_tables()) {
47 try_to_init_schema_with_migration_tools();
49 Mig::die_if_mig_tracking_table_exists();
50 Mig::die_if_mig_column_tracking_table_exists();
51 loop_through_mig_sql_templates();
55 ###############################################################################
57 sub try_to_create_schema {
58 if ($MIGSCHEMA =~ /[^\w_]/) {
59 die "$MIGSCHEMA is not suitable for a schema name in PostgreSQL\n";
61 my $dbh = Mig::db_connect();
62 my $rv = $dbh->do("CREATE SCHEMA $MIGSCHEMA;")
63 || die "Error creating migration schema ($MIGSCHEMA): $!\n";
64 print "Created schema $MIGSCHEMA\n";
65 Mig::db_disconnect($dbh);
68 sub try_to_init_schema_with_migration_tools {
69 Mig::die_if_no_migration_tools();
70 print "Calling migration_tools.init() and .build()\n";
71 my $dbh = Mig::db_connect();
72 my $rv = $dbh->do("SELECT migration_tools.init(" . $dbh->quote($MIGSCHEMA) . ");")
73 || die "Error running migration_tools.init($MIGSCHEMA): $!\n";
74 print "migration_tools.init() finished\n";
75 my $rv2 = $dbh->do("SELECT migration_tools.build(" . $dbh->quote($MIGSCHEMA) . ");")
76 || die "Error running migration_tools.build($MIGSCHEMA): $!\n";
77 print "migration_tools.build() finished\n";
78 Mig::db_disconnect($dbh);
81 sub loop_through_mig_sql_templates {
82 print "Looping through mig-sql/init/ templates\n";
83 opendir my $dir, $mig_sql or die "Cannot open directory: $!";
84 my @files = sort readdir $dir;
86 foreach my $file (@files) {
87 if ($file =~ /.sql$/) {
88 print "executing $file:\n";
89 system( $mig_bin . "mig-sql", ('-f',$mig_sql . $file) )