4672e6db38cb51c5e69cfd86fc32c15a4f27f435
[migration-tools.git] / kmig.d / bin / kmig-init
1 #!/usr/bin/perl -w
2 ###############################################################################
3 =pod
4
5 =head1 NAME
6
7 kmig-init - This will add or recreate tracking tables for the B<kmig> toolset
8 to the database specified by the current kmig environment.
9
10 In practice, you should invoke 'kmig env use schema_name' prior to calling
11 B<init>
12
13 =head1 SYNOPSIS
14
15 B<kmig-init>
16
17 B<kmig-init> <help>
18
19 =cut
20
21 ###############################################################################
22
23 use strict;
24 use Switch;
25 use Env qw(
26     HOME MYSQL_HOST MYSQL_TCP_PORT MYSQL_USER MYSQL_DATABASE MYSQL_PW
27     MIGSCHEMA MIGBASEWORKDIR MIGBASEGITDIR MIGGITDIR MIGWORKDIR
28 );
29 use Pod::Usage;
30 use DBI;
31 use FindBin;
32 my $mig_bin = "$FindBin::Bin/";
33 my $mig_sql = $mig_bin . "../sql/init/";
34 use lib "$FindBin::Bin/";
35 use KMig;
36
37 pod2usage(-verbose => 2) if $ARGV[0];
38
39 KMig::die_if_no_env_migschema();
40
41 if (! KMig::check_for_db_migschema()) {
42     die "could not find the schema";
43 }
44
45 if (! KMig::check_db_migschema_for_migration_tables()) {
46     try_to_init_schema_with_migration_tools();
47 }
48 KMig::die_if_mig_tracking_table_exists();
49 KMig::die_if_mig_column_tracking_table_exists();
50 loop_through_mig_sql_templates();
51
52 exit 0;
53
54 ###############################################################################
55
56 sub try_to_init_schema_with_migration_tools {
57     KMig::die_if_no_migration_tools();
58     print "Calling mt_init() and mt_build()\n";
59     my $dbh = KMig::db_connect();
60     my $rv = $dbh->do("SELECT mt_init();")
61         || die "Error running mt_init(): $!\n";
62     print "mt_init() finished\n";
63     my $rv2 = $dbh->do("SELECT mt_build();")
64         || die "Error running mt_build(): $!\n";
65     print "migration_tools.build() finished\n";
66     KMig::db_disconnect($dbh);
67 }
68
69 sub loop_through_mig_sql_templates {
70     print "Looping through kmig.d/sql/init/ templates\n";
71     opendir my $dir, $mig_sql or die "Cannot open directory: $!";
72     my @files = sort readdir $dir;
73     closedir $dir;
74     foreach my $file (@files) {
75         if ($file =~ /.sql$/) {
76             print "executing $file:\n";
77             system( $mig_bin . "kmig-sql", ('-e',"source $mig_sql$file") )
78         }
79     }
80 }
81