| 1 | package Mojolicious::Plugin::Migration::Sqitch 0.01; | ||
| 2 | 1 | ▶ | use v5.26; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 3 | 1 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | |||
| 5 | # ABSTRACT: Run Sqitch database migrations from a Mojo app | ||
| 6 | |||
| 7 | =encoding UTF-8 | ||
| 8 | |||
| 9 | =head1 NAME | ||
| 10 | |||
| 11 | Mojolicious::Plugin::Migration::Sqitch - Run Sqitch database migrations from a Mojo app | ||
| 12 | |||
| 13 | =head1 SYNOPSIS | ||
| 14 | |||
| 15 | # Register plugin | ||
| 16 | $self->plugin('Migration::Sqitch' => { | ||
| 17 | dsn => 'dbi:mysql:host=localhost;port=3306;database=myapp', | ||
| 18 | registry => 'sqitch_myapp', | ||
| 19 | username => 'sqitch', | ||
| 20 | password => 'world-banana-tuesday', | ||
| 21 | directory => '/schema', | ||
| 22 | }); | ||
| 23 | |||
| 24 | # use from command-line (normally done by startup script to ensure db up to date before app starts) | ||
| 25 | tyrrminal@prodserver:/app$ script/myapp schema-initdb | ||
| 26 | [2024-04-30 11:26:47.91166] [8982] [info] Database initialized | ||
| 27 | |||
| 28 | tyrrminal@prodserver:/app$ script/myapp schema-migrate | ||
| 29 | Deploying changes to db:MariaDB://sqitch@db/myapp_dev | ||
| 30 | + initial_schema .. ok | ||
| 31 | [2024-04-30 11:29:13.80192] [8985] [info] Database migration complete | ||
| 32 | |||
| 33 | # Revert a migration in dev | ||
| 34 | tyrrminal@devserver:/app$ script/myapp schema-migrate schema-migrate revert | ||
| 35 | Revert all changes from db:MariaDB://sqitch@db/myapp_dev? [Yes] | ||
| 36 | - initial_schema .. ok | ||
| 37 | [2024-04-30 11:26:47.91166] [8982] [info] Database migration complete | ||
| 38 | |||
| 39 | # Start over from scratch | ||
| 40 | tyrrminal@devserver:/app$ script/myapp schema-initdb --reset | ||
| 41 | This will result in all data being deleted from the database. Are you sure you want to continue? [yN] y | ||
| 42 | [2024-04-30 11:28:10.73379] [8983] [info] Database reset | ||
| 43 | [2024-04-30 11:28:10.73501] [8983] [info] Database initialized | ||
| 44 | |||
| 45 | =head1 DESCRIPTION | ||
| 46 | |||
| 47 | Mojolicious::Plugin::Migration::Sqitch enables the use of sqitch via Mojolicious | ||
| 48 | commands. The primary advantage of this is single-point configuration: just pass | ||
| 49 | the appropriate parameters in at plugin registration and then you don't have to | ||
| 50 | worry about passwords, DSNs, and filesystem locations for running sqitch commands | ||
| 51 | thereafter. | ||
| 52 | |||
| 53 | This plugin also provides some additional functionality for initializing the | ||
| 54 | database, which can't easily be done strictly through sqitch migrations without | ||
| 55 | hardcoding database names, which can be troublesome depending on the deployment. | ||
| 56 | |||
| 57 | =head1 METHODS | ||
| 58 | |||
| 59 | L<Mojolicious::Plugin::Migration::Sqitch> inherits all methods from | ||
| 60 | L<Mojolicious::Plugin> and implements the following new ones | ||
| 61 | |||
| 62 | =head2 register( $args ) | ||
| 63 | |||
| 64 | Register plugin in L<Mojolicious> application. The following keys are required | ||
| 65 | in C<$args> | ||
| 66 | |||
| 67 | =head4 dsn | ||
| 68 | |||
| 69 | The L<data source name|https://en.wikipedia.org/wiki/Data_source_name> for | ||
| 70 | connecting to the I<application> database. | ||
| 71 | |||
| 72 | E.g., C<dbi:mysql:host=db;port=3306;database=myapp_prod> | ||
| 73 | |||
| 74 | =head4 registry | ||
| 75 | |||
| 76 | The name of the database used by sqitch for tracking migrations | ||
| 77 | |||
| 78 | E.g., C<myapp_prod_sqitch> | ||
| 79 | |||
| 80 | =head4 username | ||
| 81 | |||
| 82 | Database username for sqitch migrations. As this account needs to run arbitrary | ||
| 83 | SQL code (both DDL and DML), it must have sufficiently high privileges. This | ||
| 84 | can be the same account used by the application, if this consideration is taken | ||
| 85 | into account. | ||
| 86 | |||
| 87 | =head4 password | ||
| 88 | |||
| 89 | The password corresponding to the sqitch migration database account | ||
| 90 | |||
| 91 | =head4 directory | ||
| 92 | |||
| 93 | The on-disk location of the sqitch migrations directory. Sqitch expects to find | ||
| 94 | C<deploy>, C<revert>, and C<verify> subdirectories there, as well as the | ||
| 95 | C<sqitch.plan> file. It must also contain a C<sqitch.conf> file, but the only | ||
| 96 | contents of this file needed are: | ||
| 97 | |||
| 98 | [core] | ||
| 99 | engine = $ENGINE | ||
| 100 | |||
| 101 | With C<$ENGINE> replaced by the actual engine name, e.g., C<mysql> or C<pgsql>. | ||
| 102 | This plugin handles the rest of the configuration that would normally be found | ||
| 103 | in that file. | ||
| 104 | |||
| 105 | E.g., C</schema> (in a containerized environment), or C</home/mojo/myapp/schema> | ||
| 106 | |||
| 107 | =head2 run_schema_initialization( \%args ) | ||
| 108 | |||
| 109 | Create the configured application and migration databases, if either or both | ||
| 110 | do not already exist. One key is regarded in the C<args> HashRef: | ||
| 111 | |||
| 112 | =head4 reset | ||
| 113 | |||
| 114 | If this key is given and is assigned a "truthy" value, the application and | ||
| 115 | migration databases will be dropped (if either or both exists) before being | ||
| 116 | re-created. I<This is a destructive operation!> | ||
| 117 | |||
| 118 | =head2 run_schema_migration( $sqitch_subcommand ) | ||
| 119 | |||
| 120 | Run the specified C<$sqitch_subcommand> including any additional parameters | ||
| 121 | (e.g., C<deploy> or C<revert -to @HEAD^1>). Returns the exit status of the | ||
| 122 | sqitch command to indicate success (zero) or failure (non-zero). | ||
| 123 | |||
| 124 | =head1 COMMANDS | ||
| 125 | |||
| 126 | =head2 schema-initdb [--reset] | ||
| 127 | |||
| 128 | Mojolicious command to execute L</run_schema_initialization> | ||
| 129 | |||
| 130 | If the C<--reset> flag is given, corresponding to the methods's L</reset> arg | ||
| 131 | key, a console warning is given alerting the user of the destructive nature of | ||
| 132 | this operation and must be manually approved before continuing. | ||
| 133 | |||
| 134 | =head2 schema-migrate [args] | ||
| 135 | |||
| 136 | Mojolicious command to execute L</run_schema_migration>. Any additional args | ||
| 137 | given are whitespace-joined and passed on to that method. If no args are | ||
| 138 | provided, C<deploy> is assumed. | ||
| 139 | |||
| 140 | =cut | ||
| 141 | |||
| 142 | 0 | ▶ | use Mojo::Base 'Mojolicious::Plugin'; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 143 | |||
| 144 | use DBI; | ||
| 145 | use Syntax::Keyword::Try; | ||
| 146 | use Readonly; | ||
| 147 | |||
| 148 | use experimental qw(signatures); | ||
| 149 | |||
| 150 | Readonly::Scalar my $INITDB_SQL => q{CREATE DATABASE IF NOT EXISTS `%s` CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_general_ci'}; | ||
| 151 | Readonly::Scalar my $RESETDB_SQL => q{DROP DATABASE IF EXISTS `%s`}; | ||
| 152 | |||
| 153 | sub _parse_dsn($dsn) { | ||
| 154 | my ($scheme, $driver, $attr_string, $attr_hash, $driver_param_str) = DBI->parse_dsn($dsn); | ||
| 155 | my %driver_params = split(/[;=]/, $driver_param_str); | ||
| 156 | { | ||
| 157 | scheme => $scheme, | ||
| 158 | driver => $driver, | ||
| 159 | attr_str => $attr_string, | ||
| 160 | attrs => $attr_hash // {}, | ||
| 161 | params => {%driver_params}, | ||
| 162 | param_str => $driver_param_str | ||
| 163 | }; | ||
| 164 | } | ||
| 165 | |||
| 166 | sub register($self, $app, $conf) { | ||
| 167 | push($app->commands->namespaces->@*, 'Mojolicious::Plugin::Migration::Sqitch::Command'); | ||
| 168 | |||
| 169 | my $dsn = _parse_dsn($conf->{dsn}); | ||
| 170 | my $migrations_registry = $conf->{registry}; | ||
| 171 | my $migrations_username = $conf->{username}; | ||
| 172 | my $migrations_password = $conf->{password}; | ||
| 173 | my $migrations_directory = $conf->{directory}; | ||
| 174 | |||
| 175 | my $initdb_sql = $conf->{initdb_sql} // $INITDB_SQL; | ||
| 176 | my $resetdb_sql = $conf->{resetdb_sql} // $RESETDB_SQL; | ||
| 177 | |||
| 178 | my $connectdb = $conf->{connectdb} // sub($parsed_dsn, $u, $p) { | ||
| 179 | DBI->connect( | ||
| 180 | sprintf('DBI:%s:host=%s;port=%s', $parsed_dsn->{driver}, $parsed_dsn->{params}->{host}, $parsed_dsn->{params}->{port},), | ||
| 181 | $u, $p,); | ||
| 182 | }; | ||
| 183 | my $initdb = $conf->{initdb} // sub($dbh, $name) {$dbh->do(sprintf($initdb_sql, $name))}; | ||
| 184 | my $resetdb = $conf->{resetdb} // sub($dbh, $name) {$dbh->do(sprintf($resetdb_sql, $name))}; | ||
| 185 | |||
| 186 | $app->helper( | ||
| 187 | run_schema_initialization => sub ($self, $args = {}) { | ||
| 188 | my $dbh = $connectdb->($dsn, $migrations_username, $migrations_password); | ||
| 189 | |||
| 190 | if ($args->{reset}) { | ||
| 191 | try { | ||
| 192 | $resetdb->($dbh, $_) foreach ($migrations_registry, $dsn->{params}->{database}); | ||
| 193 | $app->log->info("Database reset"); | ||
| 194 | } catch ($e) { | ||
| 195 | $app->log->error("Database reset failed: $e"); | ||
| 196 | } | ||
| 197 | } | ||
| 198 | |||
| 199 | try { | ||
| 200 | $initdb->($dbh, $_) foreach ($dsn->{params}->{database}, $migrations_registry); | ||
| 201 | $app->log->info("Database initialized"); | ||
| 202 | } catch ($e) { | ||
| 203 | $app->log->error("Database creation failed: $e"); | ||
| 204 | } | ||
| 205 | } | ||
| 206 | ); | ||
| 207 | |||
| 208 | $app->helper( | ||
| 209 | run_schema_migration => sub ($self, $subcommand) { | ||
| 210 | die("Sqitch subcommand is required") unless ($subcommand); | ||
| 211 | my $make_dsn = sub ($obscured = 0) | ||
| 212 | { # sqitch DSNs are a) different than DBI's, and b) complicated. This should cover all cases in sqitch's manual | ||
| 213 | my $driver = $dsn->{driver}; | ||
| 214 | |||
| 215 | my $port = $dsn->{params}->{port} ? ':' . $dsn->{params}->{port} : ''; | ||
| 216 | my $host = $dsn->{params}->{host} ? $dsn->{params}->{host} . $port : ''; | ||
| 217 | |||
| 218 | my $username = $migrations_username ? $migrations_username : ''; | ||
| 219 | my $password = $migrations_password ? ':' . ($obscured ? '*' x 8 : $migrations_password) : ''; | ||
| 220 | my $credentials = $username ? "$username$password@" : ''; | ||
| 221 | |||
| 222 | my $connection = ($credentials || $host) ? "//$credentials$host/" : ''; | ||
| 223 | my ($name) = ((grep {defined} @{$dsn->{params}}{qw(database dbname)}), ''); | ||
| 224 | |||
| 225 | my $params = ''; | ||
| 226 | $params .= '?Driver=' . ucfirst($driver) if (grep {lc($driver) eq $_} (qw(exasol snowflake vertica))); | ||
| 227 | $params .= ";warehouse=$migrations_registry" if (grep {lc($driver) eq $_} (qw(snowflake))); | ||
| 228 | |||
| 229 | return sprintf("db:$driver:$connection$name$params"); | ||
| 230 | }; | ||
| 231 | |||
| 232 | my ($cmd, $log_cmd) = map { | ||
| 233 | sprintf(q{sqitch -C %s %s --registry %s --target %s}, | ||
| 234 | $migrations_directory, $subcommand, $migrations_registry, $make_dsn->($_),) | ||
| 235 | } (0, 1); | ||
| 236 | |||
| 237 | $app->log->debug($log_cmd); | ||
| 238 | my $err = system($cmd); | ||
| 239 | |||
| 240 | if ($err) { | ||
| 241 | my $code = ($? & 0x7F) ? ($? & 0x7F) | 0x80 : $? >> 8; | ||
| 242 | $app->log->error("Database migration failed: $code"); | ||
| 243 | return $code; | ||
| 244 | } | ||
| 245 | $app->log->info("Database migration complete"); | ||
| 246 | return 0; | ||
| 247 | } | ||
| 248 | ); | ||
| 249 | |||
| 250 | } | ||
| 251 | |||
| 252 | =pod | ||
| 253 | |||
| 254 | =head1 AUTHOR | ||
| 255 | |||
| 256 | Mark Tyrrell C<< <mark@tyrrminal.dev> >> | ||
| 257 | |||
| 258 | =head1 LICENSE | ||
| 259 | |||
| 260 | Copyright (c) 2024 Mark Tyrrell | ||
| 261 | |||
| 262 | Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| 263 | of this software and associated documentation files (the "Software"), to deal | ||
| 264 | in the Software without restriction, including without limitation the rights | ||
| 265 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| 266 | copies of the Software, and to permit persons to whom the Software is | ||
| 267 | furnished to do so, subject to the following conditions: | ||
| 268 | |||
| 269 | The above copyright notice and this permission notice shall be included in all | ||
| 270 | copies or substantial portions of the Software. | ||
| 271 | |||
| 272 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| 273 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| 274 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| 275 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| 276 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| 277 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| 278 | SOFTWARE. | ||
| 279 | |||
| 280 | =cut | ||
| 281 | |||
| 282 | 1; | ||
| 283 | |||
| 284 | __END__ | ||