D.pm untested

filter: Statementstmt 0.0% 0 / 110 Branchbran 0.0% 0 / 34 Conditioncond 0.0% 0 / 60 MC/DCmcdc 0.0% 0 / 33 Subroutinesub 0.0% 0 / 31 Podpod 0.0% 0 / 26 totaltotal 0.0% 0 / 294 CC 18 SCAR 22.9
CC
18
Cov
0%
columns_info
42.0
obtain_data
12.0
INSECURE
12.0
CRAP 9.9
1 package D;
2  
3 use strict;
4 use warnings;
5  
6 our $VERSION = '0.01_01';
7  
8  
9 use C;
10 use DDP;
11  
12 # Helper to revive next and count methods to access data
13 {
14 package D::Iterator;
15 sub next { shift $_[0]->@* }
16 sub count { scalar $_[0]->@* }
17 sub D::Arr { bless [ @_ ], 'D::Iterator' }
18 }
19  
20  
21 sub db { CORE::state $schema //= ref $_[0] && $_[0] || D::connect(@_) }
22 sub dbh { db->storage->dbh }
23 # https://metacpan.org/pod/DBIx::Class::Storage#txn_scope_guard
24 sub txn { db->txn_scope_guard }
25  
26 # Prepare and execute a single statement. See DBI::do
27 sub do { dbh->do( @_ ) }
28 sub q { dbh->selectall_arrayref( @_ ) } # query -> array of arrays
29 sub q00 { D::q( @_ )->[0][0] } # the first field from the first row
30 sub rs { my $rs = dbh->prepare(shift);
31 $rs->execute( @_ );
32 return $rs;
33 }
34 sub qh { my( $st, $a ) = (shift,shift); # query hashes
35 $a? $a->{ Slice }= {} : $a= { Slice => {} };
36 D::q $st, $a, @_;
37 }
38  
39  
40 # Run arbitrary SQL, list columns and get DBIx::Class::ResultSet
41 use DBIx::Class::Report;
42 sub report {
43 my $report = DBIx::Class::Report->new(
44 schema => D::db(),
45 sql => shift,
46 columns => shift,
47 );
48  
49 return $report->fetch( @_ );
50 }
51  
52  
53  
54 sub dsn {
55 my $DB = shift;
56  
57 # Return DSN or autogenerate it
58 return $DB->{ DSN } || $DB->{ PORT }?
59 sprintf "dbi:%s:dbname=%s;host=%s;port=%s", @$DB{ qw/ DRVR NAME HOST PORT / }:
60 sprintf "dbi:%s:dbname=%s;host=%s", @$DB{ qw/ DRVR NAME HOST / };
61 }
62  
63 sub connect {
64 if( !@_ ) {
65 my $DB = C::config->{ DbAccess };
66 # Do not setup and do not cache DSN. This cause issues if user does not work with it.
67 # Eg. DRVR/NAME/HOST/PORT were changed, but DSN still cached.
68 local $DB->{ DSN } = dsn( $DB );
69 @_ = @$DB{ qw/ schema DSN USER PASS / }
70 }
71  
72 my $schema = shift->connect( @_, {
73 AutoCommit => 1,
74 RaiseError => 1,
75 PrintError => 1,
76 ShowErrorStatement => 1,
77 auto_savepoint => 1,
78 # Required to prevent syntax error: SELECT User.id because of reserwed 'user' word
79 quote_char => '"',
80 # HandleError => sub{ DB::x; 1; },
81 # unsafe => 1,
82 });
83 $schema->can( 'storage' )
84 && $schema->storage->dbh->do( 'SET timezone TO ?', {},
85 $ENV{ PGTZ } // $ENV{ TZ } // 'Europe/Zaporozhye'
86 );
87  
88  
89 return $schema;
90 }
91  
92  
93  
94 # Tries to find data by ID or condition provided via hashref as $cond
95 # Found row will be returned. It dies if many rows were found.
96 # If you provide hashref as third parameter then
97 # 1. Found row will be updated by this data.
98 # 2. Or, if nothing was found and search was done without ID then
99 # a new record will be created with { %$cond, %$data } merged together.
100 #
101  
102 sub obtain_data {
103 my( $table, $cond, $data, $update ) = @_;
104  
105  
106 ## Try to find by ID or condition
107 my $row = defined $cond && eval{
108 D::SS( $table, ref $cond? $cond : { id => $cond } );
109 } or do{
110 ## OR if no error happened ...
111 !$@ or do{ # just for debugging purpose
112 warn( sprintf "%s %s %s",
113 $table, $@, DDP::np $cond
114 );
115 my $e = $@; die;
116 };
117  
118 # ... create row if data provided and searching was done not by ID.
119 # Note: This would be not correct to create row with the provided ID or the
120 # provided data and ignored its ID at $cond.
121 $data && (!defined $cond || ref $cond) or return;
122  
123 ref $cond eq 'HASH' && ($data = { %$cond, %$data });
124  
125 # TODO: If value for PK is detected -> die
126 !exists $data->{id} or return; # SECURITY: Prohibit custom IDs during creation
127  
128 my $row = D::C( $table, $data );
129 return $row;
130 };
131  
132  
133 ## If requested then update the found row by a provided $data
134 # TODO? We should not read more fields then it was provided during update.
135 # TODO: Test D::T Test => { name => 'John' }, undef, 'update'
136 if( $update && $data ) { D::RU( $row, $data ); $row->discard_changes }
137  
138  
139 return $row;
140 }
141  
142  
143  
144 # Get resultset by name, aka pointer to table
145  
146  
147 our $SECURE = 1;
148 sub INSECURE {
149 ## Return whole table or try to obtain data
150 return @_ == 1?
151 (ref $_[0]? shift : db->resultset( shift )):
152 do{ local $SECURE = 0; obtain_data( @_ ) }
153 }
154  
155  
156  
157 sub INSECURE_C { D::INSECURE( shift )->create ( @_ ) }
158 sub INSECURE_S { D::INSECURE( shift )->search_rs( @_ ) }
159  
160  
161  
162 # Entry point to manipulate table's data
163 sub T {
164 local $SECURE = 1;
165 ## Return whole table or try to obtain data
166 return @_ == 1? D::S( shift ) : obtain_data( @_ );
167 }
168  
169  
170  
171 # Fetch permission policies
172 sub perm {
173 my( $table, $action ) = @_;
174  
175 # my $ctx = C::C();
176 # return my $rules = T Policy => { %$ctx, ... };
177 }
178  
179  
180  
181 # CRUD
182 sub C { # create
183 my( $table, $data ) = @_;
184  
185 my $defaults = {};
186 my $rs = D::INSECURE( $table );
187 # TODO: Select security rules and restrict data accessibility
188 if( $SECURE ) {
189 # my $rules = T Policy => { ... } or return;
190 # delete $data->%{ @list }
191 # $defaults = ...
192 $rs = $rs->guard( C::C );
193 }
194  
195 my $row = $rs->create({ %$data, %$defaults });
196 $row->{ _created } = 1;
197  
198 return $row;
199 }
200  
201  
202  
203 sub S { # search
204 my( $table, $cond ) = (shift,shift);
205  
206 my $rs = D::INSECURE( $table );
207 # TODO: Select security rules and restrict data accessibility
208 if( $SECURE ) {
209 # my $rules = T Policy => { ... } or return;
210 # $cond = ...
211 $rs = $rs->guard( C::C );
212 }
213 $rs->search_rs( $cond, @_ );
214 }
215  
216  
217  
218 sub SS { # search single
219 my( $table, $cond ) = @_;
220  
221 my $rs = D::INSECURE( $table );
222 # TODO: Select security rules and restrict data accessibility
223 if( $SECURE ) {
224 # my $rules = T Policy => { ... } or return;
225 # $cond = ...
226 $rs = $rs->guard( C::C );
227 }
228  
229 if( D::INSECURE( $table )->search( $cond )->count > 1 ) {
230 warn 'Multiple rows returned', $table .DDP::np $cond;
231 }
232  
233 $rs->single( $cond );
234 }
235  
236  
237  
238 sub RU { # record update
239 my( $record, $data ) = @_;
240  
241 # TODO: Select security rules and restrict data accessibility
242 # if( $SECURE ) {
243 # my $rules = T Policy => { ... } or return;
244 # delete $data->%{ @list }
245 # }
246  
247 $record->update( $data );
248 }
249  
250  
251  
252 sub RD { # record delete
253 my( $record ) = @_;
254 # NOTICE: For only one parameter D::T will return pointer to table,
255 # which will cause huge DATA LOSS: ->resultset( 'XXX' )->delete
256 # So we require more then one parameter
257 ref $record or @_ > 1 && ($record = D::T @_);
258  
259  
260 # TODO: Select security rules
261 # if( $SECURE ) {
262 # my $rules = T Policy => { ... } or return;
263 # }
264  
265 $record->delete;
266 }
267  
268  
269  
270 # MISC
271 sub columns_info {
272 my( $table, $opts ) = @_;
273  
274 # It is OK. We do not access data, only metadata.
275 $table = D::INSECURE( $table );
276  
277  
278 my $cols = $table->result_source->columns_info;
279 my $exclude = $table->can( 'internal_columns' ) && $table->internal_columns;
280  
281 my $row;
282 for my $col ( keys $cols->%* ) {
283 # SKIP excluded columns
284 next if exists $exclude->{ $col };
285  
286 my $info = $cols->{ $col };
287 ## SKIP not required columns: nullable or with defaults
288 next if $opts->{ required } && $info->{ is_nullable };
289 next if $opts->{ required } && exists $info->{ default_value };
290  
291  
292 $row->{ $col } = $info;
293 }
294  
295 return wantarray?
296 map{ exists $row->{$_}?($_, $row->{$_}):() } $table->result_source->columns:
297 $row;
298 }
299  
300  
301  
302 1;
303  
304 =encoding utf8
305  
306 =head1 NAME
307  
308 D - Simple interface to work with DB tables
309  
310 =head1 SYNOPSIS
311  
312 use D;
313  
314 my $schema = D::db; # DBIx::Class::Schema
315 my $dbh = D::dbh; # DBI handle
316  
317 my $users = D::S User => { active => 1 };
318 my $user = D::SS User => 1;
319  
320 my $count = D::q00 'SELECT count(*) FROM "User"';
321  
322 # Find by ID, another PK or set of conditions
323 my $row = D::T User => 7;
324 my $row = D::T User => { id => 7 };
325 my $row = D::T User => { email => 'a@example.com' };
326 my $row = D::T User => [ { f1 => 'v1' }, { f2 => 'v2' } ]; # See SQL::Abstract
327 my $row = D::T User => { field1 => 'cond1', field2 => 'cond2' };
328  
329 # Find existing or create by merging COND and DATA. COND merged only if it is a HASH.
330 # The create dies if user will try to use custom values for PKs
331 my $row = D::T User => { email => 'a@example.com' }, { name => 'Alice' };
332 my $row = D::T User => undef, { name => 'Alice' } # Save as D::C User => { name => 'Alice' };
333  
334 # Find and update. If not found `{ f2 => 'v2' }` will be created.
335 # NOTE: It is still not clear should we create when nothing was found and 'update'
336 # flag is true. Or should we return `undef`.
337 my $row = D::T User => { f1 => 'value1' }, { f2 => 'v2' }, 'update';
338  
339  
340 # Update $row
341 D::RU $row, { f1 => 'v1' };
342  
343 # Delete $row
344 D::RD $row;
345  
346  
347 # Work with transaction
348 my $atomic = D::txn; # ->txn_scope_guard
349 ...
350 if( ... ) { return; } # transaction will be rolled back automatically
351 $atomic->commit;
352  
353  
354 # All methods from DBIx::Class::Storage are available
355 my $db = D::db;
356 $db->txn_begin;
357 $db->svp_begin;
358 $db->txn_do( $coderef );
359 $db->svp_release;
360 $db->svp_rollback;
361 $db->txn_rollback;
362 $db->txn_commit;
363  
364  
365 =head1 DESCRIPTION
366  
367 L<D> is a small convenience layer around L<DBIx::Class> and L<DBI>.
368  
369 It provides shortcuts for:
370  
371 - Getting a schema/DBI handle
372 - Running raw SQL queries
373 - Basic CRUD helpers using a DBIx::Class resultset
374  
375 Most helpers accept a table name (Result class moniker) as the first argument.
376  
377  
378 =head1 CONFIGURATION
379  
380 If you call L</db> or L</connect> without arguments, configuration is read from
381 C<C::config-E<gt>{DbAccess}>.
382  
383 Expected keys:
384  
385 schema DBIx::Class::Schema class name (required)
386 DRVR DBI driver name (for example: Pg)
387 NAME database name
388 HOST database host
389 PORT database port (optional)
390 USER database user
391 PASS database password
392 DSN optional prebuilt DBI DSN (will be generated if missing)
393  
394 Timezone:
395  
396 - If possible, L</connect> sets PostgreSQL timezone from C<$ENV{PGTZ}> or
397 C<$ENV{TZ}>; otherwise it defaults to C<Europe/Zaporozhye>.
398  
399  
400 =head1 FUNCTIONS
401  
402 =head2 db
403  
404 my $schema = D::db;
405 my $schema = D::db $schema;
406  
407 Return (and cache) a L<DBIx::Class::Schema> instance. When called without
408 arguments, it calls L</connect>.
409  
410  
411 =head2 dbh
412  
413 my $dbh = D::dbh;
414  
415 Shortcut for C<D::db-E<gt>storage-E<gt>dbh>.
416  
417  
418 =head2 txn
419  
420 my $guard = D::txn;
421  
422 Return a transaction scope guard (see
423 L<DBIx::Class::Storage/txn_scope_guard>).
424  
425  
426 =head2 do
427  
428 D::do $statement, @bind;
429  
430 Shortcut for C<D::dbh-E<gt>do>. See L<DBI/do>.
431  
432  
433 =head2 q
434  
435 my $rows = D::q $statement, \%attr, @bind;
436 my $rows = D::q 'SELECT * FROM users';
437  
438 Shortcut for C<DBI::selectall_arrayref>.
439  
440  
441 =head2 q00
442  
443 my $value = D::q00 $statement, \%attr, @bind;
444  
445 Return the first field of the first row from L</q>. This is useful for queries
446 like:
447  
448 SELECT count(*) FROM table
449 SELECT name FROM table LIMIT 1
450  
451  
452 =head2 rs
453  
454 my $result_set = D::rs $statement, @bind;
455  
456 Prepare and execute a statement and return resultset.
457  
458  
459 =head2 qh
460  
461 my $rows = D::qh $statement, \%attr, @bind;
462  
463 Query and return an array of hashes.
464  
465  
466 =head2 report
467  
468 my $rs = D::report $sql, \@columns, @bind;
469  
470 Run arbitrary SQL using L<DBIx::Class::Report> and return its resultset.
471  
472  
473 =head2 dsn
474  
475 my $dsn = D::dsn \%db_conf;
476  
477 Build a DBI DSN from config keys.
478  
479  
480 =head2 connect
481  
482 my $schema = D::connect; # Pass through to DBI->connect
483 my $schema = D::connect( $schema_class, $dsn, $user, $pass );
484  
485 Connect to the database and return a schema instance. See L<DBI/connect>.
486 Here `$schema_class` is DBIx::Class schema of your application. See L<Schema>.
487  
488  
489 =head2 obtain_data
490  
491 my $row = D::obtain_data($table, $cond, $data, $update);
492  
493 Try to find a row by:
494  
495 - ID (when C<$cond> is a scalar)
496 - Condition (when C<$cond> is a hashref)
497  
498 If C<$update> is true and C<$data> is provided, the found row is updated.
499  
500 If nothing was found, and the search was not done by ID, a new row is created
501 from the merged C<$cond> and C<$data>.
502  
503 This helper refuses to create rows with an explicit primary key C<id>.
504  
505  
506 =head2 T
507  
508 my $rs = D::T 'User';
509 my $row = D::T 'User', $id;
510 my $row = D::T 'User', \%cond, \%data;
511 my $row = D::T 'User', \%cond, \%data, 'update';
512  
513 Entry point for table access:
514  
515 - With one argument returns a resultset (see L</S>).
516 - With more arguments calls L</obtain_data>.
517  
518  
519 =head2 INSECURE
520  
521 my $rs = D::INSECURE 'User';
522 my $row = D::INSECURE 'User', \%cond, \%data;
523  
524 Like L</T>, but disables security guard logic for the duration of the call.
525  
526  
527 =head2 C
528  
529 my $row = D::C $table, \%data;
530  
531 Create a row in C<$table>.
532  
533  
534 =head2 S
535  
536 my $rs = D::S $table, \%cond, @attrs;
537  
538 Search rows in C<$table> and return a resultset.
539  
540  
541 =head2 SS
542  
543 my $row = D::SS $table, \%cond;
544  
545 Search and return a single row.
546  
547  
548 =head2 RU
549  
550 D::RU $row, \%data;
551  
552 Update a row with provided data.
553  
554  
555 =head2 RD
556  
557 D::RD $row;
558 D::RD $table, \%cond;
559  
560 Delete a row.
561  
562 In secure mode, table access routes through C<< $rs->guard(C::C) >> (see
563 L</SECURITY NOTES>).
564  
565  
566 =head2 columns_info
567  
568 my $info = D::columns_info 'User';
569 my $req = D::columns_info 'User', { required => 1 };
570  
571 Return column metadata from the result source. If C<required> is true, nullable
572 columns and columns with defaults are excluded. See L<DBIx::Class::ResultSource/columns_info>.
573  
574  
575 =head1 SECURITY NOTES
576  
577 Secure mode is enabled by default and is meant to restrict data access and
578 mutations through per-resultset C<guard> logic.
579  
580 This distribution includes only a stub C<guard> implementation in
581 L<Schema::ResultSet>; applications are expected to override it.
582  
583 Even in insecure mode, L</obtain_data> refuses to create rows with an explicit
584 primary key C<id>.
585  
586  
587 =head1 SEE ALSO
588  
589 L<Mojolicious::Plugin::DbAccess>, L<DBIx::Class>, L<DBI>
590  
591  
592 =head1 COPYRIGHT AND LICENSE
593  
594 Copyright (c) 2026 Eugen Konkov.
595  
596 This program is free software, you can redistribute it and/or modify it under
597 the terms of the MIT License.
598  
599 =cut