blib/lib/DBIx/Auto/Migrate.pm

filter: Statementstmt 83.7% 77 / 92 Branchbran 56.2% 9 / 16 Conditioncond 50.0% 2 / 4 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 89.4% 17 / 19 Podpod n/a totaltotal 78.9% 105 / 133 CC 11 SCAR 8.0
CC
11
Cov
79%
_migrations_finish
4.2
_migrate
3.4
_apply_migration
3.1
CRAP 2.2
« Build ↑ Summary
1 package DBIx::Auto::Migrate;
2  
3 2 our $VERSION = "0.9";
4  
5 2 ▶use v5.16.3;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 2 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 sub _check_defined_sub {
12 4 ▶ my ( $caller, $sub ) = @_;
Subroutine _check_defined_sub: called CC=2 SCAR=9.2
13 4 ▶ if ( !$caller->can($sub) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $caller->can($sub)) 0 4 4
14 0 die
15 0 "To import '@{[__PACKAGE__]}' in '$caller' you must implement the '$sub' subroutine";
16 }
17 }
18  
19 sub import {
20 3 ▶ my $caller = caller;
Subroutine import: called CC=1 SCAR=0.0
21 2 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
22 3 *{"${caller}::finish_auto_migrate"} = sub {
23 1 ▶ _migrations_finish($caller);
Subroutine __ANON__: called CC=1 SCAR=0.0
24 3 };
25 }
26  
27 sub _migrations_finish {
28 1 ▶ my ($caller) = @_;
Subroutine _migrations_finish: called CC=4 SCAR=14.4
29 1 _check_defined_sub( $caller, 'migrations' );
30 1 _check_defined_sub( $caller, 'dsn' );
31 1 _check_defined_sub( $caller, 'user' );
32 1 _check_defined_sub( $caller, 'pass' );
33 1 my $extra;
34 1 ▶ if ( defined( my $extra_sub = $caller->can('extra') ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $extra_sub = $caller->can("extra"))) 0 1 1
35 0 $extra = $extra_sub->();
36 }
37 1 ▶ $extra //= {};
Condition50%1/2
$extra //= {}
l!l
01
MC/DC0%0/1
$extra //= {}
$extra
Truth table50%1/2
A
A= $extra
Aresult
11
00
38  
39 1 ▶ if ( 'HASH' ne ref $extra ) {
Branch: 1 branch
BranchTrueFalseTotal
if ("HASH" ne ref $extra) 0 1 1
40 0 die "${caller}::extra should return a hashref or undef";
41 }
42 {
43 2 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
44 2 ▶ no warnings 'redefine';
Subroutine BEGIN: called CC=1 SCAR=0.0
45 1 *{"${caller}::connect"} = sub {
46 1 ▶ my $self = shift;
Subroutine __ANON__: called CC=1 SCAR=0.0
47 1 my ( $dsn, $user, $pass ) = ( $self->dsn, $self->user, $self->pass );
48 1 _connect_wrapper( $caller, 'connect', $dsn, $user, $pass, $extra );
49 1 };
50 1 *{"${caller}::connect_cached"} = sub {
51 0 ▶ my $self = shift;
Subroutine __ANON__: not called CC=1 SCAR=6.9
52 0 my ( $dsn, $user, $pass ) = ( $self->dsn, $self->user, $self->pass );
53 0 _connect_wrapper( $caller, 'connect_cached', $dsn, $user, $pass,
54 $extra );
55 1 };
56  
57 }
58 }
59  
60 sub _connect_wrapper {
61 1 ▶ my ( $caller, $sub, $dsn, $user, $pass, $extra ) = @_;
Subroutine _connect_wrapper: called CC=1 SCAR=0.8
62 my $dbh = DBI->can($sub)->(
63 'DBI', $dsn, $user, $pass,
64 {
65 RaiseError => 1,
66 Callbacks => {
67 connected => sub {
68 0 ▶ eval {shift->do('set timezone = UTC')};
Subroutine __ANON__: not called CC=1 SCAR=6.9
69 0 return;
70 }
71 },
72 1 %$extra,
73 },
74 );
75 1 _migrate( $caller, $dbh );
76 1 return $dbh;
77 }
78  
79 sub _migrate {
80 1 ▶ my ( $caller, $dbh ) = @_;
Subroutine _migrate: called CC=3 SCAR=12.3
81 1 local $dbh->{RaiseError} = 0;
82 1 local $dbh->{PrintError} = 0;
83 1 my @migrations = $caller->can('migrations')->();
84 1 ▶ if ( _get_current_migration($dbh) > @migrations ) {
Branch: 1 branch
BranchTrueFalseTotal
if (_get_current_migration($dbh) > @migrations) 0 1 1
85 0 warn "Something happened there, wrong migration number.";
86 }
87 1 ▶ if ( _get_current_migration($dbh) >= @migrations ) {
Branch: 1 branch
BranchTrueFalseTotal
if (_get_current_migration($dbh) >= @migrations) 0 1 1
88 0 say STDERR "Migrations already applied.";
89 0 return;
90 }
91 1 _apply_migrations( $dbh, \@migrations );
92  
93 }
94  
95 sub _apply_migrations {
96 1 ▶ my $dbh = shift;
Subroutine _apply_migrations: called CC=2 SCAR=6.9
97 1 my $migrations = shift;
98 1 ▶ for ( my $i = _get_current_migration($dbh) ; $i < @$migrations ; $i++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @$migrations) 3 1 4
99 3 local $dbh->{RaiseError} = 1;
100 3 my $current_migration = $migrations->[$i];
101 3 my $migration_number = $i + 1;
102 3 _apply_migration( $dbh, $current_migration, $migration_number );
103 }
104 }
105  
106 sub _get_current_migration {
107 3 ▶ my $dbh = shift;
Subroutine _get_current_migration: called CC=2 SCAR=7.1
108 3 my $result = $dbh->selectrow_hashref( <<'EOF', undef, 'current_migration' );
109 SELECT value FROM options WHERE name = ?;
110 EOF
111 3 ▶ return int( $result->{value} // 0 );
Condition50%1/2
$result->{"value"} // 0
l!l
03
MC/DC0%0/1
$result->{"value"} // 0
$result->{"value"}
Truth table50%1/2
A
A= $result->{"value"}
Aresult
11
00
112 }
113  
114 sub _apply_migration {
115 3 ▶ my $dbh = shift;
Subroutine _apply_migration: called CC=3 SCAR=11.4
116 3 my $current_migration = shift;
117 3 my $migration_number = shift;
118 {
119 3 eval { $dbh->do($current_migration); };
120 3 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 3 3
121 0 die "$current_migration\n failed with: $@";
122 }
123 }
124 3 my $success = eval {
125 3 $dbh->do( <<'EOF', undef, 'current_migration', $migration_number );
126 INSERT INTO options (name, value)
127 VALUES (?, ?)
128 EOF
129 3 1;
130 };
131 3 ▶ if (!$success) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $success) 0 3 3
132 0 $dbh->do( <<'EOF', undef, $migration_number, 'current_migration' );
133 UPDATE options
134 SET value = ?
135 WHERE name = ?
136 EOF
137 }
138 }
139 2 1;
140  
141 =pod
142  
143 =encoding utf-8
144  
145 =head1 NAME
146  
147 DBIx::Auto::Migrate - Wrap your database connections and automatically apply db migrations.
148  
149 =head1 SYNOPSIS
150  
151 package MyCompany::DB;
152
153 use v5.16.3;
154 use strict;
155 use warnings;
156  
157 use DBIx::Auto::Migrate;
158  
159 finish_auto_migrate;
160  
161 sub create_index {
162 my ($table, $column) = @_;
163 if (!$table) {
164 die 'Index requires table';
165 }
166 if (!$column) {
167 die 'Index requires column';
168 }
169 return "CREATE INDEX index_${table}_${column} ON $table ($column)";
170 }
171  
172 sub migrations {
173 return (
174 'CREATE TABLE options (
175 id BIGSERIAL PRIMARY KEY,
176 name TEXT,
177 value TEXT,
178 UNIQUE (name)
179 )',
180 create_index(qw/options name/),
181 'CREATE TABLE users (
182 id BIGSERIAL PRIMARY KEY,
183 uuid TEXT NOT NULL,
184 username TEXT NOT NULL,
185 name TEXT NOT NULL,
186 surname TEXT NOT NULL,
187 UNIQUE(username)
188 )',
189 create_index(qw/users uuid/),
190 create_index(qw/users username/),
191 );
192 }
193  
194 sub dsn {
195 return 'dbi:Pg:dbname=my_fancy_app_db';
196 }
197  
198 sub user {
199 return 'user';
200 }
201  
202 sub pass {
203 return 'supertopsecretdbpass';
204 }
205  
206 sub extra {
207 {
208 PrintError => 1,
209 }
210 }
211  
212 And elsewhere:
213  
214 my $dbh = MyCompany::DB->connect;
215 my $dbh = MyCompany::DB->connect_cached;
216  
217 =head1 DESCRIPTION
218  
219 Sometimes is convenient to be able to make server or desktop programs that
220 use a database with the ability to be automatically have their database
221 upgraded in runtime.
222  
223 This module comes from a snippet of code I was copying all the time between
224 different projects with different database engines such as PostgreSQL and SQLite,
225 it is time to stop copying logic like this between projects and make public
226 my way to apply database migrations defined in code in a extensible way.
227  
228 It is only possible to migrate forward so be careful.
229  
230 To check an example project that uses this code you can check L<https://github.com/sergiotarxz/Perl-App-RSS-Social>
231  
232 =head1 SUBS TO IMPLEMENT IN YOUR OWN DATABASE WRAPPER
233  
234 =head2 migrations
235  
236 sub migrations {
237 return (
238 'CREATE TABLE options (
239 id BIGSERIAL PRIMARY KEY,
240 name TEXT,
241 value TEXT,
242 UNIQUE (name)
243 )',
244 'CREATE TABLE users (
245 id BIGSERIAL PRIMARY KEY,
246 uuid TEXT NOT NULL,
247 username TEXT NOT NULL,
248 name TEXT NOT NULL,
249 surname TEXT NOT NULL,
250 UNIQUE(username)
251 )',
252 );
253 }
254  
255 Returns a list of migrations, creating a options table in the first migration is
256 obligatory since it is internally used to keep track of the current migration number.
257  
258 =head2 dsn
259  
260 sub dsn {
261 return 'dbi:Pg:dbname=my_fancy_app_db';
262 }
263  
264 Returns a valid DSN for L<DBI>, you can use any logic to return this, even reading a database config file.
265  
266 =head2 user
267  
268 sub user { 'mydbuser' }
269  
270 Returns a valid user for L<DBI>, you can use any logic to return this, even reading a database config file.
271  
272 =head2 pass
273  
274 sub pass { 'mypass' }
275  
276 Returns a valid password for L<DBI>, you can use any logic to return this, even reading a database config file.
277  
278 =head2 extra
279  
280 sub extra {
281 {
282 PrintError => 1,
283 }
284 }
285  
286 You can optionally implement this method to pass extra options to L<DBI>, the
287 return must be a hashref or undef.
288  
289 =head1 FINALIZING THE DATABASE WRAPPER CLASS
290  
291 finish_auto_migrate();
292  
293 Calling this method will ensure your class is completely ready to be used,
294 you can do it at any point if every prerequisite is available.
295  
296 =head1 METHODS AUTOMATICALLY AVAILABLE IN YOUR WRAPPER
297  
298 =head2 connect
299  
300 my $dbh = MyCompany::DB->connect;
301  
302 Same as L<DBI>::C<connect> but without taking any argument.
303  
304 =head2 connect_cached
305  
306 my $dbh = MyCompany::DB->connect_cached;
307  
308 Same as L<DBI>::C<connect_cached> but without taking any argument.
309  
310 =head1 BUGS AND LIMITATIONS
311  
312 Tries to be database independent, but I cannot really ensure it.
313  
314 More testing is needed.
315  
316 =head1 AUTHOR
317  
318 SERGIOXZ - Sergio Iglesias
319  
320 =head1 CONTRIBUTORS
321  
322 SERGIOXZ - Sergio Iglesias
323  
324 =head1 COPYRIGHT
325  
326 Copyright © Sergio Iglesias (2025)
327  
328 =head1 LICENSE
329  
330 This library is free software and may be distributed under the same terms
331 as perl itself. See L<https://dev.perl.org/licenses/>.
332  
333 =cut
« Build ↑ Summary