Model.pm untested

filter: Statementstmt 0.0% 0 / 55 Branchbran 0.0% 0 / 22 Conditioncond 0.0% 0 / 38 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 9 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 127 CC 12 SCAR 34.9
CC
12
Cov
0%
new
56.0
sth
42.0
singleton
2.0
CRAP 32.9
1 package DBIx::Mojo::Model;
2 use Mojo::Base -base;
3 use Carp 'croak';
4 use DBIx::Mojo::Template;
5 use Hash::Merge qw( merge );
6 use Scalar::Util 'weaken';
7  
8 my %DICT_CACHE = ();# для каждого пакета/модуля
9  
10 has [qw(dbh dict template_vars mt)];
11 has dbi_cache_st => 1; # 1 - use DBI caching and 0 overvise this module caching
12  
13 has debug => $ENV{DEBUG_DBIx_Mojo_Model} || 0;
14 my $PKG = __PACKAGE__;
15  
16 #init once
17 sub singleton {
18 state $singleton = shift->SUPER::new(@_);
19 }
20  
21 # child model
22 sub new {
23 my $self = ref $_[0] ? shift : shift->SUPER::new(@_);
24 my $singleton = $self->singleton;
25
26 $self->dbh($singleton->dbh)
27 unless $self->dbh;
28 weaken $self->{dbh};
29
30 $self->template_vars(merge($self->template_vars || {}, $singleton->template_vars))
31 #~ and weaken $self->{template_vars}
32 if $singleton->template_vars && %{$singleton->template_vars};
33
34 $self->mt(merge($self->mt || {}, $singleton->mt))
35 #~ and weaken $self->{mt}
36 if $singleton->mt && %{$singleton->mt};
37
38 my $class = ref $self;
39
40 # pass extra class files (inside the class): our $DATA=['foo.txt', 'bar.txt'];
41 my $data_files = do { no strict 'refs'; ${"$class\::DATA"} };
42
43 $self->dict( $DICT_CACHE{$class} ||= DBIx::Mojo::Template->new($class, mt => $self->mt, vars => $self->template_vars, $data_files ? (data => $data_files) : (), ) )
44 unless $self->dict;
45 weaken $self->{dict};
46
47 $self->debug
48 && say STDERR "[DEBUG $PKG new] parsed dict keys [@{[keys %{$self->dict}]}] for class [$class]";
49
50 $self;
51 }
52  
53 sub sth {
54 my $self = shift;
55 my $name = shift;
56 my $attr = ref $_[0] eq 'HASH' ? shift : {};
57 my $class = ref $self;
58 my $dict = $self->dict;
59 my $st = $dict->{$name}
60 or croak "No such name[$name] in SQL dict! @{[ join ':', keys %$dict ]}";
61 #~ my %arg = @_;
62 my $sql = $st->render(@_).sprintf("\n--Statement name[%s]::[%s]", $class, $name); # ->template(%$template ? %arg ? %{merge($template, \%arg)} : %$template : %arg)
63 if (my $param_cached = $st->param && $st->param->{cached} || $st->param->{cache}) {
64 $self->debug
65 && say STDERR sprintf("[DEBUG $PKG sth] statement [%s]::[%s] is a %s", $class, $name, $self->dbi_cache_st ? 'DBI prepare_cached' : 'self model cached');
66 return $self->dbh->prepare_cached($sql, $attr, $attr->{Async} || $attr->{pg_async} ? 3 : ()) # attr Acync for Mojo::Pg::Che
67 if $self->dbi_cache_st;
68 return $st->sth || $st->sth($self->dbh->prepare($sql, $attr))->sth;
69 }
70 $self->debug
71 && say STDERR sprintf("[DEBUG $PKG sth] statement [%s]::[%s] is a dbh prepare", $class, $name);
72 #~ local $dbh->{TraceLevel} = "3|DBD";
73 return $self->dbh->prepare($sql, $attr);
74 }
75  
76 =pod
77  
78 =encoding utf8
79  
80 Доброго всем
81  
82 =head1 DBIx::Mojo::Model
83  
84 ¡ ¡ ¡ ALL GLORY TO GLORIA ! ! !
85  
86 =head1 NAME
87  
88 DBIx::Mojo::Model - base class for DBI models with templating statements by Mojo::Template.
89  
90 =head1 SINOPSYS
91  
92 Init once base singleton for process with dbh and (optional) template vars:
93  
94 use DBIx::Mojo::Model;
95 DBIx::Mojo::Model->singleton(dbh=>$dbh, template_vars=>$t);
96  
97 In child model must define SQL dict in __DATA__ of model package:
98  
99 package Model::Foo;
100 use Mojo::Base 'DBIx::Mojo::Model';
101
102 # optional outside dict __DATA__
103 our $DATA = ['Foo.pm.sql'];
104
105 sub new {
106 state $self = shift->SUPER::new(mt=>{tag_start=>'{%', tag_end=>'%}'}, @_);
107 }
108
109 sub foo {
110 my $self = ref $_[0] ? shift : shift->new;
111 $self->dbh->selectrow_hashref($self->sth('foo', where => 'where id=?',), undef, (shift));
112 }
113
114 __DATA__
115 @@ foo?cached=1
116 %# my foo statement with prepare_cached
117 select *
118 from foo
119 {% $where %}
120 ;
121  
122 In controller:
123  
124 ...
125 has model => sub { require Model::Foo; Model::Foo->new };
126
127 sub actionFoo {
128 my $c = shift;
129 my $foo = $c->model->foo($c->param('id'));
130 ...
131
132 }
133  
134 =head1 ATTRIBUTES
135  
136 =head2 dbh
137  
138 =head2 dict
139  
140 DBIx::Mojo::Template object. If not defined then will auto create from __DATA__ current model package.
141  
142 Model::Foo->new(dict=>DBIx::Mojo::Template->new('Model::Foo', ...), ...)
143  
144 =head2 mt
145  
146 Hashref Mojo::Template object attributes. Will passed to C<< Mojo::Template->new >> then dict auto create
147  
148 =head2 template_vars
149  
150 Hashref variables applies in statement templates.
151  
152 =head2 dbi_cache_st
153  
154 Boolean switch: 1(true) - use DBI caching ($dbh->prepare_cached)
155 and 0(false) overvise this module caching.
156  
157 The statement must has defined C<cached> param:
158  
159 @@ foo query name?cached=1
160 select ...
161  
162 Defaults is true for save statement inside DBIx::Mojo::Statement object atribute C<sth>.
163  
164 =head1 METHODS
165  
166 =head2 new
167  
168 Define or copy/merge attributes from C<singleton>.
169  
170 =head2 singleton
171  
172 Initialize default attributes for child model modules. Mostly C<dbh> and C<template_vars>
173  
174 =head2 sth
175  
176 This is main method.
177  
178 First input arg is dict statement name, next args C<< key => val >> are template variables.
179 Return DBI prepared (cached if param 'cached' is true) statement.
180  
181 =head1 Templates
182  
183 Body of template statement get as:
184  
185 $mFoo->dict->{'foo'}->sql
186  
187 Templates name can has additional params as ulr query:
188  
189 @@ foo.bar/baz?a=156&b=c
190 ...
191  
192 then model object the name of statement is url path and query is param:
193  
194 $mFoo->dict->{'foo.bar/baz'}->param->{b} # 'c'
195  
196 =head1 AUTHOR
197  
198 Михаил Че (Mikhail Che), C<< <mche[-at-]cpan.org> >>
199  
200 =head1 BUGS / CONTRIBUTING
201  
202 Please report any bugs or feature requests at L<https://github.com/mche/Mojolicious-Plugin-RoutesAuthDBI/issues>. Pull requests also welcome.
203  
204 =head1 COPYRIGHT
205  
206 Copyright 2016 Mikhail Che.
207  
208 This library is free software; you can redistribute it and/or modify
209 it under the same terms as Perl itself.
210  
211 =cut
212  
213 1;