Avatica.pm

filter: Statementstmt 44.9% 22 / 49 Branchbran 0.0% 0 / 16 Conditioncond 0.0% 0 / 8 MC/DCmcdc 0.0% 0 / 5 Subroutinesub 72.7% 8 / 11 Podpod n/a totaltotal 33.7% 30 / 89 CC 12 SCAR 42.0
CC
12
Cov
30%
_client
132.0
driver
6.0
CLONE
2.0
CRAP 67.0
↑ Summary Avatica/Adapter/Phoenix.pm »
1 package DBD::Avatica;
2  
3 # ABSTRACT: Driver for Apache Avatica compatible servers
4  
5 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use vars qw($VERSION $err $errstr $sqlstate $drh);
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 $VERSION = '0.2.3';
11  
12 $drh = undef;
13  
14 0 ▶sub driver {
Subroutine driver: not called CC=2 SCAR=17.9
15 0 ▶ return $drh if $drh;
Branch: 1 branch
BranchTrueFalseTotal
if $DBD::Avatica::drh 0 0 0
16 0 my ($class, $attr) = @_;
17 0 DBI->setup_driver('DBD::Avatica');
18 0 $drh = DBI::_new_drh("${class}::dr", {
19 'Name' => 'Avatica',
20 'Version' => $VERSION,
21 'Err' => \$err,
22 'Errstr' => \$errstr,
23 'State' => \$sqlstate,
24 'Attribution' => "DBD::Avatica $VERSION by skbkontur team"
25 });
26 0 return $drh;
27 }
28  
29 0 ▶sub CLONE {
Subroutine CLONE: not called CC=1 SCAR=6.9
30 0 $drh = undef;
31 }
32  
33 # h - some handle, it may be drh, dbh, sth
34 0 ▶sub _client {
Subroutine _client: not called CC=11 SCAR=48.8
35 0 my ($h, $method) = (shift, shift);
36  
37 0 my $client = $h->FETCH('avatica_client');
38 0 ▶ return unless $client;
Branch: 1 branch
BranchTrueFalseTotal
unless $client 0 0 0
39  
40 0 my $connection_id = $h->FETCH('avatica_connection_id');
41  
42 0 local $SIG{PIPE} = "IGNORE";
43  
44 0 my $is_trace = $h->trace();
45 0 ▶ $h->trace_msg(join('; ', '--> ', $method, ($connection_id // ()), (map { $_ // 'undef' } @_), "\n")) if $is_trace;
Branch: 1 branch
BranchTrueFalseTotal
if $is_trace 0 0 0
Condition0%0/5
$connection_id // ()
l!l&&r!l&&!r
000
$_ // "undef"
l!l
00
MC/DC0%0/2
$connection_id // ()
$connection_id ()
MC/DC0%0/1
$_ // "undef"
$_
Truth table0%0/3
A // B
A= $connection_idB= ()
ABresult
1X1
011
000
Truth table0%0/2
A
A= $_
Aresult
11
00
46  
47 0 ▶ my ($ret, $response) = $client->$method($connection_id // (), @_);
Condition0%0/3
$connection_id // ()
l!l&&r!l&&!r
000
MC/DC0%0/2
$connection_id // ()
$connection_id ()
Truth table0%0/3
A // B
A= $connection_idB= ()
ABresult
1X1
011
000
48  
49 0 ▶ $h->trace_msg(join('; ', '<-- ', $method, ($ret ? ref($response)->encode_json($response) : $response), "\n")) if $is_trace;
Branch: 2 branches
BranchTrueFalseTotal
if $is_trace 0 0 0
$ret ? : 0 0 0
50  
51 0 ▶ unless ($ret) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ret) 0 0 0
52 0 ▶ if ($response->{protocol}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->{'protocol'}) { } 0 0 0
53 0 my ($err, $msg, $state) = @{$response->{protocol}}{qw/error_code message sql_state/};
54 0 my $status = $response->{http_status};
55 0 ▶ $msg = "http status $status, error code $err, sql state $state" unless $msg;
Branch: 1 branch
BranchTrueFalseTotal
unless $msg 0 0 0
56 0 $h->set_err($err, $msg, $state);
57 } else {
58 0 $h->set_err(1, $response->{message});
59 }
60 }
61  
62 0 return ($ret, $response);
63 }
64  
65 package DBD::Avatica::dr;
66  
67 our $imp_data_size = 0;
68  
69 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
70 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
71  
72 2 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
73 0 ▶use Avatica::Client;
Subroutine BEGIN: called CC=1 SCAR=2.6
74  
75 *_client = \&DBD::Avatica::_client;
76  
77 sub connect {
78 my ($drh, $dsn, $user, $pass, $attr) = @_;
79  
80 my %dsn = split /[;=]/, $dsn;
81  
82 my $adapter_name = ucfirst($dsn{adapter_name} // '');
83 return $drh->set_err(1, q{Parameter "adapter_name" is required in dsn}) unless $adapter_name;
84 my $adapter_class_path = "DBD/Avatica/Adapter/${adapter_name}.pm";
85 my $adapter_class = "DBD::Avatica::Adapter::${adapter_name}";
86 return $drh->set_err(1, qq{Adapter for adapter_name param $adapter_name not found}) unless eval { require $adapter_class_path; 1};
87  
88 my $url = $dsn{url};
89 $url = 'http://' . $dsn{'hostname'} . ':' . $dsn{'port'} if !$url && $dsn{'hostname'} && $dsn{'port'};
90 return $drh->set_err(1, q{Missing "url" parameter}) unless $url;
91  
92 my %client_params;
93 $client_params{ua} = delete $attr->{UserAgent} if $attr->{UserAgent};
94 $client_params{max_retries} = delete $attr->{MaxRetries} if $attr->{MaxRetries};
95  
96 my $client = Avatica::Client->new(url => $url, %client_params);
97 my $connection_id = _random_str();
98  
99 $drh->{avatica_client} = $client;
100 my ($ret, $response) = _client($drh, 'open_connection', $connection_id);
101 $drh->{avatica_client} = undef;
102  
103 return unless $ret;
104  
105 my ($outer, $dbh) = DBI::_new_dbh($drh, {
106 'Name' => $dsn
107 });
108  
109 my $adapter = $adapter_class->new(dbh => $dbh);
110 $dbh->{avatica_adapter} = $adapter;
111  
112 $dbh->{avatica_pid} = $$;
113  
114 $dbh->STORE(Active => 1);
115  
116 $dbh->{avatica_client} = $client;
117 $dbh->{avatica_connection_id} = $connection_id;
118 my $connections = $drh->{avatica_connections} || [];
119 push @$connections, $dbh;
120 $drh->{avatica_connections} = $connections;
121  
122 for (qw/AutoCommit ReadOnly TransactionIsolation Catalog Schema/) {
123 $dbh->{$_} = delete $attr->{$_} if exists $attr->{$_};
124 }
125 DBD::Avatica::db::_sync_connection_params($dbh);
126 DBD::Avatica::db::_load_database_properties($dbh);
127  
128 $outer;
129 }
130  
131 sub data_sources { }
132  
133 sub disconnect_all {
134 my $drh = shift;
135 my $connections = $drh->{avatica_connections};
136 return unless $connections && @$connections;
137  
138 my ($dbh, $name);
139 while ($dbh = shift @$connections) {
140 $name = $dbh->{Name};
141 $drh->trace_msg("Disconnecting $name\n", 3);
142 $dbh->disconnect();
143 }
144 }
145  
146 sub _random_str {
147 my @alpha = ('0' .. '9', 'a' .. 'z');
148 return join '', @alpha[ map { rand scalar(@alpha) } 1 .. 30 ];
149 }
150  
151 sub STORE {
152 my ($drh, $attr, $value) = @_;
153 if ($attr =~ m/^avatica_/) {
154 $drh->{$attr} = $value;
155 return 1;
156 }
157 return $drh->SUPER::STORE($attr, $value);
158 }
159  
160 sub FETCH {
161 my ($drh, $attr) = @_;
162 if ($attr =~ m/^avatica_/) {
163 return $drh->{$attr};
164 }
165 return $drh->SUPER::FETCH($attr);
166 }
167  
168 package DBD::Avatica::db;
169  
170 our $imp_data_size = 0;
171  
172 use strict;
173 use warnings;
174  
175 use DBI;
176  
177 *_client = \&DBD::Avatica::_client;
178  
179 sub prepare {
180 my ($dbh, $statement, $attr) = @_;
181  
182 my ($ret, $response) = _client($dbh, 'prepare', $statement);
183 return unless $ret;
184  
185 my $stmt = $response->get_statement;
186 my $statement_id = $stmt->get_id;
187 my $signature = $stmt->get_signature;
188  
189 my ($outer, $sth) = DBI::_new_sth($dbh, {'Statement' => $statement});
190  
191 $sth->STORE(NUM_OF_PARAMS => $signature->parameters_size);
192 $sth->STORE(NUM_OF_FIELDS => undef);
193  
194 $sth->{avatica_client} = $dbh->FETCH('avatica_client');
195 $sth->{avatica_connection_id} = $dbh->FETCH('avatica_connection_id');
196 $sth->{avatica_statement_id} = $statement_id;
197 $sth->{avatica_signature} = $signature;
198 $sth->{avatica_params} = $signature->get_parameters_list;
199 $sth->{avatica_rows} = -1;
200 $sth->{avatica_bind_params} = [];
201 $sth->{avatica_data_done} = 1;
202 $sth->{avatica_data} = [];
203  
204 $outer;
205 }
206  
207 sub ping {
208 my $dbh = shift;
209  
210 my $sth = $dbh->{avatica_cached_stmt_ping};
211 if ($sth && !$sth->FETCH('Active')) {
212 $sth = $dbh->{avatica_cached_stmt_ping};
213 } else {
214 my ($ret, $response) = _client($dbh, 'create_statement');
215 return unless $ret;
216  
217 my $statement_id = $response->get_statement_id;
218  
219 (my $outer, $sth) = DBI::_new_sth($dbh, {'Statement' => 'SELECT 1'});
220 $sth->{avatica_client} = $dbh->FETCH('avatica_client');
221 $sth->{avatica_connection_id} = $dbh->FETCH('avatica_connection_id');
222 $sth->{avatica_statement_id} = $statement_id;
223  
224 $dbh->{avatica_cached_stmt_ping} = $sth;
225 }
226  
227 my ($ret, $response) = _client($dbh, 'prepare_and_execute', $sth->{avatica_statement_id}, 'SELECT 1', undef, DBD::Avatica::st->FETCH_SIZE);
228 return unless $ret;
229  
230 $sth->finish;
231 return 1;
232  
233 # after fix of CALCITE-4900 code below will be more correct
234 # my $sth = $dbh->prepare_cached('SELECT 1') or return 0;
235 # $sth->execute or return 0;
236 # $sth->finish;
237 # return 1;
238 }
239  
240 sub begin_work {
241 my $dbh = shift;
242 $dbh->{avatica_autocommit_at_begin_work} = $dbh->{AutoCommit};
243 return 1 unless $dbh->{AutoCommit};
244 $dbh->{AutoCommit} = 0;
245 return _sync_connection_params($dbh);
246 }
247  
248 sub commit {
249 my $dbh = shift;
250 return 1 if $dbh->{AutoCommit};
251 my ($ret, $response) = _client($dbh, 'commit');
252 return $ret unless $dbh->{avatica_autocommit_at_begin_work};
253 $dbh->{AutoCommit} = 1;
254 unless (_sync_connection_params($dbh)) {
255 warn 'DBD::Avatica::db commit failed: ' . $dbh->errstr if $dbh->{PrintError};
256 # clear errors of setting autocomit = 1, because commit succeed
257 $dbh->set_err(undef, undef, '');
258 }
259 return $ret;
260 }
261  
262 sub rollback {
263 my $dbh = shift;
264 return 1 if $dbh->{AutoCommit};
265 my ($ret, $response) = _client($dbh, 'rollback');
266 return $ret unless $dbh->{avatica_autocommit_at_begin_work};
267 $dbh->{AutoCommit} = 1;
268 unless (_sync_connection_params($dbh)) {
269 warn 'DBD::Avatica::db rollback failed: ' . $dbh->errstr if $dbh->{PrintError};
270 # clear errors of setting autocomit = 1, because rollback succeed
271 $dbh->set_err(undef, undef, '');
272 }
273 return $ret;
274 }
275  
276 sub last_insert_id {
277 my $dbh = shift;
278 return $dbh->{avatica_adapter}->last_insert_id($dbh, @_);
279 }
280  
281 my %get_info_type = (
282 ## Driver information:
283 6 => ['SQL_DRIVER_NAME', 'DBD::Avatica' ],
284 7 => ['SQL_DRIVER_VER', 'DBD_VERSION' ], # magic word
285 14 => ['SQL_SEARCH_PATTERN_ESCAPE', '\\' ],
286 ## DBMS Information
287 17 => ['SQL_DBMS_NAME', 'DBMS_NAME' ], # magic word
288 18 => ['SQL_DBMS_VERSION', 'DBMS_VERSION' ], # magic word
289 ## Data source information
290 ## Supported SQL
291 114 => ['SQL_CATALOG_LOCATION', 0 ],
292 41 => ['SQL_CATALOG_NAME_SEPARATOR', '' ],
293 28 => ['SQL_IDENTIFIER_CASE', 1 ], # SQL_IC_UPPER
294 29 => ['SQL_IDENTIFIER_QUOTE_CHAR', q{"} ],
295 89 => ['SQL_KEYWORDS', 'SQL_KEYWORDS' ], # magic word
296 ## SQL limits
297 ## Scalar function information
298 ## Conversion information - all but BIT, LONGVARBINARY, and LONGVARCHAR
299 );
300 for (keys %get_info_type) {
301 $get_info_type{$get_info_type{$_}->[0]} = $get_info_type{$_};
302 }
303  
304 sub get_info {
305 my ($dbh, $type) = @_;
306 my $res = $get_info_type{$type}[1];
307  
308 if (grep { $res eq $_ } 'DBMS_NAME', 'DBMS_VERSION', 'SQL_KEYWORDS') {
309 _load_database_properties($dbh) unless $dbh->{avatica_info_type_cache};
310 return $dbh->{avatica_info_type_cache}{$res};
311 }
312  
313 if ($res eq 'DBD_VERSION') {
314 my $v = $DBD::Avatica::VERSION;
315 $v =~ s/_/./g; # 1.12.3_4 strip trial/dev symbols
316 $v =~ s/[^0-9.]//g; # strip trial/dev symbols, a-la "-TRIAL" at the end
317 return sprintf '%02d.%02d.%1d%1d%1d%1d', (split(/\./, "${v}.0.0.0.0.0.0"))[0..5];
318 }
319  
320 return $res;
321 }
322  
323 # returned columns:
324 # TABLE_CAT, TABLE_SCHEM, TABLE_NAME, TABLE_TYPE, REMARKS, TYPE_NAME, SELF_REFERENCING_COL_NAME,
325 # REF_GENERATION, INDEX_STATE, IMMUTABLE_ROWS, SALT_BUCKETS, MULTI_TENANT, VIEW_STATEMENT, VIEW_TYPE,
326 # INDEX_TYPE, TRANSACTIONAL, IS_NAMESPACE_MAPPED, GUIDE_POSTS_WIDTH, TRANSACTION_PROVIDER
327 sub table_info {
328 my $dbh = shift;
329 my ($catalog, $schema, $table, $type) = @_;
330  
331 # minimum number of columns
332 my $cols = ['TABLE_CAT', 'TABLE_SCHEM', 'TABLE_NAME', 'TABLE_TYPE', 'REMARKS'];
333  
334 if (
335 defined $catalog && $catalog eq '%' &&
336 defined $schema && $schema eq '' &&
337 defined $table && $table eq ''
338 ) {
339 # returned columns: TABLE_CAT
340 my ($ret, $response) = _client($dbh, 'catalog');
341 return unless $ret;
342 my $sth = _sth_from_result_set($dbh, 'table_info_catalog', $response);
343 my $rows = $sth->fetchall_arrayref;
344 push @$_, (undef) x 4 for @$rows; # fill to the minimum number of columns
345 return _sth_from_data('table_info_catalog', $rows, $cols);
346 }
347  
348 if (
349 defined $catalog && $catalog eq '' &&
350 defined $schema && $schema eq '%' &&
351 defined $table && $table eq ''
352 ) {
353 # returned columns: TABLE_SCHEM, TABLE_CATALOG
354 my ($ret, $response) = _client($dbh, 'schemas');
355 return unless $ret;
356 my $sth = _sth_from_result_set($dbh, 'table_info_schemas', $response);
357 my $rows = $sth->fetchall_arrayref;
358 $_ = [reverse(@$_), (undef) x 3] for @$rows; # fill to the minimum number of columns
359 return _sth_from_data('table_info_schemas', $rows, $cols);
360 }
361  
362 if (
363 defined $catalog && $catalog eq '' &&
364 defined $schema && $schema eq '' &&
365 defined $table && $table eq '' &&
366 defined $type && $type eq '%'
367 ) {
368 # returned columns: TABLE_TYPE
369 my ($ret, $response) = _client($dbh, 'table_types');
370 return unless $ret;
371 my $sth = _sth_from_result_set($dbh, 'table_info_table_types', $response);
372 my $rows = $sth->fetchall_arrayref;
373 $_ = [(undef) x 3, @$_, undef] for @$rows; # fill to the minimum number of columns
374 return _sth_from_data('table_info_table_types', $rows, $cols);
375 }
376  
377 my ($ret, $response) = _client($dbh, 'tables', $catalog, $schema, $table, $type);
378 return unless $ret;
379 return _sth_from_result_set($dbh, 'table_info', $response);
380 }
381  
382 # returned columns:
383 # TABLE_CAT, TABLE_SCHEM, TABLE_NAME, COLUMN_NAME, DATA_TYPE, TYPE_NAME, COLUMN_SIZE, BUFFER_LENGTH,
384 # DECIMAL_DIGITS, NUM_PREC_RADIX, NULLABLE, REMARKS, COLUMN_DEF, SQL_DATA_TYPE, SQL_DATETIME_SUB,
385 # CHAR_OCTET_LENGTH, ORDINAL_POSITION, IS_NULLABLE, SCOPE_CATALOG, SCOPE_SCHEMA, SCOPE_TABLE,
386 # SOURCE_DATA_TYPE, IS_AUTOINCREMENT, ARRAY_SIZE, COLUMN_FAMILY, TYPE_ID, VIEW_CONSTANT, MULTI_TENANT,
387 # KEY_SEQ
388 sub column_info {
389 my $dbh = shift;
390 my ($catalog, $schema, $table, $column) = @_;
391  
392 my ($ret, $response) = _client($dbh, 'columns', $catalog, $schema, $table, $column);
393 return unless $ret;
394  
395 return _sth_from_result_set($dbh, 'column_info', $response);
396 }
397  
398 # returned columns:
399 # TABLE_CAT, TABLE_SCHEM, TABLE_NAME, COLUMN_NAME, KEY_SEQ, PK_NAME,
400 # ASC_OR_DESC, DATA_TYPE, TYPE_NAME, COLUMN_SIZE, TYPE_ID, VIEW_CONSTANT
401 sub primary_key_info {
402 my ($dbh, $catalog, $schema, $table) = @_;
403  
404 my ($ret, $response) = _client($dbh, 'primary_keys', $catalog, $schema, $table);
405 return unless $ret;
406  
407 # extend signature with database specific columns
408 $dbh->{avatica_adapter}->extend_primary_key_info_signature($response->get_signature);
409  
410 return _sth_from_result_set($dbh, 'primary_keys', $response);
411 }
412  
413 sub foreign_key_info { }
414  
415 sub statistics_info { }
416  
417 sub type_info_all { [] }
418  
419 sub _sth_from_data {
420 my ($statement, $rows, $col_names, %attr) = @_;
421 my $sponge = DBI->connect('dbi:Sponge:', '', '', { RaiseError => 1 });
422 my $sth = $sponge->prepare($statement, { rows=>$rows, NAME=>$col_names, %attr });
423 return $sth;
424 }
425  
426 sub _sth_from_result_set {
427 my ($dbh, $operation, $result_set) = @_;
428  
429 my $statement_id = $result_set->get_statement_id;
430 my $signature = $result_set->get_signature;
431 my $num_columns = $signature->columns_size;
432  
433 my ($outer, $sth) = DBI::_new_sth($dbh, {'Statement' => $operation});
434  
435 my $frame = $result_set->get_first_frame;
436 $sth->{avatica_data_done} = $frame->get_done;
437 $sth->{avatica_data} = $frame->get_rows_list;
438 $sth->{avatica_rows} = 0;
439 $sth->{avatica_client} = $dbh->{avatica_client};
440 $sth->{avatica_connection_id} = $dbh->{avatica_connection_id};
441 $sth->{avatica_statement_id} = $statement_id;
442 $sth->{avatica_signature} = $signature;
443  
444 $sth->STORE(NUM_OF_FIELDS => $num_columns);
445 $sth->STORE(Active => 1);
446  
447 $outer;
448 }
449  
450 sub _sync_connection_params {
451 my $dbh = shift;
452 my %props = map { $_ => $dbh->{$_} }
453 grep { exists $dbh->{$_} }
454 qw/AutoCommit ReadOnly TransactionIsolation Catalog Schema/;
455  
456 my ($ret, $response) = _client($dbh, 'connection_sync', \%props);
457 return unless $ret;
458  
459 my $props = $response->get_conn_props;
460 $dbh->{AutoCommit} = $props->get_auto_commit if $props->has_auto_commit;
461 $dbh->{ReadOnly} = $props->get_read_only if $props->has_read_only;
462 $dbh->{TransactionIsolation} = $props->get_transaction_isolation;
463 $dbh->{Catalog} = $props->get_catalog if $props->get_catalog;
464 $dbh->{Schema} = $props->get_schema if $props->get_schema;
465 return 1;
466 }
467  
468 sub _load_database_properties {
469 my $dbh = shift;
470 my ($ret, $response) = _client($dbh, 'database_property');
471 return unless $ret;
472 my $props = $dbh->{avatica_adapter}->map_database_properties($response->get_props_list);
473 $dbh->{$_} = $props->{$_} for qw/AVATICA_DRIVER_NAME AVATICA_DRIVER_VERSION/;
474 $dbh->{avatica_info_type_cache}{$_} = $props->{$_} for qw/DBMS_NAME DBMS_VERSION SQL_KEYWORDS/;
475 }
476  
477 sub disconnect {
478 my $dbh = shift;
479 return 1 unless $dbh->FETCH('Active');
480  
481 delete $dbh->{avatica_cached_stmt_ping};
482  
483 $dbh->STORE(Active => 0);
484  
485 if ($dbh->{avatica_pid} != $$) {
486 $dbh->{avatica_client} = undef;
487 return 1;
488 }
489  
490 my ($ret, $response) = _client($dbh, 'close_connection');
491 $dbh->{avatica_client} = undef;
492  
493 return $ret;
494 }
495  
496 sub STORE {
497 my ($dbh, $attr, $value) = @_;
498 if (grep { $attr eq $_ } ('AutoCommit', 'ReadOnly', 'TransactionIsolation', 'Catalog', 'Schema')) {
499 $dbh->{$attr} = $value;
500 _sync_connection_params($dbh);
501 return 1;
502 }
503 if ($attr =~ m/^avatica_/) {
504 $dbh->{$attr} = $value;
505 return 1;
506 }
507 # READ ONLY attributes
508 return 0 if grep { $attr eq $_ } qw/AVATICA_DRIVER_NAME AVATICA_DRIVER_VERSION/;
509 return $dbh->SUPER::STORE($attr, $value);
510 }
511  
512 sub FETCH {
513 my ($dbh, $attr) = @_;
514 if ($attr =~ m/^avatica_/) {
515 return $dbh->{$attr};
516 }
517 if (grep { $attr eq $_ }
518 qw/AutoCommit ReadOnly TransactionIsolation Catalog Schema AVATICA_DRIVER_NAME AVATICA_DRIVER_VERSION/) {
519 return $dbh->{$attr};
520 }
521 return $dbh->SUPER::FETCH($attr);
522 }
523  
524 sub DESTROY {
525 my $dbh = shift;
526 return unless $dbh->FETCH('Active');
527 return if $dbh->FETCH('InactiveDestroy');
528 eval { $dbh->disconnect() };
529 }
530  
531 package DBD::Avatica::st;
532  
533 our $imp_data_size = 0;
534  
535 use strict;
536 use warnings;
537  
538 use DBI;
539  
540 use constant FETCH_SIZE => 2000;
541 use constant BATCH_SIZE => 2000;
542  
543 *_client = \&DBD::Avatica::_client;
544  
545  
546 sub bind_param {
547 my ($sth, $param, $value, $attr) = @_;
548  
549 # at the moment the type is not processed because we know type from prepare request
550 # my ($type) = (ref $attr) ? $attr->{'TYPE'} : $attr;
551  
552 my $params = $sth->{avatica_bind_params};
553 $params->[$param - 1] = $value;
554 1;
555 }
556  
557 sub execute {
558 my ($sth, @bind_values) = @_;
559  
560 my $bind_params = $sth->{avatica_bind_params};
561 @bind_values = @$bind_params if !@bind_values && $bind_params && @$bind_params;
562  
563 my $num_params = $sth->FETCH('NUM_OF_PARAMS');
564 return $sth->set_err(1, 'Wrong number of parameters') if @bind_values != $num_params;
565  
566 my $statement_id = $sth->{avatica_statement_id};
567 my $signature = $sth->{avatica_signature};
568  
569 my $dbh = $sth->{Database};
570 my $mapped_params = $dbh->{avatica_adapter}->row_to_jdbc(\@bind_values, $sth->{avatica_params});
571  
572 my ($ret, $response) = _client($sth, 'execute', $statement_id, $signature, $mapped_params, DBD::Avatica::st->FETCH_SIZE);
573 unless ($ret) {
574 return if $num_params != 0 || index($response->{message}, 'NullPointerException') == -1;
575  
576 # https://issues.apache.org/jira/browse/CALCITE-4900
577 # so, workaround, if num_params == 0 then need to use create_statement && prepare_and_execute without params
578  
579 # clear errors
580 $sth->set_err(undef, undef, '');
581  
582 my $sql = $sth->FETCH('Statement');
583  
584 ($ret, $response) = _client($sth, 'create_statement');
585 return unless $ret;
586  
587 _avatica_close_statement($sth);
588 $statement_id = $sth->{avatica_statement_id} = $response->get_statement_id;
589  
590 ($ret, $response) = _client($sth, 'prepare_and_execute', $statement_id, $sql, undef, DBD::Avatica::st->FETCH_SIZE);
591 return unless $ret;
592 }
593  
594 my $result = $response->get_results(0);
595  
596 if ($result->get_own_statement) {
597 my $new_statement_id = $result->get_statement_id;
598 _avatica_close_statement($sth) if $statement_id && $statement_id != $new_statement_id;
599 $sth->{avatica_statement_id} = $new_statement_id;
600 }
601  
602 $signature = $result->get_signature;
603 $sth->{avatica_signature} = $signature if $signature;
604  
605 my $num_updates = $result->get_update_count;
606 $num_updates = -1 if $num_updates == '18446744073709551615'; # max_int
607  
608 if ($num_updates >= 0) {
609 # DML
610 $sth->STORE(Active => 0);
611 $sth->STORE(NUM_OF_FIELDS => 0);
612 $sth->{avatica_rows} = $num_updates;
613 $sth->{avatica_data_done} = 1;
614 $sth->{avatica_data} = [];
615 return $num_updates == 0 ? '0E0' : $num_updates;
616 }
617  
618 # SELECT
619 my $frame = $result->get_first_frame;
620 $sth->{avatica_data_done} = $frame->get_done;
621 $sth->{avatica_data} = $frame->get_rows_list;
622 $sth->{avatica_rows} = 0;
623  
624 my $num_columns = $signature->columns_size;
625 $sth->STORE(Active => 1);
626 $sth->STORE(NUM_OF_FIELDS => $num_columns);
627  
628 return 1;
629 }
630  
631 sub _execute_batch {
632 my ($sth, $rows) = @_;
633  
634 my $statement_id = $sth->{avatica_statement_id};
635 my $signature = $sth->{avatica_signature};
636  
637 my $dbh = $sth->{Database};
638 my $mapped_params = [
639 map {
640 $dbh->{avatica_adapter}->row_to_jdbc($_, $sth->{avatica_params});
641 }
642 @$rows
643 ];
644  
645 my ($ret, $response) = _client($sth, 'execute_batch', $statement_id, $mapped_params);
646 return unless $ret;
647  
648 my $updates = $response->get_update_counts_list;
649 # 18446744073709551615 is max int64
650 return [map { $_ == '18446744073709551615' ? -1 : $_ } @$updates]
651 }
652  
653 sub execute_for_fetch {
654 my ($sth, $fetch_tuple_sub, $tuple_status) = @_;
655 # start with empty status array
656 ($tuple_status) ? @$tuple_status = () : $tuple_status = [];
657  
658 my ($tuples, $rc_total) = (0, 0);
659 my $err_count;
660 while (1) {
661 my ($rows, $rows_count) = ([], 0);
662  
663 while (my $tuple = &$fetch_tuple_sub()) {
664 push @$rows, $tuple;
665 ++$rows_count;
666 last if $rows_count >= DBD::Avatica::st->BATCH_SIZE;
667 }
668 last unless @$rows;
669  
670 $tuples += @$rows;
671  
672 if ( my $many_rc = _execute_batch($sth, $rows) ) {
673 push @$tuple_status, @$many_rc;
674 for my $rc (@$many_rc) {
675 $rc_total = ($rc >= 0 && $rc_total >= 0) ? $rc_total + $rc : -1;
676 }
677 } else {
678 $err_count += @$rows;
679 my $status = [ $sth->err, $sth->errstr, $sth->state ];
680 push @$tuple_status, $status for @$rows;
681 }
682  
683 last if @$rows < DBD::Avatica::st->BATCH_SIZE;
684 }
685  
686 return $sth->set_err($DBI::stderr, "executing $tuples generated $err_count errors") if $err_count;
687 $tuples ||= "0E0";
688  
689 return $tuples unless wantarray;
690 return ($tuples, $rc_total);
691 }
692  
693 sub fetch {
694 my ($sth) = @_;
695  
696 my $signature = $sth->{avatica_signature};
697  
698 my $avatica_rows_list = $sth->{avatica_data};
699 my $avatica_rows_done = $sth->{avatica_data_done};
700  
701 if ((!$avatica_rows_list || !@$avatica_rows_list) && !$avatica_rows_done) {
702 my $statement_id = $sth->{avatica_statement_id};
703 my ($ret, $response) = _client($sth, 'fetch', $statement_id, undef, DBD::Avatica::st->FETCH_SIZE);
704 return unless $ret;
705  
706 my $frame = $response->get_frame;
707 $sth->{avatica_data_done} = $frame->get_done;
708 $sth->{avatica_data} = $frame->get_rows_list;
709  
710 $avatica_rows_done = $sth->{avatica_data_done};
711 $avatica_rows_list = $sth->{avatica_data};
712 }
713  
714 if ($avatica_rows_list && @$avatica_rows_list) {
715 $sth->{avatica_rows} += 1;
716 my $dbh = $sth->{Database};
717 my $avatica_row = shift @$avatica_rows_list;
718 my $values = $avatica_row->get_value_list;
719 my $columns = $signature->get_columns_list;
720 my $row = $dbh->{avatica_adapter}->row_from_jdbc($values, $columns);
721 return $sth->_set_fbav($row);
722 }
723  
724 $sth->finish;
725 return;
726 }
727 *fetchrow_arrayref = \&fetch;
728  
729 sub rows {
730 shift->{avatica_rows}
731 }
732  
733 # It seems that here need to call _avatica_close_statement method,
734 # but then such a scenario will not work
735 # when there are many "execute" commands for one "prepare" command.
736 # Therefore, we will not do this here.
737 sub finish {
738 my $sth = shift;
739 $sth->STORE(Active => 0);
740 1;
741 }
742  
743 sub STORE {
744 my ($sth, $attr, $value) = @_;
745 if ($attr =~ m/^avatica_/) {
746 $sth->{$attr} = $value;
747 return 1;
748 }
749 return $sth->SUPER::STORE($attr, $value);
750 }
751  
752 sub FETCH {
753 my ($sth, $attr) = @_;
754 if ($attr =~ m/^avatica_/) {
755 return $sth->{$attr};
756 }
757 if ($attr eq 'NAME') {
758 return $sth->{avatica_cache_name} ||=
759 [map { $_->get_label // $_->get_column_name } @{$sth->{avatica_signature}->get_columns_list}];
760 }
761 if ($attr eq 'TYPE') {
762 my $dbh = $sth->{Database};
763 return $sth->{avatica_cache_type} ||=
764 [map { $dbh->{avatica_adapter}->to_dbi($_->get_type) } @{$sth->{avatica_signature}->get_columns_list}];
765 }
766 if ($attr eq 'PRECISION') {
767 return $sth->{avatica_cache_precision} ||=
768 [map { $_->get_display_size } @{$sth->{avatica_signature}->get_columns_list}];
769 }
770 if ($attr eq 'SCALE') {
771 return $sth->{avatica_cache_scale} ||=
772 [map { $_->get_scale || undef } @{$sth->{avatica_signature}->get_columns_list}];
773 }
774 if ($attr eq 'NULLABLE') {
775 return $sth->{avatica_cache_nullable} ||=
776 [map { $_->get_nullable} @{$sth->{avatica_signature}->get_columns_list}];
777 }
778 if ($attr eq 'ParamValues') {
779 return $sth->{avatica_cache_paramvalues} ||=
780 {map { $_ => ($sth->{avatica_bind_params}->[$_ - 1] // undef) } 1 .. @{$sth->{avatica_params} // []}};
781 }
782 return $sth->SUPER::FETCH($attr);
783 }
784  
785 sub _avatica_close_statement {
786 my $sth = shift;
787 my $statement_id = $sth->{avatica_statement_id};
788 _client($sth, 'close_statement', $statement_id) if $statement_id && $sth->FETCH('Database')->{avatica_pid} == $$;
789 $sth->{avatica_statement_id} = undef;
790 }
791  
792 sub DESTROY {
793 my $sth = shift;
794 return if $sth->FETCH('InactiveDestroy');
795 return unless $sth->FETCH('Database')->FETCH('Active');
796 eval { _avatica_close_statement($sth) };
797 $sth->finish;
798 }
799  
800 1;
801  
802 __END__
↑ Summary Avatica/Adapter/Phoenix.pm »