lib/MojoX/Pg/Migrations/Env.pm

filter: Statementstmt 100% 44 / 44 Branchbran 100% 16 / 16 Conditioncond 100% 14 / 14 MC/DCmcdc 100% 9 / 9 Subroutinesub 100% 10 / 10 Podpod 100% 4 / 4 totaltotal 100% 97 / 97 CC 16 SCAR 13.1
CC
16
Cov
100%
placeholders
6.0
resolve
5.0
sql_for
4.0
CRAP 3.7
↑ Summary
1 package MojoX::Pg::Migrations::Env;
2  
3 2 ▶use Mojo::Base 'Mojo::Pg::Migrations', -signatures;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 2 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 # This will be changed automatically when running `mise run create:release`
8 2 our $VERSION = '0.2.0';
9  
10 # Variables looked up by ${NAME} and ${NAME:-fallback} placeholders in migration sql
11 1 ▶has env => sub { \%ENV };
Subroutine __ANON__: called CC=1 SCAR=0.0
12  
13 # ${NAME}, ${NAME:-fallback} and the escaped form $${NAME} which is left alone
14 2 my $PLACEHOLDER = qr/\$(\$?)\{([A-Za-z_]\w*)(?::-([^}]*))?\}/;
15  
16 # How a migration is named in error messages, a subclass can add what it knows about the migration
17 4 ▶sub label_for ( $self, $version ) { return "Migration $version" }
Subroutine label_for: called CC=1 SCAR=0.0
Pod documented
18  
19 # Placeholders used by a migration, in order of first appearance, as {name, fallback}
20 22 ▶sub placeholders ( $self, $version )
Subroutine placeholders: called CC=6 SCAR=17.9
Pod documented
21 {
22 22 my ( %seen, @found );
23 22 for my $way (qw(up down)) {
24 44 ▶ my $sql = $self->{migrations}{$way}{$version} // next;
Condition100%2/2
$self->{"migrations"}{$way}{$version} // (next)
l!l
3311
MC/DC100%1/1
$self->{"migrations"}{$way}{$version} // (next)
$self->{"migrations"}{$way}{$version}
Truth table100%2/2
A
A= $self->{"migrations"}{$way}{$version}
Aresult
11
00
25 33 ▶ while ( $sql =~ /$PLACEHOLDER/g ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /$PLACEHOLDER/gu) 21 33 54
26 21 ▶ next if $1 || $seen{$2}++;
Branch: 1 branch
BranchTrueFalseTotal
if $1 or $seen{$2}++ 8 13 21
Condition100%3/3
$1 or $seen{$2}++
l!l&&r!l&&!r
4413
MC/DC100%2/2
$1 or $seen{$2}++
$1 $seen{$2}++
Truth table100%3/3
A or B
A= $1B= $seen{$2}++
ABresult
1X1
011
000
27 13 push @found, { name => $2, fallback => $3 };
28 }
29 }
30 22 return \@found;
31 }
32  
33 # Where the value of a placeholder comes from and what it is, the only place that decides
34 45 ▶sub resolve ( $self, $name, $fallback = undef )
Subroutine resolve: called CC=5 SCAR=16.1
Pod documented
35 45 {
36 45 my $value = $self->env->{$name};
37 45 ▶ return ( 'env', $value ) if defined $value && length $value;
Branch: 1 branch
BranchTrueFalseTotal
if defined $value and length $value 23 22 45
Condition100%3/3
defined $value and length $value
!ll&&!rl&&r
18423
MC/DC100%2/2
defined $value and length $value
defined $value length $value
Truth table100%3/3
A and B
A= defined $valueB= length $value
ABresult
0X0
100
111
38 22 ▶ return ( 'fallback', $fallback ) if defined $fallback;
Branch: 1 branch
BranchTrueFalseTotal
if defined $fallback 14 8 22
39 8 return ( 'missing', undef );
40 }
41  
42 # Same selection as the parent, with placeholders substituted per migration so an error can name it
43 77 ▶sub sql_for ( $self, $from, $to )
Subroutine sql_for: called CC=4 SCAR=13.9
Pod documented
44 {
45 77 my ( $up, $down ) = @{ $self->{migrations} }{qw(up down)};
46 77 ▶ if ( $from < $to ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($from < $to) 45 32 77
47 45 ▶ my @versions = sort { $a <=> $b } grep { $_ <= $to && $_ > $from } keys %$up;
Condition100%3/3
$_ <= $to && $_ > $from
!ll&&!rl&&r
131365
MC/DC100%2/2
$_ <= $to && $_ > $from
$_ <= $to $_ > $from
Truth table100%3/3
A && B
A= $_ <= $toB= $_ > $from
ABresult
0X0
100
111
48 45 return join '', map { $self->_substitute( $up->{$_}, $_ ) } @versions;
49 }
50 32 ▶ my @versions = reverse sort { $a <=> $b } grep { $_ > $to && $_ <= $from } keys %$down;
Condition100%3/3
$_ > $to && $_ <= $from
!ll&&!rl&&r
28828
MC/DC100%2/2
$_ > $to && $_ <= $from
$_ > $to $_ <= $from
Truth table100%3/3
A && B
A= $_ > $toB= $_ <= $from
ABresult
0X0
100
111
51 32 return join '', map { $self->_substitute( $down->{$_}, $_ ) } @versions;
52 }
53  
54 93 ▶sub _substitute ( $self, $sql, $version )
Subroutine _substitute: called CC=2 SCAR=6.9
55 {
56 93 ▶ $sql =~ s/$PLACEHOLDER/$1 ? _unescape($2, $3) : $self->_value($2, $3, $version)/ge;
Branch: 1 branch
BranchTrueFalseTotal
$1 ? : 5 35 40
57 88 return $sql;
58 }
59  
60 # An escaped placeholder as it was written, without the extra dollar
61 5 ▶sub _unescape ( $name, $fallback )
Subroutine _unescape: called CC=2 SCAR=6.9
62 {
63 5 ▶ return "\${$name" . ( defined $fallback ? ":-$fallback" : '' ) . '}';
Branch: 1 branch
BranchTrueFalseTotal
defined $fallback ? : 2 3 5
64 }
65  
66 35 ▶sub _value ( $self, $name, $fallback, $version )
Subroutine _value: called CC=2 SCAR=6.9
67 {
68 35 my ( $source, $value ) = $self->resolve( $name, $fallback );
69 35 ▶ return $value unless $source eq 'missing';
Branch: 1 branch
BranchTrueFalseTotal
unless $source eq "missing" 30 5 35
70 5 croak $self->label_for($version) . " needs environment variable $name, which is not set and has no fallback";
71 }
72  
73 2 1;
74  
75 =encoding utf8
76  
77 =head1 NAME
78  
79 MojoX::Pg::Migrations::Env - Mojo::Pg migrations that replace environment placeholders in their sql, sponsored by Fibia
80  
81 =head1 SYNOPSIS
82  
83 use Mojo::Pg;
84 use MojoX::Pg::Migrations::Env;
85  
86 my $pg = Mojo::Pg->new('postgresql://app@/app');
87 $pg->migrations(MojoX::Pg::Migrations::Env->new(pg => $pg, name => 'app'));
88 $pg->migrations->from_file('db/migrations.sql')->migrate;
89  
90 # Or look first
91 for my $placeholder (@{$pg->migrations->placeholders(3)}) {
92 my ($source, $value) = $pg->migrations->resolve($placeholder->{name}, $placeholder->{fallback});
93 say "$placeholder->{name} ($source)";
94 }
95  
96 With C<db/migrations.sql> containing
97  
98 -- 3 up
99 grant select on invoices to ${APP_READONLY_ROLE:-readonly};
100 -- 3 down
101 revoke select on invoices from ${APP_READONLY_ROLE:-readonly};
102  
103 =head1 DESCRIPTION
104  
105 L<MojoX::Pg::Migrations::Env> is a drop-in replacement for L<Mojo::Pg::Migrations>. It is a subclass
106 that loads, selects and applies migrations exactly like its parent, with one difference: placeholders in
107 the migration sql are replaced with values from the environment when the sql is produced. That lets
108 migrations refer to things that differ between environments, for example the name of a role to grant to.
109  
110 Migrations without placeholders produce the same sql as they do with L<Mojo::Pg::Migrations>, so an
111 existing project can switch class without changing its migrations.
112  
113 It requires L<Mojo::Pg> 4.04 or newer, the first release where L<Mojo::Pg::Migrations/"migrate"> gets its
114 sql from L<Mojo::Pg::Migrations/"sql_for">, L<Mojolicious> 7.51 or newer and Perl 5.20 or newer for
115 subroutine signatures.
116  
117 =head1 PLACEHOLDERS
118  
119 grant select on invoices to ${APP_READONLY_ROLE:-readonly};
120  
121 =over 2
122  
123 =item ${NAME}
124  
125 Replaced with the value of C<NAME> in L</"env">. A variable that is unset or empty is missing, and producing
126 the sql fails.
127  
128 =item ${NAME:-fallback}
129  
130 Replaced with the value of C<NAME> in L</"env">, or with the fallback when the variable is unset or empty.
131 The fallback is everything up to the closing brace and can be empty, as in C<${NAME:-}>.
132  
133 =item $${NAME}
134  
135 Left as the literal C<${NAME}>, and C<$${NAME:-fallback}> as the literal C<${NAME:-fallback}>. An escaped
136 placeholder is never looked up and never listed by L</"placeholders">.
137  
138 =back
139  
140 A name starts with a letter or an underscore, followed by letters, digits and underscores. Nothing else is
141 touched, so numbered parameters like C<$1> and dollar quoted function bodies (C<$$> and C<$tag$>) are safe
142 to use. Take care where a dollar quote is directly followed by a placeholder, because C<$$${NAME}> reads as
143 a dollar sign followed by the escaped form. Put whitespace between them.
144  
145 Placeholders are replaced everywhere in the sql of a migration, also inside comments and string literals,
146 in both up and down sql. Values are inserted as they are, without quoting.
147  
148 Values are looked up when the sql is produced, and all sql between two versions is produced before any of
149 it runs. A missing variable therefore aborts L<Mojo::Pg::Migrations/"migrate"> with nothing applied, and
150 only the migrations between the active and the target version need their variables set.
151  
152 =head1 ATTRIBUTES
153  
154 L<MojoX::Pg::Migrations::Env> inherits all attributes from L<Mojo::Pg::Migrations> and implements the
155 following new ones.
156  
157 =head2 env
158  
159 my $env = $migrations->env;
160 $migrations = $migrations->env({APP_READONLY_ROLE => 'reporting'});
161  
162 Variables that placeholders are looked up in, defaults to C<%ENV>.
163  
164 =head1 METHODS
165  
166 L<MojoX::Pg::Migrations::Env> inherits all methods from L<Mojo::Pg::Migrations> and implements the
167 following new ones.
168  
169 =head2 label_for
170  
171 my $label = $migrations->label_for(3);
172  
173 How a migration is named in error messages, defaults to C<Migration 3>. It is only called when an error is
174 raised. A subclass that knows more about its migrations than their version can override it, and the label
175 becomes the subject of the error.
176  
177 package My::Migrations;
178 use Mojo::Base 'MojoX::Pg::Migrations::Env', -signatures;
179  
180 sub label_for ($self, $version) { "Migration $version (" . $self->title_of($version) . ')' }
181  
182 # Migration 3 (add readonly grants) needs environment variable APP_READONLY_ROLE, which is not ...
183  
184 =head2 placeholders
185  
186 my $placeholders = $migrations->placeholders(3);
187  
188 Placeholders used by a version's up and down sql, in order of first appearance, as hashes with C<name> and
189 C<fallback>, where the fallback is C<undef> for a required variable. A name used more than once is listed
190 once, with the fallback of its first appearance. Escaped placeholders are not listed.
191  
192 =head2 resolve
193  
194 my ($source, $value) = $migrations->resolve('APP_READONLY_ROLE');
195 my ($source, $value) = $migrations->resolve('APP_READONLY_ROLE', 'readonly');
196  
197 Where the value for a placeholder comes from, and the value, without producing any sql. Never dies.
198  
199 =over 2
200  
201 =item env
202  
203 L</"env"> has a value for the name that is not empty, which is the value returned.
204  
205 =item fallback
206  
207 L</"env"> has no value for the name, or an empty one, and a fallback was given, which is the value returned.
208  
209 =item missing
210  
211 L</"env"> has no value for the name, or an empty one, and there is no fallback. The value is C<undef>.
212  
213 =back
214  
215 =head2 sql_for
216  
217 my $sql = $migrations->sql_for(5, 10);
218  
219 Same as L<Mojo::Pg::Migrations/"sql_for">, with the placeholders of every migration on the way replaced.
220 Dies when a variable is missing, naming the migration that needs it with L</"label_for">.
221  
222 Migration 3 needs environment variable APP_READONLY_ROLE, which is not set and has no fallback
223  
224 =head1 SPONSORS
225  
226 This module is sponsored by L<Fibia|https://fibia.dk>.
227  
228 =head1 AUTHOR
229  
230 David Jack Wange Olrik, C<djo@cpan.org>.
231  
232 =head1 COPYRIGHT AND LICENSE
233  
234 Copyright (C) 2026, David Jack Wange Olrik.
235  
236 This program is free software, you can redistribute it and/or modify it under the terms of the MIT license. See the
237 C<LICENSE> file for the full text.
238  
239 =head1 SEE ALSO
240  
241 L<Mojo::Pg>, L<Mojo::Pg::Migrations>, L<Mojolicious::Guides>, L<https://mojolicious.org>.
242  
243 =cut
↑ Summary