Paste #126990

   
pasted on 26.09.2019 13:40
  • Edit to this paste
  • Print
  • Raw
  • Compare with paste
    #  
  • Toggle line numbers
  • Syntax highlighting  
Text paste
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#####################################
package Model::Base;
use Mojo::Base -base;

has [qw(dbh)], undef, weak=>1;
has qw(sth_cached);#

sub insert_default_values {
  my ($self, $schema, $table,) = splice @_,0, 3;
  warn ("_insert_default_values [$schema][$table] [@_]");
  $self->dbh->selectrow_hashref($self->prepare_sth(<<SQL), undef, @_);
INSERT INTO "$schema"."$table"
DEFAULT VALUES
returning *, ? as "foo";
SQL
}

sub prepare_sth {
  my ($self, $sql, $cached) = @_;
  $cached //= $self->sth_cached;
  return $self->dbh->prepare_cached($sql)
    if $cached;
  return  $self->dbh->prepare($sql);
}

1;

#####################################
package Model::Test;
use Mojo::Base 'Model::Base';

sub test1 {
  my ($self, $id, $req_id) = @_;
  my $s = $self->foo($id)
    if $id;
  # вот эта строчка запускается только для первого запроса
  $s ||= $self->insert_default_values("public", "test", $req_id); 
  return $s;
}

1;
################################
package main;
use Mojo::Base 'Mojolicious';
use DBI;
use Mojo::Util qw(dumper);

has dbh => sub {
  my $dbh = DBI->connect('dbi:Pg:dbname=dev2', 'postgres', undef,);
  $dbh->do(<<SQL);
CREATE TABLE IF NOT EXISTS public.test (
  id SERIAL not null primary key,
  ts timestamp not null default now()
);
SQL
  $dbh;
};

has model => sub {
  Model::Test->new(dbh=>shift->app->dbh);
};

sub startup {
  my $app = shift;
  $app->secrets(['My secret pa$$phrase']);
  my $r = $app->routes;
  $r->get('/' => sub {
    my $c = shift;
    my $r = $c->app->model->test1($c->session->{foo}, $c->req->request_id);
    $c->app->log->debug(dumper $r);
    $c->render(text => $r->{id});
  });
}

__PACKAGE__->new->start;
Add Comment
Author