/
Avatica.pm
1746 lines (1221 loc) · 56.4 KB
/
Avatica.pm
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package DBD::Avatica;
# ABSTRACT: Driver for Apache Avatica compatible servers
use strict;
use warnings;
use DBI;
use vars qw($VERSION $err $errstr $sqlstate $drh);
$VERSION = '0.2.2';
$drh = undef;
sub driver {
return $drh if $drh;
my ($class, $attr) = @_;
DBI->setup_driver('DBD::Avatica');
$drh = DBI::_new_drh("${class}::dr", {
'Name' => 'Avatica',
'Version' => $VERSION,
'Err' => \$err,
'Errstr' => \$errstr,
'State' => \$sqlstate,
'Attribution' => "DBD::Avatica $VERSION by skbkontur team"
});
return $drh;
}
sub CLONE {
$drh = undef;
}
# h - some handle, it may be drh, dbh, sth
sub _client {
my ($h, $method) = (shift, shift);
my $client = $h->FETCH('avatica_client');
return unless $client;
my $connection_id = $h->FETCH('avatica_connection_id');
local $SIG{PIPE} = "IGNORE";
my $is_trace = $h->trace();
$h->trace_msg(join('; ', '--> ', $method, ($connection_id // ()), (map { $_ // 'undef' } @_), "\n")) if $is_trace;
my ($ret, $response) = $client->$method($connection_id // (), @_);
$h->trace_msg(join('; ', '<-- ', $method, ($ret ? ref($response)->encode_json($response) : $response), "\n")) if $is_trace;
unless ($ret) {
if ($response->{protocol}) {
my ($err, $msg, $state) = @{$response->{protocol}}{qw/error_code message sql_state/};
my $status = $response->{http_status};
$msg = "http status $status, error code $err, sql state $state" unless $msg;
$h->set_err($err, $msg, $state);
} else {
$h->set_err(1, $response->{message});
}
}
return ($ret, $response);
}
package DBD::Avatica::dr;
our $imp_data_size = 0;
use strict;
use warnings;
use DBI;
use Avatica::Client;
*_client = \&DBD::Avatica::_client;
sub connect {
my ($drh, $dsn, $user, $pass, $attr) = @_;
my %dsn = split /[;=]/, $dsn;
my $adapter_name = ucfirst($dsn{adapter_name} // '');
return $drh->set_err(1, q{Parameter "adapter_name" is required in dsn}) unless $adapter_name;
my $adapter_class_path = "DBD/Avatica/Adapter/${adapter_name}.pm";
my $adapter_class = "DBD::Avatica::Adapter::${adapter_name}";
return $drh->set_err(1, qq{Adapter for adapter_name param $adapter_name not found}) unless eval { require $adapter_class_path; 1};
my $url = $dsn{url};
$url = 'http://' . $dsn{'hostname'} . ':' . $dsn{'port'} if !$url && $dsn{'hostname'} && $dsn{'port'};
return $drh->set_err(1, q{Missing "url" parameter}) unless $url;
my %client_params;
$client_params{ua} = delete $attr->{UserAgent} if $attr->{UserAgent};
$client_params{max_retries} = delete $attr->{MaxRetries} if $attr->{MaxRetries};
my $client = Avatica::Client->new(url => $url, %client_params);
my $connection_id = _random_str();
$drh->{avatica_client} = $client;
my ($ret, $response) = _client($drh, 'open_connection', $connection_id);
$drh->{avatica_client} = undef;
return unless $ret;
my ($outer, $dbh) = DBI::_new_dbh($drh, {
'Name' => $dsn
});
my $adapter = $adapter_class->new(dbh => $dbh);
$dbh->{avatica_adapter} = $adapter;
$dbh->{avatica_pid} = $$;
$dbh->STORE(Active => 1);
$dbh->{avatica_client} = $client;
$dbh->{avatica_connection_id} = $connection_id;
my $connections = $drh->{avatica_connections} || [];
push @$connections, $dbh;
$drh->{avatica_connections} = $connections;
for (qw/AutoCommit ReadOnly TransactionIsolation Catalog Schema/) {
$dbh->{$_} = delete $attr->{$_} if exists $attr->{$_};
}
DBD::Avatica::db::_sync_connection_params($dbh);
DBD::Avatica::db::_load_database_properties($dbh);
$outer;
}
sub data_sources { }
sub disconnect_all {
my $drh = shift;
my $connections = $drh->{avatica_connections};
return unless $connections && @$connections;
my ($dbh, $name);
while ($dbh = shift @$connections) {
$name = $dbh->{Name};
$drh->trace_msg("Disconnecting $name\n", 3);
$dbh->disconnect();
}
}
sub _random_str {
my @alpha = ('0' .. '9', 'a' .. 'z');
return join '', @alpha[ map { rand scalar(@alpha) } 1 .. 30 ];
}
sub STORE {
my ($drh, $attr, $value) = @_;
if ($attr =~ m/^avatica_/) {
$drh->{$attr} = $value;
return 1;
}
return $drh->SUPER::STORE($attr, $value);
}
sub FETCH {
my ($drh, $attr) = @_;
if ($attr =~ m/^avatica_/) {
return $drh->{$attr};
}
return $drh->SUPER::FETCH($attr);
}
package DBD::Avatica::db;
our $imp_data_size = 0;
use strict;
use warnings;
use DBI;
*_client = \&DBD::Avatica::_client;
sub prepare {
my ($dbh, $statement, $attr) = @_;
my ($ret, $response) = _client($dbh, 'prepare', $statement);
return unless $ret;
my $stmt = $response->get_statement;
my $statement_id = $stmt->get_id;
my $signature = $stmt->get_signature;
my ($outer, $sth) = DBI::_new_sth($dbh, {'Statement' => $statement});
$sth->STORE(NUM_OF_PARAMS => $signature->parameters_size);
$sth->STORE(NUM_OF_FIELDS => undef);
$sth->{avatica_client} = $dbh->FETCH('avatica_client');
$sth->{avatica_connection_id} = $dbh->FETCH('avatica_connection_id');
$sth->{avatica_statement_id} = $statement_id;
$sth->{avatica_signature} = $signature;
$sth->{avatica_params} = $signature->get_parameters_list;
$sth->{avatica_rows} = -1;
$sth->{avatica_bind_params} = [];
$sth->{avatica_data_done} = 1;
$sth->{avatica_data} = [];
$outer;
}
sub ping {
my $dbh = shift;
my $sth = $dbh->{avatica_cached_stmt_ping};
if ($sth && !$sth->FETCH('Active')) {
$sth = $dbh->{avatica_cached_stmt_ping};
} else {
my ($ret, $response) = _client($dbh, 'create_statement');
return unless $ret;
my $statement_id = $response->get_statement_id;
(my $outer, $sth) = DBI::_new_sth($dbh, {'Statement' => 'SELECT 1'});
$sth->{avatica_client} = $dbh->FETCH('avatica_client');
$sth->{avatica_connection_id} = $dbh->FETCH('avatica_connection_id');
$sth->{avatica_statement_id} = $statement_id;
$dbh->{avatica_cached_stmt_ping} = $sth;
}
my ($ret, $response) = _client($dbh, 'prepare_and_execute', $sth->{avatica_statement_id}, 'SELECT 1', undef, DBD::Avatica::st->FETCH_SIZE);
return unless $ret;
$sth->finish;
return 1;
# after fix of CALCITE-4900 code below will be more correct
# my $sth = $dbh->prepare_cached('SELECT 1') or return 0;
# $sth->execute or return 0;
# $sth->finish;
# return 1;
}
sub begin_work {
my $dbh = shift;
$dbh->{avatica_autocommit_at_begin_work} = $dbh->{AutoCommit};
return 1 unless $dbh->{AutoCommit};
$dbh->{AutoCommit} = 0;
return _sync_connection_params($dbh);
}
sub commit {
my $dbh = shift;
return 1 if $dbh->{AutoCommit};
my ($ret, $response) = _client($dbh, 'commit');
return $ret unless $dbh->{avatica_autocommit_at_begin_work};
$dbh->{AutoCommit} = 1;
unless (_sync_connection_params($dbh)) {
warn 'DBD::Avatica::db commit failed: ' . $dbh->errstr if $dbh->{PrintError};
# clear errors of setting autocomit = 1, because commit succeed
$dbh->set_err(undef, undef, '');
}
return $ret;
}
sub rollback {
my $dbh = shift;
return 1 if $dbh->{AutoCommit};
my ($ret, $response) = _client($dbh, 'rollback');
return $ret unless $dbh->{avatica_autocommit_at_begin_work};
$dbh->{AutoCommit} = 1;
unless (_sync_connection_params($dbh)) {
warn 'DBD::Avatica::db rollback failed: ' . $dbh->errstr if $dbh->{PrintError};
# clear errors of setting autocomit = 1, because rollback succeed
$dbh->set_err(undef, undef, '');
}
return $ret;
}
sub last_insert_id {
my $dbh = shift;
return $dbh->{avatica_adapter}->last_insert_id($dbh, @_);
}
my %get_info_type = (
## Driver information:
6 => ['SQL_DRIVER_NAME', 'DBD::Avatica' ],
7 => ['SQL_DRIVER_VER', 'DBD_VERSION' ], # magic word
14 => ['SQL_SEARCH_PATTERN_ESCAPE', '\\' ],
## DBMS Information
17 => ['SQL_DBMS_NAME', 'DBMS_NAME' ], # magic word
18 => ['SQL_DBMS_VERSION', 'DBMS_VERSION' ], # magic word
## Data source information
## Supported SQL
114 => ['SQL_CATALOG_LOCATION', 0 ],
41 => ['SQL_CATALOG_NAME_SEPARATOR', '' ],
28 => ['SQL_IDENTIFIER_CASE', 1 ], # SQL_IC_UPPER
29 => ['SQL_IDENTIFIER_QUOTE_CHAR', q{"} ],
89 => ['SQL_KEYWORDS', 'SQL_KEYWORDS' ], # magic word
## SQL limits
## Scalar function information
## Conversion information - all but BIT, LONGVARBINARY, and LONGVARCHAR
);
for (keys %get_info_type) {
$get_info_type{$get_info_type{$_}->[0]} = $get_info_type{$_};
}
sub get_info {
my ($dbh, $type) = @_;
my $res = $get_info_type{$type}[1];
if (grep { $res eq $_ } 'DBMS_NAME', 'DBMS_VERSION', 'SQL_KEYWORDS') {
_load_database_properties($dbh) unless $dbh->{avatica_info_type_cache};
return $dbh->{avatica_info_type_cache}{$res};
}
if ($res eq 'DBD_VERSION') {
my $v = $DBD::Avatica::VERSION;
$v =~ s/_/./g; # 1.12.3_4 strip trial/dev symbols
$v =~ s/[^0-9.]//g; # strip trial/dev symbols, a-la "-TRIAL" at the end
return sprintf '%02d.%02d.%1d%1d%1d%1d', (split(/\./, "${v}.0.0.0.0.0.0"))[0..5];
}
return $res;
}
# returned columns:
# TABLE_CAT, TABLE_SCHEM, TABLE_NAME, TABLE_TYPE, REMARKS, TYPE_NAME, SELF_REFERENCING_COL_NAME,
# REF_GENERATION, INDEX_STATE, IMMUTABLE_ROWS, SALT_BUCKETS, MULTI_TENANT, VIEW_STATEMENT, VIEW_TYPE,
# INDEX_TYPE, TRANSACTIONAL, IS_NAMESPACE_MAPPED, GUIDE_POSTS_WIDTH, TRANSACTION_PROVIDER
sub table_info {
my $dbh = shift;
my ($catalog, $schema, $table, $type) = @_;
# minimum number of columns
my $cols = ['TABLE_CAT', 'TABLE_SCHEM', 'TABLE_NAME', 'TABLE_TYPE', 'REMARKS'];
if (
defined $catalog && $catalog eq '%' &&
defined $schema && $schema eq '' &&
defined $table && $table eq ''
) {
# returned columns: TABLE_CAT
my ($ret, $response) = _client($dbh, 'catalog');
return unless $ret;
my $sth = _sth_from_result_set($dbh, 'table_info_catalog', $response);
my $rows = $sth->fetchall_arrayref;
push @$_, (undef) x 4 for @$rows; # fill to the minimum number of columns
return _sth_from_data('table_info_catalog', $rows, $cols);
}
if (
defined $catalog && $catalog eq '' &&
defined $schema && $schema eq '%' &&
defined $table && $table eq ''
) {
# returned columns: TABLE_SCHEM, TABLE_CATALOG
my ($ret, $response) = _client($dbh, 'schemas');
return unless $ret;
my $sth = _sth_from_result_set($dbh, 'table_info_schemas', $response);
my $rows = $sth->fetchall_arrayref;
$_ = [reverse(@$_), (undef) x 3] for @$rows; # fill to the minimum number of columns
return _sth_from_data('table_info_schemas', $rows, $cols);
}
if (
defined $catalog && $catalog eq '' &&
defined $schema && $schema eq '' &&
defined $table && $table eq '' &&
defined $type && $type eq '%'
) {
# returned columns: TABLE_TYPE
my ($ret, $response) = _client($dbh, 'table_types');
return unless $ret;
my $sth = _sth_from_result_set($dbh, 'table_info_table_types', $response);
my $rows = $sth->fetchall_arrayref;
$_ = [(undef) x 3, @$_, undef] for @$rows; # fill to the minimum number of columns
return _sth_from_data('table_info_table_types', $rows, $cols);
}
my ($ret, $response) = _client($dbh, 'tables', $catalog, $schema, $table, $type);
return unless $ret;
return _sth_from_result_set($dbh, 'table_info', $response);
}
# returned columns:
# TABLE_CAT, TABLE_SCHEM, TABLE_NAME, COLUMN_NAME, DATA_TYPE, TYPE_NAME, COLUMN_SIZE, BUFFER_LENGTH,
# DECIMAL_DIGITS, NUM_PREC_RADIX, NULLABLE, REMARKS, COLUMN_DEF, SQL_DATA_TYPE, SQL_DATETIME_SUB,
# CHAR_OCTET_LENGTH, ORDINAL_POSITION, IS_NULLABLE, SCOPE_CATALOG, SCOPE_SCHEMA, SCOPE_TABLE,
# SOURCE_DATA_TYPE, IS_AUTOINCREMENT, ARRAY_SIZE, COLUMN_FAMILY, TYPE_ID, VIEW_CONSTANT, MULTI_TENANT,
# KEY_SEQ
sub column_info {
my $dbh = shift;
my ($catalog, $schema, $table, $column) = @_;
my ($ret, $response) = _client($dbh, 'columns', $catalog, $schema, $table, $column);
return unless $ret;
return _sth_from_result_set($dbh, 'column_info', $response);
}
# returned columns:
# TABLE_CAT, TABLE_SCHEM, TABLE_NAME, COLUMN_NAME, KEY_SEQ, PK_NAME,
# ASC_OR_DESC, DATA_TYPE, TYPE_NAME, COLUMN_SIZE, TYPE_ID, VIEW_CONSTANT
sub primary_key_info {
my ($dbh, $catalog, $schema, $table) = @_;
my ($ret, $response) = _client($dbh, 'primary_keys', $catalog, $schema, $table);
return unless $ret;
# extend signature with database specific columns
$dbh->{avatica_adapter}->extend_primary_key_info_signature($response->get_signature);
return _sth_from_result_set($dbh, 'primary_keys', $response);
}
sub foreign_key_info { }
sub statistics_info { }
sub type_info_all { [] }
sub _sth_from_data {
my ($statement, $rows, $col_names, %attr) = @_;
my $sponge = DBI->connect('dbi:Sponge:', '', '', { RaiseError => 1 });
my $sth = $sponge->prepare($statement, { rows=>$rows, NAME=>$col_names, %attr });
return $sth;
}
sub _sth_from_result_set {
my ($dbh, $operation, $result_set) = @_;
my $statement_id = $result_set->get_statement_id;
my $signature = $result_set->get_signature;
my $num_columns = $signature->columns_size;
my ($outer, $sth) = DBI::_new_sth($dbh, {'Statement' => $operation});
my $frame = $result_set->get_first_frame;
$sth->{avatica_data_done} = $frame->get_done;
$sth->{avatica_data} = $frame->get_rows_list;
$sth->{avatica_rows} = 0;
$sth->{avatica_client} = $dbh->{avatica_client};
$sth->{avatica_connection_id} = $dbh->{avatica_connection_id};
$sth->{avatica_statement_id} = $statement_id;
$sth->{avatica_signature} = $signature;
$sth->STORE(NUM_OF_FIELDS => $num_columns);
$sth->STORE(Active => 1);
$outer;
}
sub _sync_connection_params {
my $dbh = shift;
my %props = map { $_ => $dbh->{$_} }
grep { exists $dbh->{$_} }
qw/AutoCommit ReadOnly TransactionIsolation Catalog Schema/;
my ($ret, $response) = _client($dbh, 'connection_sync', \%props);
return unless $ret;
my $props = $response->get_conn_props;
$dbh->{AutoCommit} = $props->get_auto_commit if $props->has_auto_commit;
$dbh->{ReadOnly} = $props->get_read_only if $props->has_read_only;
$dbh->{TransactionIsolation} = $props->get_transaction_isolation;
$dbh->{Catalog} = $props->get_catalog if $props->get_catalog;
$dbh->{Schema} = $props->get_schema if $props->get_schema;
return 1;
}
sub _load_database_properties {
my $dbh = shift;
my ($ret, $response) = _client($dbh, 'database_property');
return unless $ret;
my $props = $dbh->{avatica_adapter}->map_database_properties($response->get_props_list);
$dbh->{$_} = $props->{$_} for qw/AVATICA_DRIVER_NAME AVATICA_DRIVER_VERSION/;
$dbh->{avatica_info_type_cache}{$_} = $props->{$_} for qw/DBMS_NAME DBMS_VERSION SQL_KEYWORDS/;
}
sub disconnect {
my $dbh = shift;
return 1 unless $dbh->FETCH('Active');
delete $dbh->{avatica_cached_stmt_ping};
$dbh->STORE(Active => 0);
if ($dbh->{avatica_pid} != $$) {
$dbh->{avatica_client} = undef;
return 1;
}
my ($ret, $response) = _client($dbh, 'close_connection');
$dbh->{avatica_client} = undef;
return $ret;
}
sub STORE {
my ($dbh, $attr, $value) = @_;
if (grep { $attr eq $_ } ('AutoCommit', 'ReadOnly', 'TransactionIsolation', 'Catalog', 'Schema')) {
$dbh->{$attr} = $value;
_sync_connection_params($dbh);
return 1;
}
if ($attr =~ m/^avatica_/) {
$dbh->{$attr} = $value;
return 1;
}
# READ ONLY attributes
return 0 if grep { $attr eq $_ } qw/AVATICA_DRIVER_NAME AVATICA_DRIVER_VERSION/;
return $dbh->SUPER::STORE($attr, $value);
}
sub FETCH {
my ($dbh, $attr) = @_;
if ($attr =~ m/^avatica_/) {
return $dbh->{$attr};
}
if (grep { $attr eq $_ }
qw/AutoCommit ReadOnly TransactionIsolation Catalog Schema AVATICA_DRIVER_NAME AVATICA_DRIVER_VERSION/) {
return $dbh->{$attr};
}
return $dbh->SUPER::FETCH($attr);
}
sub DESTROY {
my $dbh = shift;
return unless $dbh->FETCH('Active');
return if $dbh->FETCH('InactiveDestroy');
eval { $dbh->disconnect() };
}
package DBD::Avatica::st;
our $imp_data_size = 0;
use strict;
use warnings;
use DBI;
use constant FETCH_SIZE => 2000;
use constant BATCH_SIZE => 2000;
*_client = \&DBD::Avatica::_client;
sub bind_param {
my ($sth, $param, $value, $attr) = @_;
# at the moment the type is not processed because we know type from prepare request
# my ($type) = (ref $attr) ? $attr->{'TYPE'} : $attr;
my $params = $sth->{avatica_bind_params};
$params->[$param - 1] = $value;
1;
}
sub execute {
my ($sth, @bind_values) = @_;
my $bind_params = $sth->{avatica_bind_params};
@bind_values = @$bind_params if !@bind_values && $bind_params && @$bind_params;
my $num_params = $sth->FETCH('NUM_OF_PARAMS');
return $sth->set_err(1, 'Wrong number of parameters') if @bind_values != $num_params;
my $statement_id = $sth->{avatica_statement_id};
my $signature = $sth->{avatica_signature};
my $dbh = $sth->{Database};
my $mapped_params = $dbh->{avatica_adapter}->row_to_jdbc(\@bind_values, $sth->{avatica_params});
my ($ret, $response) = _client($sth, 'execute', $statement_id, $signature, $mapped_params, DBD::Avatica::st->FETCH_SIZE);
unless ($ret) {
return if $num_params != 0 || index($response->{message}, 'NullPointerException') == -1;
# https://issues.apache.org/jira/browse/CALCITE-4900
# so, workaround, if num_params == 0 then need to use create_statement && prepare_and_execute without params
# clear errors
$sth->set_err(undef, undef, '');
my $sql = $sth->FETCH('Statement');
($ret, $response) = _client($sth, 'create_statement');
return unless $ret;
_avatica_close_statement($sth);
$statement_id = $sth->{avatica_statement_id} = $response->get_statement_id;
($ret, $response) = _client($sth, 'prepare_and_execute', $statement_id, $sql, undef, DBD::Avatica::st->FETCH_SIZE);
return unless $ret;
}
my $result = $response->get_results(0);
if ($result->get_own_statement) {
my $new_statement_id = $result->get_statement_id;
_avatica_close_statement($sth) if $statement_id && $statement_id != $new_statement_id;
$sth->{avatica_statement_id} = $new_statement_id;
}
$signature = $result->get_signature;
$sth->{avatica_signature} = $signature if $signature;
my $num_updates = $result->get_update_count;
$num_updates = -1 if $num_updates == '18446744073709551615'; # max_int
if ($num_updates >= 0) {
# DML
$sth->STORE(Active => 0);
$sth->STORE(NUM_OF_FIELDS => 0);
$sth->{avatica_rows} = $num_updates;
$sth->{avatica_data_done} = 1;
$sth->{avatica_data} = [];
return $num_updates == 0 ? '0E0' : $num_updates;
}
# SELECT
my $frame = $result->get_first_frame;
$sth->{avatica_data_done} = $frame->get_done;
$sth->{avatica_data} = $frame->get_rows_list;
$sth->{avatica_rows} = 0;
my $num_columns = $signature->columns_size;
$sth->STORE(Active => 1);
$sth->STORE(NUM_OF_FIELDS => $num_columns);
return 1;
}
sub _execute_batch {
my ($sth, $rows) = @_;
my $statement_id = $sth->{avatica_statement_id};
my $signature = $sth->{avatica_signature};
my $dbh = $sth->{Database};
my $mapped_params = [
map {
$dbh->{avatica_adapter}->row_to_jdbc($_, $sth->{avatica_params});
}
@$rows
];
my ($ret, $response) = _client($sth, 'execute_batch', $statement_id, $mapped_params);
return unless $ret;
my $updates = $response->get_update_counts_list;
# 18446744073709551615 is max int64
return [map { $_ == '18446744073709551615' ? -1 : $_ } @$updates]
}
sub execute_for_fetch {
my ($sth, $fetch_tuple_sub, $tuple_status) = @_;
# start with empty status array
($tuple_status) ? @$tuple_status = () : $tuple_status = [];
my ($tuples, $rc_total) = (0, 0);
my $err_count;
while (1) {
my ($rows, $rows_count) = ([], 0);
while (my $tuple = &$fetch_tuple_sub()) {
push @$rows, $tuple;
++$rows_count;
last if $rows_count >= DBD::Avatica::st->BATCH_SIZE;
}
last unless @$rows;
$tuples += @$rows;
if ( my $many_rc = _execute_batch($sth, $rows) ) {
push @$tuple_status, @$many_rc;
for my $rc (@$many_rc) {
$rc_total = ($rc >= 0 && $rc_total >= 0) ? $rc_total + $rc : -1;
}
} else {
$err_count += @$rows;
my $status = [ $sth->err, $sth->errstr, $sth->state ];
push @$tuple_status, $status for @$rows;
}
last if @$rows < DBD::Avatica::st->BATCH_SIZE;
}
return $sth->set_err($DBI::stderr, "executing $tuples generated $err_count errors") if $err_count;
$tuples ||= "0E0";
return $tuples unless wantarray;
return ($tuples, $rc_total);
}
sub fetch {
my ($sth) = @_;
my $signature = $sth->{avatica_signature};
my $avatica_rows_list = $sth->{avatica_data};
my $avatica_rows_done = $sth->{avatica_data_done};
if ((!$avatica_rows_list || !@$avatica_rows_list) && !$avatica_rows_done) {
my $statement_id = $sth->{avatica_statement_id};
my ($ret, $response) = _client($sth, 'fetch', $statement_id, undef, DBD::Avatica::st->FETCH_SIZE);
return unless $ret;
my $frame = $response->get_frame;
$sth->{avatica_data_done} = $frame->get_done;
$sth->{avatica_data} = $frame->get_rows_list;
$avatica_rows_done = $sth->{avatica_data_done};
$avatica_rows_list = $sth->{avatica_data};
}
if ($avatica_rows_list && @$avatica_rows_list) {
$sth->{avatica_rows} += 1;
my $dbh = $sth->{Database};
my $avatica_row = shift @$avatica_rows_list;
my $values = $avatica_row->get_value_list;
my $columns = $signature->get_columns_list;
my $row = $dbh->{avatica_adapter}->row_from_jdbc($values, $columns);
return $sth->_set_fbav($row);
}
$sth->finish;
return;
}
*fetchrow_arrayref = \&fetch;
sub rows {
shift->{avatica_rows}
}
# It seems that here need to call _avatica_close_statement method,
# but then such a scenario will not work
# when there are many "execute" commands for one "prepare" command.
# Therefore, we will not do this here.
sub finish {
my $sth = shift;
$sth->STORE(Active => 0);
1;
}
sub STORE {
my ($sth, $attr, $value) = @_;
if ($attr =~ m/^avatica_/) {
$sth->{$attr} = $value;
return 1;
}
return $sth->SUPER::STORE($attr, $value);
}
sub FETCH {
my ($sth, $attr) = @_;
if ($attr =~ m/^avatica_/) {
return $sth->{$attr};
}
if ($attr eq 'NAME') {
return $sth->{avatica_cache_name} ||=
[map { $_->get_column_name } @{$sth->{avatica_signature}->get_columns_list}];
}
if ($attr eq 'TYPE') {
my $dbh = $sth->{Database};
return $sth->{avatica_cache_type} ||=
[map { $dbh->{avatica_adapter}->to_dbi($_->get_type) } @{$sth->{avatica_signature}->get_columns_list}];
}
if ($attr eq 'PRECISION') {
return $sth->{avatica_cache_precision} ||=
[map { $_->get_display_size } @{$sth->{avatica_signature}->get_columns_list}];
}
if ($attr eq 'SCALE') {
return $sth->{avatica_cache_scale} ||=
[map { $_->get_scale || undef } @{$sth->{avatica_signature}->get_columns_list}];
}
if ($attr eq 'NULLABLE') {
return $sth->{avatica_cache_nullable} ||=
[map { $_->get_nullable} @{$sth->{avatica_signature}->get_columns_list}];
}
if ($attr eq 'ParamValues') {
return $sth->{avatica_cache_paramvalues} ||=
{map { $_ => ($sth->{avatica_bind_params}->[$_ - 1] // undef) } 1 .. @{$sth->{avatica_params} // []}};
}
return $sth->SUPER::FETCH($attr);
}
sub _avatica_close_statement {
my $sth = shift;
my $statement_id = $sth->{avatica_statement_id};
_client($sth, 'close_statement', $statement_id) if $statement_id && $sth->FETCH('Database')->{avatica_pid} == $$;
$sth->{avatica_statement_id} = undef;
}
sub DESTROY {
my $sth = shift;
return if $sth->FETCH('InactiveDestroy');
return unless $sth->FETCH('Database')->FETCH('Active');
eval { _avatica_close_statement($sth) };
$sth->finish;
}
1;
__END__
=pod
=encoding UTF-8
=head1 NAME
DBD::Avatica - Driver for Apache Avatica compatible servers
=head1 VERSION
version 0.2.2
=head1 SYNOPSIS
use DBI;
# for Apache Phoenix
$dbh = DBI->connect("dbi:Avatica:adapter_name=phoenix;url=http://127.0.0.1:8765", '', '', {AutoCommit => 0}) or die $DBI::errstr;
# The AutoCommit attribute should always be explicitly set
$rows = $dbh->do('UPSERT INTO mytable(a) VALUES (1)') or die $dbh->errstr;
$sth = $dbh->prepare('UPSERT INTO mytable(a) VALUES (?)') or die $dbh->errstr;
$sth->execute(2) or die $sth->errstr;
=head1 DESCRIPTION
DBD::Avatica is a Perl module that works with the DBI module to provide access to
databases with Apache Avatica compatible protocol.
=head1 MODULE DOCUMENTATION
This documentation describes driver specific behavior and restrictions. It is
not supposed to be used as the only reference for the user. In any case
consult the B<DBI> documentation first!
L<Latest DBI documentation.|DBI>
=head1 THE DBI CLASS
=head2 DBI Class Methods
=head3 B<connect>
This method creates a database handle by connecting to a database, and is the DBI
equivalent of the "new" method. To connect to a database with a minimum of parameters,
use the following syntax:
$dbh = DBI->connect("dbi:Avatica:adapter_name=phoenix;url=http://127.0.0.1:8765", '', '', {AutoCommit => 0});
This connects to the database accessed by url C<http://127.0.0.1:8765> without any user authentication.
The following connect statement shows almost all possible parameters:
$dbh = DBI->connect(
"dbi:Avatica:adapter_name=phoenix;url=$url;",
$username,
$password,
{
UserAgent => HTTP::Tiny->new(),
AutoCommit => 0,
RaiseError => 1,
PrintError => 0,
MaxRetries => 2,
TransactionIsolation => 2,
},
);
Currently username/password not supported. To set username/password for authentication need to redefine UserAgent attribute.
Your UserAgent must implement C<POST> request with HTTP::Tiny semantics.
So, after some timeouts, network errors UserAgent must return http status 599 and do not retries after failure.
For example, Furl has better performance than HTTP::Tiny.
Attrubute MaxRetries specifies the number of retries to send the request (in case HTTP 500 response). Default value is 0.
Specific for Apache Phoenix:
It is not recommended to use the MaxRetries parameter due to the L<CALCITE-4900|https://issues.apache.org/jira/browse/CALCITE-4900>
error, due to which the phoenix server may return an error which will lead to repeated requests, between which sleep is inserted.
It is guaranteed that the total time spent in sleep among all retries is no more than 1.6 seconds.
=head3 B<connect_cached>
$dbh = DBI->connect_cached("dbi:Avatica:adapter_name=phoenix;url=$url", $username, $password, \%options);
Implemented by DBI, no driver-specific impact.
=head2 Methods Common To All Handles
For all of the methods below, B<$h> can be either a database handle (B<$dbh>)
or a statement handle (B<$sth>). Note that I<$dbh> and I<$sth> can be replaced with
any variable name you choose: these are just the names most often used. Another
common variable used in this documentation is $I<rv>, which stands for "return value".
=head3 B<err>
$rv = $h->err;
Returns the error code from the last method called. If the error is generated by the perl module
it will always be 1. If an error was received from the server, then the value will be
Avatica::Client::Protocol::ErrorResponse: error_code, which corresponds to an error in the protobuf protocol.
=head3 B<errstr>
$str = $h->errstr;
Returns the error message from the last method called.
=head3 B<state>
$str = $h->state;
Returns a five-character "SQLSTATE" code. Success is indicated by a C<00000> code, which
gets mapped to an empty string by DBI.
=head3 B<trace>
$h->trace(1);
$h->trace(1, $trace_filename);
$trace_settings = $h->trace;
Changes the trace settings on a database or statement handle.
The optional second argument specifies a file to write the
trace information to. If no filename is given, the information
is written to F<STDERR>. Note that tracing can be set globally as
well by setting C<< DBI->trace >>, or by using the environment
variable I<DBI_TRACE>.
=head3 B<trace_msg>
$h->trace_msg($message_text);
$h->trace_msg($message_text, $min_level);
Writes a message to the current trace output (as set by the L</trace> method). If a second argument
is given, the message is only written if the current tracing level is equal to or greater than
the C<$min_level>.
=head3 B<parse_trace_flag> and B<parse_trace_flags>
$h->trace($h->parse_trace_flags('ALL')); # not recommended
$h->trace($h->parse_trace_flags(1));
## Simpler:
$h->trace('ALL'); # not recommended
$h->trace('1');
The parse_trace_flags method is used to convert one or more named
flags to a number which can passed to the L</trace> method.
Implemented by DBI, no driver-specific impact.
See the L<DBI section on TRACING|DBI/TRACING> for more information.
=head1 ATTRIBUTES COMMON TO ALL HANDLES
=head3 B<InactiveDestroy> (boolean)
If set to true, then the L</disconnect> and statement close methods will not be automatically
called when the database handle goes out of scope. This is required if you are forking,
and even then you must tread carefully and ensure that either the parent or the child (but not
both!) handles all database calls from that point forwards, so that messages from the
Postgres backend are only handled by one of the processes. The best solution is to either
have the child process reconnect to the database with a fresh database handle, or to
rewrite your application not to use forking.
=head3 B<AutoInactiveDestroy> (boolean)
The InactiveDestroy attribute, described above, needs to be explicitly set in the child
process after a fork. If the code that performs the fork is in a third party module such
as Sys::Syslog, this can present a problem. Use AutoInactiveDestroy to get around this
problem.
DBD::Avatica has additional security, but after the fork you still need to create a new
connection in the child process.
=head3 B<RaiseError> (boolean, inherited)
Forces errors to always raise an exception. Although it defaults to off, it is recommended that this
be turned on, as the alternative is to check the return value of every method (prepare, execute, fetch, etc.)
manually, which is easy to forget to do.
=head3 B<PrintError> (boolean, inherited)
Forces database errors to also generate warnings, which can then be filtered with methods such as
locally redefining I<$SIG{__WARN__}> or using modules such as C<CGI::Carp>. This attribute is on
by default.
=head3 B<ShowErrorStatement> (boolean, inherited)
Appends information about the current statement to error messages. If placeholder information
is available, adds that as well. Defaults to false.
Note that this will not work when using L</do> without any arguments.
=head3 B<Warn> (boolean, inherited)
Enables warnings. This is on by default, and should only be turned off in a local block
for a short a time only when absolutely needed.