File: Helpers.pm

package info (click to toggle)
sreview 0.12.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,504 kB
  • sloc: perl: 12,360; javascript: 509; sh: 72; makefile: 8
file content (189 lines) | stat: -rw-r--r-- 4,935 bytes parent folder | download | duplicates (2)
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package SReview::API::Helpers;

use strict;
use warnings;

use feature "signatures";
no warnings "experimental::signatures";

use Exporter 'import';
our @EXPORT = qw/db_query update_with_json add_with_json delete_with_query/;
our @EXPORT_OK = qw/db_query_log is_authed/;

use SReview::Config::Common;
use Mojo::JSON qw/decode_json encode_json/;
use DateTime::Format::Pg;

sub db_query_log {
	my ($app, $dbh, $query, @args) = @_;
	my $st = $dbh->prepare($query);
	$st->execute(@args);
	my $results = [];
	while(my @row = $st->fetchrow_array) {
		if(scalar(@row) > 1) {
			my $h = {};
			foreach my $col(@{$st->{NAME_lc}}) {
				$h->{$col} = shift @row;
			}
			push @$results, $h;
		} else {
			push @$results, @row;
		}
	}
	return $results;
}

sub db_query {
	my ($dbh, $query, @args) = @_;

	return db_query_log(undef, $dbh, $query, @args);
}

sub delete_with_query {
	my ($c, $query, @args) = @_;

	my $st = $c->dbh->prepare($query);
	eval {
		$st->execute(@args);
	};

	if($st->err) {
		$c->render(openapi => {errors => [{message => 'could not delete:', $st->errmsg}]}, status => 400);
		return;
	}

	if($st->rows < 1) {
		$c->render(openapi => {errors => [{message => 'not found'}]}, status => 404);
		return;
	}
	my $row = $st->fetchrow_arrayref;
	$c->render(openapi => $row->[0]);
}

sub update_with_json {
	my ($c, $json, $tablename, $fields, $fixup) = @_;

	my @args;

	if(!exists($json->{id})) {
		$c->render(openapi => {errors => [{message => 'id required'}]}, status => 400);
		return;
	}

	$c->app->log->debug("updating $tablename with " . encode_json($json));

	my @updates;

	while(my @tuple = each %$json) {
		if($tuple[0] eq "id") {
			$c->app->log->debug("skipping id");
			next;
		}
		unless(exists($fields->{$tuple[0]})) {
			$c->app->log->debug("skipping unknown field " . $tuple[0]);
			next;
		}
		my $update = $tuple[0] . " = ?";
		push @updates, $update;
		push @args, $tuple[1];
	}
	my $updates = join(', ', @updates);
	my $dbh = $c->dbh;
	my $res;
	my $query = "UPDATE $tablename SET $updates WHERE id = ? RETURNING $tablename.*";
	eval {
		$res = db_query($dbh, $query ,@args, $json->{id});
	};
	if($@) {
		$c->app->log->warn("error running $query: " . $dbh->errstr);
		$c->render(openapi => {errors => [{message => "error communicating with database"}]}, status => 500);
		return;
	}

	if(scalar(@$res) < 1) {
		$c->render(openapi => {errors => [{message => "not found"}]}, status => 404);
		return;
	}
	my $result = $res->[0];
	foreach my $field(keys %$fields) {
		next unless exists($fields->{$field}{format});
		if($fields->{$field}{format} eq "date-time") {
			# PostgreSQL never uses the T in date-time
			# fields unless we're encoding JSON. Doing that
			# makes Mojo::JSON unhappy. Not doing that makes
			# OpenAPI unhappy about the lack of the T.
			#
                        # JSON makes me unhappy.
                        $c->app->log->debug("changing date; before: ");
                        $c->app->log->debug($result->{$field});
			$result->{$field} = DateTime::Format::Pg->parse_datetime($result->{$field})->iso8601() or die;
                        $c->app->log->debug("after: " . $result->{$field});
		}
	}
	if(defined($fixup)) {
		&$fixup($res->[0]);
	}

	$c->render(openapi => $res->[0]);
}

sub add_with_json {
	my ($c, $json, $tablename, $fields, $fixup) = @_;

	my @args;
	my @inserts;

	if(exists($json->{id})) {
		delete $json->{id};
	}

	while(my @tuple = each %$json) {
		next if($tuple[0] eq "id");
		next unless(exists($fields->{$tuple[0]}));
		push @inserts, $tuple[0];
		push @args, $tuple[1];
	}

	my $inserts = join(', ', @inserts);
	my $fieldlist;
	if(scalar(@inserts) > 0) {
		$fieldlist = "?, " x (scalar(@inserts) - 1) . "?";
	} else {
		$fieldlist = "";
	}
	my $dbh = $c->dbh;
	my $res;
	eval {
		$res = db_query($dbh, "INSERT INTO $tablename($inserts) VALUES($fieldlist) RETURNING $tablename.*", @args);
	};

	if(!defined($res) || scalar(@$res) < 1) {
		$c->render(openapi => {errors => [{message => "failed to add data: " . $dbh->errstr}]}, status => 400);
		return;
	}
	my $result = $res->[0];
	foreach my $field(keys %$fields) {
		next unless exists($fields->{$field}{format});
		if($fields->{$field}{format} eq "date-time") {
			# PostgreSQL never uses the T in date-time
			# fields unless we're encoding JSON. Doing that
			# makes Mojo::JSON unhappy. Not doing that makes
			# OpenAPI unhappy about the lack of the T.
			#
                        # JSON makes me unhappy.
                        $c->app->log->debug("changing date; before: ");
                        $c->app->log->debug($result->{$field});
			$result->{$field} = DateTime::Format::Pg->parse_datetime($result->{$field})->iso8601() or die;
                        $c->app->log->debug("after: " . $result->{$field});
		}
	}
	if(defined($fixup)) {
		&$fixup($res->[0]);
	}

	$c->render(openapi => $res->[0]);
}

sub is_authed($c) {
	return defined($c->req->headers->header("X-SReview-Key"));
}