forked from ged/ruby-pg
-
Notifications
You must be signed in to change notification settings - Fork 1
/
connection_spec.rb
2438 lines (2053 loc) · 77.6 KB
/
connection_spec.rb
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
# -*- rspec -*-
#encoding: utf-8
require_relative '../helpers'
require 'timeout'
require 'socket'
require 'objspace'
require 'pg'
describe PG::Connection do
it "should give account about memory usage" do
expect( ObjectSpace.memsize_of(@conn) ).to be > DATA_OBJ_MEMSIZE
end
describe "PG::Connection#conninfo_parse" do
it "encode and decode Hash to connection string to Hash" do
hash = {
:host => 'pgsql.example.com',
:dbname => 'db01',
'sslmode' => 'require',
'service' => '',
'password' => "\\ \t\n\"'",
}
optstring = described_class.connect_hash_to_string(hash)
res = described_class.conninfo_parse(optstring).each_with_object({}){|h, o| o[h[:keyword].to_sym] = h[:val] if h[:val] }
expect( res ).to eq( hash.transform_keys(&:to_sym) )
end
it "decode option string to Hash" do
optstring = "host=overwritten host=c:\\\\pipe password = \\\\\\'\" "
res = described_class.conninfo_parse(optstring).each_with_object({}){|h, o| o[h[:keyword].to_sym] = h[:val] if h[:val] }
expect( res ).to eq({
host: 'c:\pipe',
password: "\\'\"",
})
end
it "can parse connection info strings kind of key=value" do
ar = PG::Connection.conninfo_parse("user=auser host=somehost port=3334 dbname=db")
expect( ar ).to be_kind_of( Array )
expect( ar.first ).to be_kind_of( Hash )
expect( ar.map{|a| a[:keyword] } ).to include( "dbname", "user", "password", "port" )
expect( ar.map{|a| a[:val] } ).to include( "auser", "somehost", "3334", "db" )
end
it "can parse connection info strings kind of URI" do
ar = PG::Connection.conninfo_parse("postgresql://auser@somehost:3334/db")
expect( ar ).to be_kind_of( Array )
expect( ar.first ).to be_kind_of( Hash )
expect( ar.map{|a| a[:keyword] } ).to include( "dbname", "user", "password", "port" )
expect( ar.map{|a| a[:val] } ).to include( "auser", "somehost", "3334", "db" )
end
it "can parse connection info strings with error" do
expect{ PG::Connection.conninfo_parse("host='abc") }.to raise_error(PG::Error, /unterminated quoted string/)
expect{ PG::Connection.conninfo_parse("host") }.to raise_error(PG::Error, /missing "=" after/)
end
end
describe "PG::Connection#parse_connect_args" do
it "shouldn't resolve absolute path in connection option string" do
optstring = described_class.parse_connect_args(
:host => '/var/socket'
)
expect( optstring ).to match( /(^|\s)host='\/var\/socket'/ )
expect( optstring ).not_to match( /hostaddr/ )
end
it "shouldn't resolve Windows path in connection option string", :windows do
optstring = described_class.parse_connect_args(
:host => "C:\\pipe\\00"
)
expect( optstring ).to match( /(^|\s)host='C:\\\\pipe\\\\00'/ )
expect( optstring ).not_to match( /hostaddr/ )
end
it "can create a connection option string from a Hash parameter" do
optstring = described_class.parse_connect_args(
:host => 'pgsql.example.com',
:dbname => 'db01',
'sslmode' => 'require',
'hostaddr' => '1.2.3.4'
)
expect( optstring ).to be_a( String )
expect( optstring ).to match( /(^|\s)host='pgsql.example.com'/ )
expect( optstring ).to match( /(^|\s)dbname='db01'/ )
expect( optstring ).to match( /(^|\s)sslmode='require'/ )
expect( optstring ).to match( /(^|\s)hostaddr='1.2.3.4'/ )
end
it "can create a connection option string from positional parameters" do
optstring = described_class.parse_connect_args( 'localhost', nil, '-c geqo=off', nil,
'sales' )
expect( optstring ).to be_a( String )
expect( optstring ).to match( /(^|\s)host='localhost'/ )
expect( optstring ).to match( /(^|\s)dbname='sales'/ )
expect( optstring ).to match( /(^|\s)options='-c geqo=off'/ )
expect( optstring ).to_not match( /port=/ )
expect( optstring ).to_not match( /tty=/ )
end
it "can create a connection option string from a mix of positional and hash parameters" do
optstring = described_class.parse_connect_args( 'pgsql.example.com',
:dbname => 'licensing', :user => 'jrandom',
'hostaddr' => '1.2.3.4' )
expect( optstring ).to be_a( String )
expect( optstring ).to match( /(^|\s)host='pgsql.example.com'/ )
expect( optstring ).to match( /(^|\s)dbname='licensing'/ )
expect( optstring ).to match( /(^|\s)user='jrandom'/ )
expect( optstring ).to match( /(^|\s)hostaddr='1.2.3.4'/ )
end
it "can create a connection option string from an option string and a hash" do
optstring = described_class.parse_connect_args( 'dbname=original', :user => 'jrandom',
'host' => 'www.ruby-lang.org,nonexisting-domaiiin.xyz,localhost' )
expect( optstring ).to be_a( String )
expect( optstring ).to match( /(^|\s)dbname='original'/ )
expect( optstring ).to match( /(^|\s)user='jrandom'/ )
end
it "escapes single quotes and backslashes in connection parameters" do
expect(
described_class.parse_connect_args( password: "DB 'browser' \\" )
).to match( /password='DB \\'browser\\' \\\\'/ )
end
let(:uri) { 'postgresql://user:pass@pgsql.example.com:222/db01?sslmode=require&hostaddr=4.3.2.1' }
it "accepts an URI string" do
string = described_class.parse_connect_args( uri )
expect( string ).to be_a( String )
expect( string ).to match( %r{^user='user' password='pass' dbname='db01' host='pgsql.example.com' hostaddr='4.3.2.1' port='222' sslmode='require' fallback_application_name} )
end
it "accepts an URI object" do
string = described_class.parse_connect_args( URI.parse(uri) )
expect( string ).to be_a( String )
expect( string ).to match( %r{^user='user' password='pass' dbname='db01' host='pgsql.example.com' hostaddr='4.3.2.1' port='222' sslmode='require' fallback_application_name} )
end
it "accepts an URI and adds parameters from hash" do
string = described_class.parse_connect_args( uri + "&fallback_application_name=testapp", :connect_timeout => 2 )
expect( string ).to be_a( String )
expect( string ).to match( %r{^user='user' password='pass' dbname='db01' host='pgsql.example.com' hostaddr='4.3.2.1' port='222' fallback_application_name='testapp' sslmode='require' connect_timeout='2'} )
end
it "accepts an URI with a non-standard domain socket directory" do
string = described_class.parse_connect_args( 'postgresql://%2Fvar%2Flib%2Fpostgresql/dbname' )
expect( string ).to be_a( String )
expect( string ).to match( %r{^dbname='dbname' host='/var/lib/postgresql'} )
string = described_class.
parse_connect_args( 'postgresql:///dbname', :host => '/var/lib/postgresql' )
expect( string ).to be_a( String )
expect( string ).to match( %r{^dbname='dbname' host='/var/lib/postgresql'} )
end
it "connects with defaults if no connection parameters are given" do
expect( described_class.parse_connect_args ).to match( /fallback_application_name='[^']+'/ )
end
it "connects successfully with connection string" do
conninfo_with_colon_in_password = "host=localhost user=a port=555 dbname=test password=a:a"
string = described_class.parse_connect_args( conninfo_with_colon_in_password )
expect( string ).to be_a( String )
expect( string ).to match( %r{(^|\s)user='a'} )
expect( string ).to match( %r{(^|\s)password='a:a'} )
expect( string ).to match( %r{(^|\s)host='localhost'} )
expect( string ).to match( %r{(^|\s)port='555'} )
expect( string ).to match( %r{(^|\s)dbname='test'} )
end
it "sets the fallback_application_name on new connections" do
conn_string = PG::Connection.parse_connect_args( 'dbname=test' )
conn_name = conn_string[ /application_name='(.*?)'/, 1 ]
expect( conn_name ).to include( $0[0..10] )
expect( conn_name ).to include( $0[-10..-1] )
expect( conn_name.length ).to be <= 64
end
it "sets a shortened fallback_application_name on new connections" do
old_0 = $0
begin
$0 = "/this/is/a/very/long/path/with/many/directories/to/our/beloved/ruby"
conn_string = PG::Connection.parse_connect_args( 'dbname=test' )
conn_name = conn_string[ /application_name='(.*?)'/, 1 ]
expect( conn_name ).to include( $0[0..10] )
expect( conn_name ).to include( $0[-10..-1] )
expect( conn_name.length ).to be <= 64
ensure
$0 = old_0
end
end
end
it "connects successfully with connection string" do
tmpconn = described_class.connect( @conninfo )
expect( tmpconn.status ).to eq( PG::CONNECTION_OK )
tmpconn.finish
end
it "connects using 7 arguments converted to strings" do
tmpconn = described_class.connect( 'localhost', @port, nil, nil, :test, nil, nil )
expect( tmpconn.status ).to eq( PG::CONNECTION_OK )
tmpconn.finish
end
it "connects using a hash of connection parameters" do
tmpconn = described_class.connect(
:host => 'localhost',
:port => @port,
:dbname => :test)
expect( tmpconn.status ).to eq( PG::CONNECTION_OK )
tmpconn.finish
end
it "connects using a hash of optional connection parameters" do
tmpconn = described_class.connect(
:host => 'localhost',
:port => @port,
:dbname => :test,
:keepalives => 1)
expect( tmpconn.status ).to eq( PG::CONNECTION_OK )
tmpconn.finish
end
it "raises an exception when connecting with an invalid number of arguments" do
expect {
described_class.connect( 1, 2, 3, 4, 5, 6, 7, 'the-extra-arg' )
}.to raise_error do |error|
expect( error ).to be_an( ArgumentError )
expect( error.message ).to match( /extra positional parameter/i )
expect( error.message ).to match( /8/ )
expect( error.message ).to match( /the-extra-arg/ )
end
end
it "emits a suitable error_message at connection errors" do
skip("Will be fixed in postgresql-15 on Windows") if RUBY_PLATFORM=~/mingw|mswin/
expect {
described_class.connect(
:host => 'localhost',
:port => @port,
:dbname => "non-existent")
}.to raise_error do |error|
expect( error ).to be_an( PG::ConnectionBad )
expect( error.message ).to match( /database "non-existent" does not exist/i )
expect( error.message.encoding ).to eq( Encoding::BINARY )
end
end
it "times out after connect_timeout seconds" do
TCPServer.open( 'localhost', 54320 ) do |serv|
start_time = Time.now
expect {
described_class.connect(
host: 'localhost',
port: 54320,
connect_timeout: 1,
dbname: "test")
}.to raise_error do |error|
expect( error ).to be_an( PG::ConnectionBad )
expect( error.message ).to match( /timeout expired/ )
if PG.library_version >= 120000
expect( error.message ).to match( /\"localhost\"/ )
expect( error.message ).to match( /port 54320/ )
end
end
expect( Time.now - start_time ).to be_between(1.9, 10).inclusive
end
end
it "connects using URI with multiple hosts", :postgresql_12 do
uri = "postgres://localhost:#{@port+1},127.0.0.1:#{@port}/test?keepalives=1"
tmpconn = described_class.connect( uri )
expect( tmpconn.status ).to eq( PG::CONNECTION_OK )
expect( tmpconn.port ).to eq( @port )
expect( tmpconn.host ).to eq( "127.0.0.1" )
expect( tmpconn.hostaddr ).to match( /\A(::1|127\.0\.0\.1)\z/ )
tmpconn.finish
end
it "connects using URI with IPv6 hosts", :postgresql_12, :ipv6 do
uri = "postgres://localhost:#{@port},[::1]:#{@port},/test"
tmpconn = described_class.connect( uri )
expect( tmpconn.status ).to eq( PG::CONNECTION_OK )
expect( tmpconn.host ).to eq( "localhost" )
expect( tmpconn.hostaddr ).to match( /\A(::1|127\.0\.0\.1)\z/ )
tmpconn.finish
end
it "connects using URI with UnixSocket host", :postgresql_12, :unix_socket do
uri = "postgres://#{@unix_socket.gsub("/", "%2F")}:#{@port}/test"
tmpconn = described_class.connect( uri )
expect( tmpconn.status ).to eq( PG::CONNECTION_OK )
expect( tmpconn.host ).to eq( @unix_socket )
expect( tmpconn.hostaddr ).to eq( "" )
tmpconn.finish
end
it "connects using Hash with multiple hosts", :postgresql_12 do
tmpconn = described_class.connect( host: "#{@unix_socket}xx,127.0.0.1,localhost", port: @port, dbname: "test" )
expect( tmpconn.status ).to eq( PG::CONNECTION_OK )
expect( tmpconn.host ).to eq( "127.0.0.1" )
expect( tmpconn.hostaddr ).to match( /\A127\.0\.0\.1\z/ )
tmpconn.finish
end
%i[open new connect sync_connect async_connect setdb setdblogin].each do |meth|
it "can call ##{meth} of a derived class" do
klass = Class.new(described_class) do
alias execute exec
end
klass.send(meth, @conninfo) do |conn|
expect( conn ).to be_a_kind_of( klass )
expect( conn.execute("SELECT 1") ).to be_a_kind_of( PG::Result )
end
end
end
it "can connect asynchronously" do
tmpconn = described_class.connect_start( @conninfo )
expect( tmpconn ).to be_a( described_class )
wait_for_polling_ok(tmpconn)
expect( tmpconn.status ).to eq( PG::CONNECTION_OK )
tmpconn.finish
end
it "can connect asynchronously for the duration of a block" do
conn = nil
described_class.connect_start(@conninfo) do |tmpconn|
expect( tmpconn ).to be_a( described_class )
conn = tmpconn
wait_for_polling_ok(tmpconn)
expect( tmpconn.status ).to eq( PG::CONNECTION_OK )
end
expect( conn ).to be_finished()
end
context "with async established connection" do
before :each do
@conn2 = described_class.connect_start( @conninfo )
wait_for_polling_ok(@conn2)
expect( @conn2 ).to still_be_usable
end
after :each do
expect( @conn2 ).to still_be_usable
@conn2.close
end
it "conn.send_query and IO.select work" do
@conn2.send_query("SELECT 1")
res = wait_for_query_result(@conn2)
expect( res.values ).to eq([["1"]])
end
it "conn.send_query and conn.block work" do
@conn2.send_query("SELECT 2")
@conn2.block
res = @conn2.get_last_result
expect( res.values ).to eq([["2"]])
end
it "conn.async_query works" do
res = @conn2.async_query("SELECT 3")
expect( res.values ).to eq([["3"]])
expect( @conn2 ).to still_be_usable
res = @conn2.query("SELECT 4")
end
it "can work with changing IO while connection setup" do
# The file_no of the socket IO can change while connecting.
# This can happen when alternative hosts are tried,
# while GSS authentication
# and when falling back to unencrypted in sslmode:prefer
# Consume some file descriptors and free them while the connection is established.
pipes = 100.times.map{ IO.pipe }
Thread.new do
pipes.reverse_each do |ios|
ios.each(&:close)
sleep 0.01
end
end
# Connect with SSL, but use a wrong client cert, so that connection is aborted.
# A second connection is then started with a new IO.
# And since the pipes above were freed in the concurrent thread above, there is a high chance that it's a lower file descriptor than before.
conn = PG.connect( @conninfo + " sslcert=tmp_test_specs/data/ruby-pg-ca-cert" )
# The new connection should work even when the file descriptor has changed.
res = conn.exec("SELECT 1")
expect( res.values ).to eq([["1"]])
conn.close
end
it "can use conn.reset_start to restart the connection" do
ios = IO.pipe
conn = described_class.connect_start( @conninfo )
wait_for_polling_ok(conn)
# Close the two pipe file descriptors, so that the file descriptor of
# newly established connection is probably distinct from the previous one.
ios.each(&:close)
conn.reset_start
wait_for_polling_ok(conn, :reset_poll)
# The new connection should work even when the file descriptor has changed.
conn.send_query("SELECT 1")
res = wait_for_query_result(conn)
expect( res.values ).to eq([["1"]])
conn.close
end
it "should properly close a socket IO when GC'ed" do
# This results in
# Errno::ENOTSOCK: An operation was attempted on something that is not a socket.
# on Windows when rb_w32_unwrap_io_handle() isn't called in pgconn_gc_free().
5.times do
conn = described_class.connect( @conninfo )
conn.socket_io.close
end
GC.start
IO.pipe.each(&:close)
end
it "provides the server generated error message" do
skip("Will be fixed in postgresql-15 on Windows") if RUBY_PLATFORM=~/mingw|mswin/
conn = described_class.connect_start(
:host => 'localhost',
:port => @port,
:dbname => "non-existent")
wait_for_polling_ok(conn)
msg = conn.error_message
expect( msg ).to match( /database "non-existent" does not exist/i )
expect( msg.encoding ).to eq( Encoding::BINARY )
end
end
context "in nonblocking mode" do
after :each do
@conn.setnonblocking(false)
end
it "defaults to blocking" do
expect( @conn.isnonblocking ).to eq(false)
expect( @conn.nonblocking? ).to eq(false)
end
it "can set nonblocking" do
expect( @conn.setnonblocking(true) ).to be_nil
expect( @conn.isnonblocking ).to eq(true)
expect( @conn.nonblocking? ).to eq(true)
expect( @conn.setnonblocking(false) ).to be_nil
expect( @conn.isnonblocking ).to eq(false)
expect( @conn.nonblocking? ).to eq(false)
end
it "sets nonblocking for the connection only" do
co2 = PG.connect(@conninfo)
expect( co2.setnonblocking(true) ).to be_nil
expect( co2.isnonblocking ).to eq(true)
expect( @conn.isnonblocking ).to eq(false)
co2.finish
end
it "can send query" do
@conn.setnonblocking(true)
@conn.send_query("SELECT 3")
wait_for_flush(@conn)
res = wait_for_query_result(@conn)
expect( res.values ).to eq([["3"]])
end
it "can send query with params" do
@conn.setnonblocking(true)
data = "x" * 1000 * 1000 * 10
@conn.send_query_params("SELECT LENGTH($1)", [data])
wait_for_flush(@conn)
res = wait_for_query_result(@conn)
expect( res.values ).to eq([[data.length.to_s]])
end
it "rejects to send lots of COPY data" do
skip("takes around an hour to succeed on Windows") if RUBY_PLATFORM=~/mingw|mswin/
conn = described_class.new(@conninfo)
conn.setnonblocking(true)
res = nil
begin
Timeout.timeout(60) do
conn.exec <<-EOSQL
CREATE TEMP TABLE copytable (col1 TEXT);
CREATE OR REPLACE FUNCTION delay_input() RETURNS trigger AS $x$
BEGIN
PERFORM pg_sleep(1);
RETURN NEW;
END;
$x$ LANGUAGE plpgsql;
CREATE TRIGGER delay_input BEFORE INSERT ON copytable
FOR EACH ROW EXECUTE PROCEDURE delay_input();
EOSQL
conn.exec( "COPY copytable FROM STDOUT CSV" )
data = "x" * 1000 * 1000
data << "\n"
20000.times do
res = conn.put_copy_data(data)
break if res == false
end
end
expect( res ).to be_falsey
rescue Timeout::Error
skip <<-EOT
Unfortunately this test is not reliable.
It is timing dependent, since it assumes that the ruby process
sends data faster than the PostgreSQL server can process it.
This assumption is wrong in some environments.
EOT
ensure
conn.cancel
conn.discard_results
conn.finish
end
end
it "needs to flush data after send_query" do
retries = 3
begin
conn = described_class.new(@conninfo)
conn.setnonblocking(true)
data = "x" * 1000 * 1000 * 100
res = conn.send_query_params("SELECT LENGTH($1)", [data])
expect( res ).to be_nil
res = conn.flush
expect( res ).to be_falsey
rescue RSpec::Expectations::ExpectationNotMetError
if (retries-=1) >= 0
until conn.flush()
IO.select(nil, [conn.socket_io], nil, 10)
end
conn.get_last_result
conn.finish
retry
end
raise
ensure
until conn.flush()
IO.select(nil, [conn.socket_io], nil, 10)
end
expect( conn.flush ).to be_truthy
res = conn.get_last_result
expect( res.values ).to eq( [[data.length.to_s]] )
conn.finish
end
end
it "returns immediately from get_copy_data(nonblock=true)" do
expect do
@conn.copy_data( "COPY (SELECT generate_series(0,999), NULL UNION ALL SELECT 1000, pg_sleep(10)) TO STDOUT" ) do |res|
res = nil
1000.times do
res = @conn.get_copy_data(true)
break if res==false
end
@conn.cancel
expect( res ).to be_falsey
while @conn.get_copy_data
end
end
end.to raise_error(PG::QueryCanceled)
end
end
it "raises proper error when sending fails" do
conn = described_class.connect_start( '127.0.0.1', 54320, "", "", "me", "xxxx", "somedb" )
expect{ conn.exec 'SELECT 1' }.to raise_error(PG::UnableToSend, /no connection/)
end
it "doesn't leave stale server connections after finish" do
described_class.connect(@conninfo).finish
sleep 0.5
res = @conn.exec(%[SELECT COUNT(*) AS n FROM pg_stat_activity
WHERE usename IS NOT NULL AND application_name != ''])
# there's still the global @conn, but should be no more
expect( res[0]['n'] ).to eq( '1' )
end
it "can retrieve it's connection parameters for the established connection" do
expect( @conn.db ).to eq( "test" )
expect( @conn.user ).to be_a_kind_of( String )
expect( @conn.pass ).to eq( "" )
expect( @conn.host ).to eq( "localhost" )
expect( @conn.port ).to eq( @port )
expect( @conn.tty ).to eq( "" )
expect( @conn.options ).to eq( "" )
end
it "can retrieve hostaddr for the established connection", :postgresql_12 do
expect( @conn.hostaddr ).to match( /^127\.0\.0\.1$|^::1$/ )
end
it "can set error verbosity" do
old = @conn.set_error_verbosity( PG::PQERRORS_TERSE )
new = @conn.set_error_verbosity( old )
expect( new ).to eq( PG::PQERRORS_TERSE )
end
it "can set error context visibility", :postgresql_96 do
old = @conn.set_error_context_visibility( PG::PQSHOW_CONTEXT_NEVER )
new = @conn.set_error_context_visibility( old )
expect( new ).to eq( PG::PQSHOW_CONTEXT_NEVER )
end
let(:expected_trace_output_pre_14) do
%{
To backend> Msg Q
To backend> "SELECT 1 AS one"
To backend> Msg complete, length 21
From backend> T
From backend (#4)> 28
From backend (#2)> 1
From backend> "one"
From backend (#4)> 0
From backend (#2)> 0
From backend (#4)> 23
From backend (#2)> 4
From backend (#4)> -1
From backend (#2)> 0
From backend> D
From backend (#4)> 11
From backend (#2)> 1
From backend (#4)> 1
From backend (1)> 1
From backend> C
From backend (#4)> 13
From backend> "SELECT 1"
From backend> Z
From backend (#4)> 5
From backend> Z
From backend (#4)> 5
From backend> T
}.gsub( /^\t{2}/, '' ).lstrip
end
let(:expected_trace_output) do
%{
TIMESTAMP F 20 Query "SELECT 1 AS one"
TIMESTAMP B 28 RowDescription 1 "one" 0 0 23 4 -1 0
TIMESTAMP B 11 DataRow 1 1 '1'
TIMESTAMP B 13 CommandComplete "SELECT 1"
TIMESTAMP B 5 ReadyForQuery T
}.gsub( /^\t{2}/, '' ).lstrip
end
it "trace and untrace client-server communication", :unix do
# be careful to explicitly close files so that the
# directory can be removed and we don't have to wait for
# the GC to run.
trace_file = TEST_DIRECTORY + "test_trace.out"
trace_io = trace_file.open( 'w', 0600 )
@conn.trace( trace_io )
trace_io.close
@conn.exec("SELECT 1 AS one")
@conn.untrace
@conn.exec("SELECT 2 AS two")
trace_data = trace_file.read
if PG.library_version >= 140000
trace_data.gsub!( /\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d{6}/, 'TIMESTAMP' )
expect( trace_data ).to eq( expected_trace_output )
else
# For async_exec the output will be different:
# From backend> Z
# From backend (#4)> 5
# +From backend> Z
# +From backend (#4)> 5
# From backend> T
trace_data.sub!( /(From backend> Z\nFrom backend \(#4\)> 5\n){3}/m, '\\1\\1' )
expect( trace_data ).to eq( expected_trace_output_pre_14 )
end
end
it "allows a query to be cancelled" do
start = Time.now
@conn.set_notice_processor do |notice|
@conn.cancel if notice =~ /foobar/
end
@conn.send_query "do $$ BEGIN RAISE NOTICE 'foobar'; PERFORM pg_sleep(10); END; $$ LANGUAGE plpgsql;"
expect{ @conn.get_last_result }.to raise_error(PG::QueryCanceled)
expect( Time.now - start ).to be < 9.9
end
describe "#transaction" do
it "automatically rolls back a transaction if an exception is raised" do
# abort the per-example transaction so we can test our own
@conn.exec( 'ROLLBACK' )
res = nil
@conn.exec( "CREATE TABLE pie ( flavor TEXT )" )
begin
expect {
res = @conn.transaction do
@conn.exec( "INSERT INTO pie VALUES ('rhubarb'), ('cherry'), ('schizophrenia')" )
raise Exception, "Oh noes! All pie is gone!"
end
}.to raise_exception( Exception, /all pie is gone/i )
res = @conn.exec( "SELECT * FROM pie" )
expect( res.ntuples ).to eq( 0 )
ensure
@conn.exec( "DROP TABLE pie" )
end
end
it "passes the connection to the block and returns the block result" do
# abort the per-example transaction so we can test our own
@conn.exec( 'ROLLBACK' )
res = @conn.transaction do |co|
expect( co ).to equal( @conn )
"transaction result"
end
expect( res ).to eq( "transaction result" )
end
end
it "not read past the end of a large object" do
@conn.transaction do
oid = @conn.lo_create( 0 )
fd = @conn.lo_open( oid, PG::INV_READ|PG::INV_WRITE )
@conn.lo_write( fd, "foobar" )
expect( @conn.lo_read( fd, 10 ) ).to be_nil()
@conn.lo_lseek( fd, 0, PG::SEEK_SET )
expect( @conn.lo_read( fd, 10 ) ).to eq( 'foobar' )
end
end
it "supports explicitly calling #exec_params" do
@conn.exec( "CREATE TABLE students ( name TEXT, age INTEGER )" )
@conn.exec_params( "INSERT INTO students VALUES( $1, $2 )", ['Wally', 8] )
@conn.exec_params( "INSERT INTO students VALUES( $1, $2 )", ['Sally', 6] )
@conn.exec_params( "INSERT INTO students VALUES( $1, $2 )", ['Dorothy', 4] )
res = @conn.exec_params( "SELECT name FROM students WHERE age >= $1", [6] )
expect( res.values ).to eq( [ ['Wally'], ['Sally'] ] )
end
it "supports hash form parameters for #exec_params" do
hash_param_bin = { value: ["00ff"].pack("H*"), type: 17, format: 1 }
hash_param_nil = { value: nil, type: 17, format: 1 }
res = @conn.exec_params( "SELECT $1, $2",
[ hash_param_bin, hash_param_nil ] )
expect( res.values ).to eq( [["\\x00ff", nil]] )
expect( result_typenames(res) ).to eq( ['bytea', 'bytea'] )
end
it "should work with arbitrary number of params" do
begin
3.step( 12, 0.2 ) do |exp|
num_params = (2 ** exp).to_i
sql = num_params.times.map{|n| "$#{n+1}::INT" }.join(",")
params = num_params.times.to_a
res = @conn.exec_params( "SELECT #{sql}", params )
expect( res.nfields ).to eq( num_params )
expect( res.values ).to eq( [num_params.times.map(&:to_s)] )
end
rescue PG::ProgramLimitExceeded
# Stop silently if the server complains about too many params
end
end
it "can wait for NOTIFY events" do
@conn.exec( 'ROLLBACK' )
@conn.exec( 'LISTEN woo' )
t = Thread.new do
begin
conn = described_class.connect( @conninfo )
sleep 0.1
conn.exec( 'NOTIFY woo' )
ensure
conn.finish
end
end
expect( @conn.wait_for_notify( 10 ) ).to eq( 'woo' )
@conn.exec( 'UNLISTEN woo' )
t.join
end
it "calls a block for NOTIFY events if one is given" do
@conn.exec( 'ROLLBACK' )
@conn.exec( 'LISTEN woo' )
t = Thread.new do
begin
conn = described_class.connect( @conninfo )
sleep 0.1
conn.exec( 'NOTIFY woo' )
ensure
conn.finish
end
end
eventpid = event = nil
@conn.wait_for_notify( 10 ) {|*args| event, eventpid = args }
expect( event ).to eq( 'woo' )
expect( eventpid ).to be_an( Integer )
@conn.exec( 'UNLISTEN woo' )
t.join
end
it "doesn't collapse sequential notifications" do
@conn.exec( 'ROLLBACK' )
@conn.exec( 'LISTEN woo' )
@conn.exec( 'LISTEN war' )
@conn.exec( 'LISTEN woz' )
begin
conn = described_class.connect( @conninfo )
conn.exec( 'NOTIFY woo' )
conn.exec( 'NOTIFY war' )
conn.exec( 'NOTIFY woz' )
ensure
conn.finish
end
channels = []
3.times do
channels << @conn.wait_for_notify( 2 )
end
expect( channels.size ).to eq( 3 )
expect( channels ).to include( 'woo', 'war', 'woz' )
@conn.exec( 'UNLISTEN woz' )
@conn.exec( 'UNLISTEN war' )
@conn.exec( 'UNLISTEN woo' )
end
it "returns notifications which are already in the queue before wait_for_notify is called " +
"without waiting for the socket to become readable" do
@conn.exec( 'ROLLBACK' )
@conn.exec( 'LISTEN woo' )
begin
conn = described_class.connect( @conninfo )
conn.exec( 'NOTIFY woo' )
ensure
conn.finish
end
# Cause the notification to buffer, but not be read yet
@conn.exec( 'SELECT 1' )
expect( @conn.wait_for_notify( 10 ) ).to eq( 'woo' )
@conn.exec( 'UNLISTEN woo' )
end
it "can receive notices while waiting for NOTIFY without exceeding the timeout" do
retries = 20
loop do
@conn.get_last_result # clear pending results
expect( retries-=1 ).to be > 0
notices = []
lt = nil
@conn.set_notice_processor do |msg|
notices << [msg, Time.now - lt] if lt
lt = Time.now
end
st = Time.now
# Send two notifications while a query is running
@conn.send_query <<-EOT
DO $$ BEGIN
RAISE NOTICE 'notice1';
PERFORM pg_sleep(0.3);
RAISE NOTICE 'notice2';
END; $$ LANGUAGE plpgsql
EOT
# wait_for_notify recalculates the internal select() timeout after each all to set_notice_processor
expect( @conn.wait_for_notify( 0.5 ) ).to be_nil
et = Time.now
# The notifications should have been delivered while (not after) the query is running.
# Check this and retry otherwise.
next unless notices.size == 1 # should have received one notice
expect( notices.first[0] ).to match(/notice2/)
next unless notices.first[1] >= 0.29 # should take at least the pg_sleep() duration
next unless notices.first[1] < 0.49 # but should be shorter than the wait_for_notify() duration
next unless et - st < 0.75 # total time should not exceed wait_for_notify() + pg_sleep() duration
expect( et - st ).to be >= 0.49 # total time must be at least the wait_for_notify() duration
break
end
end
it "yields the result if block is given to exec" do
rval = @conn.exec( "select 1234::int as a union select 5678::int as a" ) do |result|
values = []
expect( result ).to be_kind_of( PG::Result )
expect( result.ntuples ).to eq( 2 )
result.each do |tuple|
values << tuple['a']
end
values
end
expect( rval.size ).to eq( 2 )
expect( rval ).to include( '5678', '1234' )
end
it "correctly finishes COPY queries passed to #exec" do
@conn.exec( "COPY (SELECT 1 UNION ALL SELECT 2) TO STDOUT" )
results = []
begin
data = @conn.get_copy_data( true )
if false == data
@conn.block( 2.0 )
data = @conn.get_copy_data( true )
end
results << data if data
end until data.nil?
expect( results.size ).to eq( 2 )
expect( results ).to include( "1\n", "2\n" )
end
it "#get_result should send remaining data before waiting" do
str = "abcd" * 2000 + "\n"
@conn.exec( "CREATE TEMP TABLE copytable2 (col1 TEXT)" )
@conn.exec( "COPY copytable2 FROM STDOUT" )
1000.times do
@conn.sync_put_copy_data(str)
end
@conn.sync_put_copy_end
res = @conn.get_last_result
expect( res.result_status ).to eq( PG::PGRES_COMMAND_OK )
end
describe "#copy_data" do