-
Notifications
You must be signed in to change notification settings - Fork 182
/
connection_spec.rb
1974 lines (1653 loc) · 62.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 'pg'
describe PG::Connection do
it "can create a connection option string from a Hash of options" do
optstring = described_class.parse_connect_args(
:host => 'pgsql.example.com',
:dbname => 'db01',
'sslmode' => 'require'
)
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'/ )
end
it "can create a connection option string from positional parameters" do
optstring = described_class.parse_connect_args( 'pgsql.example.com', nil, '-c geqo=off', nil,
'sales' )
expect( optstring ).to be_a( String )
expect( optstring ).to match( /(^|\s)host='pgsql.example.com'/ )
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' )
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'/ )
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' )
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( "DB 'browser' \\" )
).to match( /host='DB \\'browser\\' \\\\'/ )
end
let(:uri) { 'postgresql://user:[email protected]:222/db01?sslmode=require' }
it "can connect using a URI" do
string = described_class.parse_connect_args( uri )
expect( string ).to be_a( String )
expect( string ).to match( %r{^postgresql://user:[email protected]:222/db01\?} )
expect( string ).to match( %r{\?.*sslmode=require} )
string = described_class.parse_connect_args( URI.parse(uri) )
expect( string ).to be_a( String )
expect( string ).to match( %r{^postgresql://user:[email protected]:222/db01\?} )
expect( string ).to match( %r{\?.*sslmode=require} )
end
it "can create a connection URI from a URI and a hash" do
string = described_class.parse_connect_args( uri, :connect_timeout => 2 )
expect( string ).to be_a( String )
expect( string ).to match( %r{^postgresql://user:[email protected]:222/db01\?} )
expect( string ).to match( %r{\?.*sslmode=require} )
expect( string ).to match( %r{\?.*connect_timeout=2} )
string = described_class.parse_connect_args( uri,
:user => 'a',
:password => 'b',
:host => 'localhost',
:port => 555,
:dbname => 'x' )
expect( string ).to be_a( String )
expect( string ).to match( %r{^postgresql://\?} )
expect( string ).to match( %r{\?.*user=a} )
expect( string ).to match( %r{\?.*password=b} )
expect( string ).to match( %r{\?.*host=localhost} )
expect( string ).to match( %r{\?.*port=555} )
expect( string ).to match( %r{\?.*dbname=x} )
end
it "can create a connection 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{^postgresql://%2Fvar%2Flib%2Fpostgresql/dbname} )
string = described_class.
parse_connect_args( 'postgresql:///dbname', :host => '/var/lib/postgresql' )
expect( string ).to be_a( String )
expect( string ).to match( %r{^postgresql:///dbname\?} )
expect( string ).to match( %r{\?.*host=%2Fvar%2Flib%2Fpostgresql} )
end
it "connects with defaults if no connection parameters are given" do
expect( described_class.parse_connect_args ).to eq( '' )
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 "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 "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 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
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.port ).to eq( @port )
expect( @conn.tty ).to eq( "" )
expect( @conn.options ).to eq( "" )
end
it "can retrieve it's connection parameters for the established connection",
skip: RUBY_PLATFORM=~/x64-mingw/ ? "host segfaults on Windows-x64" : false do
expect( @conn.host ).to eq( "localhost" )
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) 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
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
# 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 )
end
it "allows a query to be cancelled" do
error = false
@conn.send_query("SELECT pg_sleep(1000)")
@conn.cancel
tmpres = @conn.get_result
if(tmpres.result_status != PG::PGRES_TUPLES_OK)
error = true
end
expect( error ).to eq( true )
end
it "can stop a thread that runs a blocking query with async_exec" do
start = Time.now
t = Thread.new do
@conn.async_exec( 'select pg_sleep(10)' )
end
sleep 0.1
t.kill
t.join
expect( (Time.now - start) ).to be < 10
end
it "should work together with signal handlers", :unix do
signal_received = false
trap 'USR2' do
signal_received = true
end
Thread.new do
sleep 0.1
Process.kill("USR2", Process.pid)
end
@conn.exec("select pg_sleep(0.3)")
expect( signal_received ).to be_truthy
end
it "automatically rolls back a transaction started with Connection#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 "Oh noes! All pie is gone!"
end
}.to raise_exception( RuntimeError, /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 "returns the block result from Connection#transaction" do
# abort the per-example transaction so we can test our own
@conn.exec( 'ROLLBACK' )
res = @conn.transaction do
"transaction result"
end
expect( res ).to eq( "transaction result" )
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 1
conn.async_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 1
conn.async_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 "can process #copy_data output queries" do
rows = []
res2 = @conn.copy_data( "COPY (SELECT 1 UNION ALL SELECT 2) TO STDOUT" ) do |res|
expect( res.result_status ).to eq( PG::PGRES_COPY_OUT )
expect( res.nfields ).to eq( 1 )
while [email protected]_copy_data
rows << row
end
end
expect( rows ).to eq( ["1\n", "2\n"] )
expect( res2.result_status ).to eq( PG::PGRES_COMMAND_OK )
expect( @conn ).to still_be_usable
end
it "can handle incomplete #copy_data output queries" do
expect {
@conn.copy_data( "COPY (SELECT 1 UNION ALL SELECT 2) TO STDOUT" ) do |res|
@conn.get_copy_data
end
}.to raise_error(PG::NotAllCopyDataRetrieved, /Not all/)
expect( @conn ).to still_be_usable
end
it "can handle client errors in #copy_data for output" do
expect {
@conn.copy_data( "COPY (SELECT 1 UNION ALL SELECT 2) TO STDOUT" ) do
raise "boom"
end
}.to raise_error(RuntimeError, "boom")
expect( @conn ).to still_be_usable
end
it "can handle server errors in #copy_data for output" do
@conn.exec "ROLLBACK"
@conn.transaction do
@conn.exec( "CREATE FUNCTION errfunc() RETURNS int AS $$ BEGIN RAISE 'test-error'; END; $$ LANGUAGE plpgsql;" )
expect {
@conn.copy_data( "COPY (SELECT errfunc()) TO STDOUT" ) do |res|
while @conn.get_copy_data
end
end
}.to raise_error(PG::Error, /test-error/)
end
expect( @conn ).to still_be_usable
end
it "can process #copy_data input queries" do
@conn.exec( "CREATE TEMP TABLE copytable (col1 TEXT)" )
res2 = @conn.copy_data( "COPY copytable FROM STDOUT" ) do |res|
expect( res.result_status ).to eq( PG::PGRES_COPY_IN )
expect( res.nfields ).to eq( 1 )
@conn.put_copy_data "1\n"
@conn.put_copy_data "2\n"
end
expect( res2.result_status ).to eq( PG::PGRES_COMMAND_OK )
expect( @conn ).to still_be_usable
res = @conn.exec( "SELECT * FROM copytable ORDER BY col1" )
expect( res.values ).to eq( [["1"], ["2"]] )
end
it "can handle client errors in #copy_data for input" do
@conn.exec "ROLLBACK"
@conn.transaction do
@conn.exec( "CREATE TEMP TABLE copytable (col1 TEXT)" )
expect {
@conn.copy_data( "COPY copytable FROM STDOUT" ) do |res|
raise "boom"
end
}.to raise_error(RuntimeError, "boom")
end
expect( @conn ).to still_be_usable
end
it "can handle server errors in #copy_data for input" do
@conn.exec "ROLLBACK"
@conn.transaction do
@conn.exec( "CREATE TEMP TABLE copytable (col1 INT)" )
expect {
@conn.copy_data( "COPY copytable FROM STDOUT" ) do |res|
@conn.put_copy_data "xyz\n"
end
}.to raise_error(PG::Error, /invalid input syntax for .*integer/)
end
expect( @conn ).to still_be_usable
end
it "gracefully handle SQL statements while in #copy_data for input" do
@conn.exec "ROLLBACK"
@conn.transaction do
@conn.exec( "CREATE TEMP TABLE copytable (col1 INT)" )
expect {
@conn.copy_data( "COPY copytable FROM STDOUT" ) do |res|
@conn.exec "SELECT 1"
end
}.to raise_error(PG::Error, /no COPY in progress/)
end
expect( @conn ).to still_be_usable
end
it "gracefully handle SQL statements while in #copy_data for output" do
@conn.exec "ROLLBACK"
@conn.transaction do
expect {
@conn.copy_data( "COPY (VALUES(1), (2)) TO STDOUT" ) do |res|
@conn.exec "SELECT 3"
end
}.to raise_error(PG::Error, /no COPY in progress/)
end
expect( @conn ).to still_be_usable
end
it "should raise an error for non copy statements in #copy_data" do
expect {
@conn.copy_data( "SELECT 1" ){}
}.to raise_error(ArgumentError, /no COPY/)
expect( @conn ).to still_be_usable
end
it "correctly finishes COPY queries passed to #async_exec" do
@conn.async_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 "described_class#block shouldn't block a second thread" do
start = Time.now
t = Thread.new do
@conn.send_query( "select pg_sleep(3)" )
@conn.block
end
sleep 0.5
expect( t ).to be_alive()
@conn.cancel
t.join
expect( (Time.now - start) ).to be < 3
end
it "described_class#block should allow a timeout" do
@conn.send_query( "select pg_sleep(100)" )
start = Time.now
@conn.block( 0.3 )
finish = Time.now
@conn.cancel
expect( (finish - start) ).to be_between( 0.2, 99 ).exclusive
end
it "can return the default connection options" do
expect( described_class.conndefaults ).to be_a( Array )
expect( described_class.conndefaults ).to all( be_a(Hash) )
expect( described_class.conndefaults[0] ).to include( :keyword, :label, :dispchar, :dispsize )
expect( @conn.conndefaults ).to eq( described_class.conndefaults )
end
it "can return the default connection options as a Hash" do
expect( described_class.conndefaults_hash ).to be_a( Hash )
expect( described_class.conndefaults_hash ).to include( :user, :password, :dbname, :host, :port )
expect( ['5432', '54321', @port.to_s] ).to include( described_class.conndefaults_hash[:port] )
expect( @conn.conndefaults_hash ).to eq( described_class.conndefaults_hash )
end
it "can return the connection's connection options", :postgresql_93 do
expect( @conn.conninfo ).to be_a( Array )
expect( @conn.conninfo ).to all( be_a(Hash) )
expect( @conn.conninfo[0] ).to include( :keyword, :label, :dispchar, :dispsize )
end
it "can return the connection's connection options as a Hash", :postgresql_93 do
expect( @conn.conninfo_hash ).to be_a( Hash )
expect( @conn.conninfo_hash ).to include( :user, :password, :connect_timeout, :dbname, :host )
expect( @conn.conninfo_hash[:dbname] ).to eq( 'test' )
end
describe "connection information related to SSL" do
it "can retrieve connection's ssl state", :postgresql_95 do
expect( @conn.ssl_in_use? ).to be false
end
it "can retrieve connection's ssl attribute_names", :postgresql_95 do
expect( @conn.ssl_attribute_names ).to be_a(Array)
end
it "can retrieve a single ssl connection attribute", :postgresql_95 do
expect( @conn.ssl_attribute('dbname') ).to eq( nil )
end
it "can retrieve all connection's ssl attributes", :postgresql_95 do
expect( @conn.ssl_attributes ).to be_a_kind_of( Hash )
end
end
it "honors the connect_timeout connection parameter", :postgresql_93 do
conn = PG.connect( port: @port, dbname: 'test', connect_timeout: 11 )
begin
expect( conn.conninfo_hash[:connect_timeout] ).to eq( "11" )
ensure
conn.finish
end
end
describe "deprecated password encryption method" do
it "can encrypt password for a given user" do
expect( described_class.encrypt_password("postgres", "postgres") ).to match( /\S+/ )
end
it "raises an appropriate error if either of the required arguments is not valid" do
expect {
described_class.encrypt_password( nil, nil )
}.to raise_error( TypeError )
expect {
described_class.encrypt_password( "postgres", nil )
}.to raise_error( TypeError )
expect {
described_class.encrypt_password( nil, "postgres" )
}.to raise_error( TypeError )
end
end
describe "password encryption method", :postgresql_10 do
it "can encrypt without algorithm" do
expect( @conn.encrypt_password("postgres", "postgres") ).to match( /\S+/ )
expect( @conn.encrypt_password("postgres", "postgres", nil) ).to match( /\S+/ )
end
it "can encrypt with algorithm" do
expect( @conn.encrypt_password("postgres", "postgres", "md5") ).to match( /md5\S+/i )
expect( @conn.encrypt_password("postgres", "postgres", "scram-sha-256") ).to match( /SCRAM-SHA-256\S+/i )
end
it "raises an appropriate error if either of the required arguments is not valid" do
expect {
@conn.encrypt_password( nil, nil )
}.to raise_error( TypeError )
expect {
@conn.encrypt_password( "postgres", nil )
}.to raise_error( TypeError )
expect {
@conn.encrypt_password( nil, "postgres" )
}.to raise_error( TypeError )
expect {
@conn.encrypt_password( "postgres", "postgres", :invalid )
}.to raise_error( TypeError )
expect {
@conn.encrypt_password( "postgres", "postgres", "invalid" )
}.to raise_error( PG::Error, /unrecognized/ )
end
end
it "allows fetching a column of values from a result by column number" do
res = @conn.exec( 'VALUES (1,2),(2,3),(3,4)' )
expect( res.column_values( 0 ) ).to eq( %w[1 2 3] )
expect( res.column_values( 1 ) ).to eq( %w[2 3 4] )
end
it "allows fetching a column of values from a result by field name" do
res = @conn.exec( 'VALUES (1,2),(2,3),(3,4)' )
expect( res.field_values( 'column1' ) ).to eq( %w[1 2 3] )
expect( res.field_values( 'column2' ) ).to eq( %w[2 3 4] )
end
it "raises an error if selecting an invalid column index" do
res = @conn.exec( 'VALUES (1,2),(2,3),(3,4)' )
expect {
res.column_values( 20 )
}.to raise_error( IndexError )
end
it "raises an error if selecting an invalid field name" do
res = @conn.exec( 'VALUES (1,2),(2,3),(3,4)' )
expect {
res.field_values( 'hUUuurrg' )
}.to raise_error( IndexError )
end
it "raises an error if column index is not a number" do
res = @conn.exec( 'VALUES (1,2),(2,3),(3,4)' )
expect {
res.column_values( 'hUUuurrg' )
}.to raise_error( TypeError )
end
it "handles server close while asynchronous connect" do
serv = TCPServer.new( '127.0.0.1', 54320 )
conn = described_class.connect_start( '127.0.0.1', 54320, "", "", "me", "xxxx", "somedb" )
expect( [PG::PGRES_POLLING_WRITING, PG::CONNECTION_OK] ).to include conn.connect_poll
select( nil, [conn.socket_io], nil, 0.2 )
serv.close
if conn.connect_poll == PG::PGRES_POLLING_READING
select( [conn.socket_io], nil, nil, 0.2 )
end
expect( conn.connect_poll ).to eq( PG::PGRES_POLLING_FAILED )
end
it "discards previous results at #discard_results" do
@conn.send_query( "select 1" )
@conn.discard_results
@conn.send_query( "select 41 as one" )
res = @conn.get_last_result
expect( res.to_a ).to eq( [{ 'one' => '41' }] )
end
it "discards previous results (if any) before waiting on #exec" do
@conn.send_query( "select 1" )
res = @conn.exec( "select 42 as one" )
expect( res.to_a ).to eq( [{ 'one' => '42' }] )
end
it "discards previous errors before waiting on #exec", :without_transaction do
@conn.send_query( "ERROR" )
res = @conn.exec( "select 43 as one" )
expect( res.to_a ).to eq( [{ 'one' => '43' }] )
end
it "calls the block if one is provided to #exec" do
result = nil
@conn.exec( "select 47 as one" ) do |pg_res|
result = pg_res[0]
end
expect( result ).to eq( { 'one' => '47' } )
end
it "raises a rescue-able error if #finish is called twice", :without_transaction do
conn = PG.connect( @conninfo )
conn.finish
expect { conn.finish }.to raise_error( PG::ConnectionBad, /connection is closed/i )
end
it "can use conn.reset to restart the connection" do
ios = IO.pipe
conn = PG.connect( @conninfo )
# 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
# The new connection should work even when the file descriptor has changed.
expect( conn.exec("SELECT 1").values ).to eq([["1"]])
conn.close
end
it "closes the IO fetched from #socket_io when the connection is closed", :without_transaction do
conn = PG.connect( @conninfo )
io = conn.socket_io
conn.finish
expect( io ).to be_closed()
expect { conn.socket_io }.to raise_error( PG::ConnectionBad, /connection is closed/i )
end
it "closes the IO fetched from #socket_io when the connection is reset", :without_transaction do
conn = PG.connect( @conninfo )