Repository navigation
Expand file tree
/
Copy pathquery_sql.rb
More file actions
1685 lines (1471 loc) · 56.8 KB
/
Copy pathquery_sql.rb
File metadata and controls
1685 lines (1471 loc) · 56.8 KB
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
# frozen_string_literal: true
# auto-generated by sqlc - do not edit
require 'connection_pool'
require 'pg'
require_relative 'connection'
require_relative 'models'
module PgCodegen
GET_AUTHOR_SQL = <<~'SQL'
SELECT id, name, bio FROM authors
WHERE id = $1 LIMIT 1
SQL
class GetAuthorRow < ::Data.define(:id, :name, :bio)
end
LIST_AUTHORS_SQL = <<~'SQL'
SELECT id, name, bio FROM authors
ORDER BY name
SQL
class ListAuthorsRow < ::Data.define(:id, :name, :bio)
end
CREATE_AUTHOR_SQL = <<~'SQL'
INSERT INTO authors (
name, bio
) VALUES (
$1, $2
)
RETURNING id, name, bio
SQL
class CreateAuthorRow < ::Data.define(:id, :name, :bio)
end
DELETE_AUTHOR_SQL = <<~'SQL'
DELETE FROM authors
WHERE id = $1
SQL
INSERT_POSTGRES_NUMERIC_TYPES_SQL = <<~'SQL'
INSERT INTO postgres_numeric_types (
c_boolean, c_smallint, c_integer, c_bigint, c_decimal, c_numeric, c_real, c_double_precision, c_money, c_oid, c_positive
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11
)
SQL
GET_POSTGRES_NUMERIC_TYPES_SQL = <<~'SQL'
SELECT c_boolean, c_smallint, c_integer, c_bigint, c_serial, c_decimal, c_numeric, c_real, c_double_precision, c_money, c_oid, c_positive FROM postgres_numeric_types LIMIT 1
SQL
class GetPostgresNumericTypesRow < ::Data.define(
:c_boolean,
:c_smallint,
:c_integer,
:c_bigint,
:c_serial,
:c_decimal,
:c_numeric,
:c_real,
:c_double_precision,
:c_money,
:c_oid,
:c_positive
)
end
INSERT_POSTGRES_STRING_TYPES_SQL = <<~'SQL'
INSERT INTO postgres_string_types (
c_char, c_varchar, c_text, c_not_null, c_xml, c_tsvector, c_ltree, c_hstore, c_regclass
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9
)
SQL
GET_POSTGRES_STRING_TYPES_SQL = <<~'SQL'
SELECT c_char, c_varchar, c_text, c_not_null, c_xml, c_tsvector, c_ltree, c_hstore, c_regclass FROM postgres_string_types LIMIT 1
SQL
class GetPostgresStringTypesRow < ::Data.define(
:c_char,
:c_varchar,
:c_text,
:c_not_null,
:c_xml,
:c_tsvector,
:c_ltree,
:c_hstore,
:c_regclass
)
end
INSERT_POSTGRES_DATETIME_TYPES_SQL = <<~'SQL'
INSERT INTO postgres_datetime_types (
c_date, c_time, c_timetz, c_timestamp, c_timestamptz, c_interval
) VALUES (
$1, $2, $3, $4, $5, $6
)
SQL
GET_POSTGRES_DATETIME_TYPES_SQL = <<~'SQL'
SELECT c_date, c_time, c_timetz, c_timestamp, c_timestamptz, c_interval FROM postgres_datetime_types LIMIT 1
SQL
class GetPostgresDatetimeTypesRow < ::Data.define(
:c_date,
:c_time,
:c_timetz,
:c_timestamp,
:c_timestamptz,
:c_interval
)
end
INSERT_POSTGRES_JSON_TYPES_SQL = <<~'SQL'
INSERT INTO postgres_json_types (id, c_json, c_jsonb) VALUES ($1, $2, $3)
SQL
GET_POSTGRES_JSON_TYPES_SQL = <<~'SQL'
SELECT c_json, c_jsonb FROM postgres_json_types WHERE id = $1
SQL
class GetPostgresJSONTypesRow < ::Data.define(:c_json, :c_jsonb)
end
TOGGLE_POSTGRES_JSONB_TYPE_SQL = <<~'SQL'
UPDATE postgres_json_types
SET c_jsonb = to_jsonb(NOT (c_jsonb #>> '{}')::boolean)
WHERE id = $1
SQL
INSERT_POSTGRES_ARRAY_TYPES_SQL = <<~'SQL'
INSERT INTO postgres_array_types (
id, c_boolean, c_double_precision, c_text_array, c_integer_array, c_uuid_array, c_bio_type_array, c_bytea_array, c_jsonb_array, c_numeric_array, c_timestamptz_array, c_integer_matrix, c_text_matrix
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13
)
SQL
LIST_POSTGRES_ARRAY_TYPES_SQL = <<~'SQL'
SELECT id, c_boolean, c_double_precision, c_text_array, c_integer_array, c_uuid_array, c_bio_type_array, c_bytea_array, c_jsonb_array, c_numeric_array, c_timestamptz_array, c_integer_matrix, c_text_matrix FROM postgres_array_types ORDER BY id
SQL
class ListPostgresArrayTypesRow < ::Data.define(
:id,
:c_boolean,
:c_double_precision,
:c_text_array,
:c_integer_array,
:c_uuid_array,
:c_bio_type_array,
:c_bytea_array,
:c_jsonb_array,
:c_numeric_array,
:c_timestamptz_array,
:c_integer_matrix,
:c_text_matrix
)
end
INSERT_POSTGRES_ARRAY_TYPES_BATCH_SQL = <<~'SQL'
INSERT INTO postgres_array_types (id, c_boolean, c_double_precision, c_bytea_array, c_jsonb_array, c_integer_array, c_numeric_array, c_timestamptz_array) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
SQL
class InsertPostgresArrayTypesBatchArgs < ::Data.define(
:id,
:c_boolean,
:c_double_precision,
:c_bytea_array,
:c_jsonb_array,
:c_integer_array,
:c_numeric_array,
:c_timestamptz_array
)
end
class CopyPostgresArrayTypesArgs < ::Data.define(
:id,
:c_boolean,
:c_double_precision,
:c_bytea_array,
:c_jsonb_array,
:c_integer_array,
:c_numeric_array,
:c_timestamptz_array
)
end
COUNT_POSTGRES_ARRAY_TYPES_ABOVE_SQL = <<~'SQL'
SELECT count(*) FROM postgres_array_types WHERE id > $1
SQL
class CountPostgresArrayTypesAboveRow < ::Data.define(:count)
end
INSERT_POSTGRES_SPECIAL_TYPES_SQL = <<~'SQL'
INSERT INTO postgres_special_types (
c_bytea, c_bit, c_varbit, c_uuid, c_inet, c_cidr, c_macaddr, c_point, c_int4range, c_dimensions
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10
)
SQL
GET_POSTGRES_SPECIAL_TYPES_SQL = <<~'SQL'
SELECT c_bytea, c_bit, c_varbit, c_uuid, c_inet, c_cidr, c_macaddr, c_point, c_int4range, c_dimensions FROM postgres_special_types LIMIT 1
SQL
class GetPostgresSpecialTypesRow < ::Data.define(
:c_bytea,
:c_bit,
:c_varbit,
:c_uuid,
:c_inet,
:c_cidr,
:c_macaddr,
:c_point,
:c_int4range,
:c_dimensions
)
end
TRUNCATE_TEST_TABLES_SQL = <<~'SQL'
TRUNCATE TABLE
postgres_numeric_types, postgres_string_types, postgres_datetime_types, postgres_json_types, postgres_array_types,
postgres_special_types, extended.bios, regressions, name_cases, "MixedCaseCopies", deferred_books
SQL
PAUSE_QUERY_SQL = <<~'SQL'
SELECT pg_sleep($1::double precision)
SQL
class PauseQueryRow < ::Data.define(:pg_sleep)
end
LIST_AUTHORS_PAGED_SQL = <<~'SQL'
SELECT id, name, bio FROM authors
ORDER BY name
LIMIT $2
OFFSET $1
SQL
class ListAuthorsPagedRow < ::Data.define(:id, :name, :bio)
end
GET_AUTHOR_BY_NAME_PATTERN_SQL = <<~'SQL'
SELECT id, name, bio FROM authors
WHERE name LIKE COALESCE($1, '%')
SQL
class GetAuthorByNamePatternRow < ::Data.define(:id, :name, :bio)
end
GET_AUTHORS_BY_OPTIONAL_NAME_SQL = <<~'SQL'
SELECT id, name, bio FROM authors
WHERE ($1::text IS NULL OR name = $1::text)
ORDER BY id
LIMIT $2
SQL
class GetAuthorsByOptionalNameRow < ::Data.define(:id, :name, :bio)
end
CREATE_AUTHOR_RETURN_ID_SQL = <<~'SQL'
INSERT INTO authors (name, bio) VALUES ($1, $2) RETURNING id
SQL
class CreateAuthorReturnIdRow < ::Data.define(:id)
end
UPDATE_AUTHOR_BIOS_SQL = <<~'SQL'
UPDATE authors
SET bio = $1
WHERE bio IS NOT NULL
SQL
GET_AUTHORS_BY_IDS_SQL = <<~'SQL'
SELECT id, name, bio FROM authors
WHERE id = ANY($1::BIGINT [])
SQL
class GetAuthorsByIdsRow < ::Data.define(:id, :name, :bio)
end
GET_AUTHORS_BY_IDS_AND_NAMES_SQL = <<~'SQL'
SELECT id, name, bio FROM authors
WHERE id = ANY($1::BIGINT []) AND name = ANY($2::TEXT [])
SQL
class GetAuthorsByIdsAndNamesRow < ::Data.define(:id, :name, :bio)
end
class CopyAuthorsArgs < ::Data.define(:name, :bio)
end
TRUNCATE_AUTHORS_SQL = <<~'SQL'
TRUNCATE TABLE authors CASCADE
SQL
CREATE_BOOK_SQL = <<~'SQL'
INSERT INTO books (name, author_id) VALUES ($1, $2) RETURNING id
SQL
class CreateBookRow < ::Data.define(:id)
end
CREATE_DEFERRED_BOOK_SQL = <<~'SQL'
INSERT INTO deferred_books (author_id) VALUES ($1)
SQL
LIST_ALL_AUTHORS_BOOKS_SQL = <<~'SQL'
SELECT
authors.id, authors.name, authors.bio,
books.id, books.name, books.author_id, books.description
FROM authors
INNER JOIN books ON authors.id = books.author_id
ORDER BY authors.name
SQL
class ListAllAuthorsBooksRow < ::Data.define(:author, :book)
end
GET_DUPLICATE_AUTHORS_SQL = <<~'SQL'
SELECT
authors1.id, authors1.name, authors1.bio,
authors2.id, authors2.name, authors2.bio
FROM authors AS authors1
INNER JOIN authors AS authors2 ON authors1.name = authors2.name
WHERE authors1.id < authors2.id
SQL
class GetDuplicateAuthorsRow < ::Data.define(:author, :author2)
end
GET_AUTHORS_BY_BOOK_NAME_SQL = <<~'SQL'
SELECT
authors.id, authors.name, authors.bio,
books.id, books.name, books.author_id, books.description
FROM authors INNER JOIN books ON authors.id = books.author_id
WHERE books.name = $1
SQL
class GetAuthorsByBookNameRow < ::Data.define(:id, :name, :bio, :book)
end
CREATE_EXTENDED_BIO_SQL = <<~'SQL'
INSERT INTO extended.bios (author_name, name, bio_type) VALUES ($1, $2, $3)
SQL
GET_FIRST_EXTENDED_BIO_BY_TYPE_SQL = <<~'SQL'
SELECT author_name, name, bio_type FROM extended.bios WHERE bio_type = $1 LIMIT 1
SQL
class GetFirstExtendedBioByTypeRow < ::Data.define(:author_name, :name, :bio_type)
end
LIST_AUTHORS_WITH_OPTIONAL_BOOK_SQL = <<~'SQL'
SELECT
authors.id, authors.name, authors.bio,
books.id, books.name, books.author_id, books.description
FROM authors
LEFT JOIN books ON authors.id = books.author_id
ORDER BY authors.name
SQL
class ListAuthorsWithOptionalBookRow < ::Data.define(:author, :book)
end
LIST_AUTHORS_BETWEEN_IDS_SQL = <<~'SQL'
SELECT id, name, bio FROM authors
WHERE id > $1 AND id < $2
ORDER BY id
SQL
class ListAuthorsBetweenIdsRow < ::Data.define(:id, :name, :bio)
end
CREATE_AUTHOR_RESULT_SQL = <<~'SQL'
INSERT INTO authors (name, bio) VALUES ($1, $2)
SQL
CREATE_AUTHORS_BATCH_SQL = <<~'SQL'
INSERT INTO authors (name, bio) VALUES ($1, $2)
SQL
class CreateAuthorsBatchArgs < ::Data.define(:name, :bio)
end
GET_AUTHOR_BATCH_SQL = <<~'SQL'
SELECT id, name, bio FROM authors WHERE id = $1
SQL
class GetAuthorBatchRow < ::Data.define(:id, :name, :bio)
end
class GetAuthorBatchArgs < ::Data.define(:id)
end
LIST_AUTHORS_BY_NAME_BATCH_SQL = <<~'SQL'
SELECT id, name, bio FROM authors WHERE name = $1 ORDER BY id
SQL
class ListAuthorsByNameBatchRow < ::Data.define(:id, :name, :bio)
end
class ListAuthorsByNameBatchArgs < ::Data.define(:name)
end
CREATE_REGRESSION_SQL = <<~'SQL'
INSERT INTO regressions (id, "order", payload, doc, bio_types, uids) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id, "order", payload, doc, bio_types, uids, step
SQL
class CreateRegressionRow < ::Data.define(
:id,
:order,
:payload,
:doc,
:bio_types,
:uids,
:step
)
end
CREATE_REGRESSION_IF_NEW_SQL = <<~'SQL'
INSERT INTO regressions (id, "order") VALUES ($1, $2) ON CONFLICT (id) DO NOTHING RETURNING id
SQL
class CreateRegressionIfNewRow < ::Data.define(:id)
end
class CopyRegressionsArgs < ::Data.define(:id, :order, :payload, :doc)
end
CREATE_REGRESSIONS_BATCH_SQL = <<~'SQL'
INSERT INTO regressions (id, "order", payload, doc) VALUES ($1, $2, $3, $4)
SQL
class CreateRegressionsBatchArgs < ::Data.define(:id, :order, :payload, :doc)
end
LIST_REGRESSIONS_SQL = <<~'SQL'
SELECT id, "order", payload, doc, bio_types, uids, step FROM regressions WHERE ($1::text IS NULL OR "order" = $1) ORDER BY id
SQL
class ListRegressionsRow < ::Data.define(
:id,
:order,
:payload,
:doc,
:bio_types,
:uids,
:step
)
end
SET_REGRESSION_STEP_SQL = <<~'SQL'
UPDATE regressions SET step = $2 WHERE id = $1 RETURNING step
SQL
class SetRegressionStepRow < ::Data.define(:step)
end
INSERT_NAME_CASE_SQL = <<~'SQL'
INSERT INTO name_cases (id, "class", "end", "hash", "method", "count", "camelCase", "HTTPServer", "initialize")
VALUES ($1, $2, $3, $4, $5, $6,
$7, $8, $9)
SQL
GET_NAME_CASE_SQL = <<~'SQL'
SELECT id, class, "end", hash, method, count, "camelCase", "HTTPServer", initialize FROM name_cases
WHERE id = $1 AND "class" = $2 AND "end" = $3 AND "hash" = $4
AND "method" = $5 AND "count" = $6
AND "HTTPServer" = $7 AND "camelCase" = $8
AND "initialize" = $9
SQL
# rubocop:disable Naming/MethodName
class GetNameCaseRow < ::Data.define(
:id,
:class_,
:end,
:hash_,
:method_,
:count,
:camelCase,
:HTTPServer,
:initialize_
)
end
# rubocop:enable Naming/MethodName
GET_HTTP_SERVER_SQL = <<~'SQL'
SELECT id, class, "end", hash, method, count, "camelCase", "HTTPServer", initialize FROM name_cases WHERE id = $1
SQL
# rubocop:disable Naming/MethodName
class GetHTTPServerRow < ::Data.define(
:id,
:class_,
:end,
:hash_,
:method_,
:count,
:camelCase,
:HTTPServer,
:initialize_
)
end
# rubocop:enable Naming/MethodName
class CopyMixedCaseCopiesArgs < ::Data.define(:id, :some_value)
end
LIST_MIXED_CASE_COPIES_SQL = <<~'SQL'
SELECT "Id", "SomeValue" FROM "MixedCaseCopies" ORDER BY "Id"
SQL
# rubocop:disable Naming/MethodName
class ListMixedCaseCopiesRow < ::Data.define(:Id, :SomeValue)
end
# rubocop:enable Naming/MethodName
GET_UNNAMED_COLUMNS_SQL = <<~'SQL'
SELECT 1, 'two'
SQL
# rubocop:disable Naming/VariableNumber
class GetUnnamedColumnsRow < ::Data.define(:column_1, :column_2)
end
# rubocop:enable Naming/VariableNumber
GET_QUOTED_ALIAS_SQL = <<~'SQL'
SELECT 1 AS "it's"
SQL
class GetQuotedAliasRow < ::Data.define(:it_s)
end
CREATE_EXCEPTION_SQL = <<~'SQL'
INSERT INTO exceptions DEFAULT VALUES
SQL
COUNT_EXCEPTIONS_SQL = <<~'SQL'
SELECT COUNT(*) AS n FROM exceptions
SQL
class CountExceptionsRow < ::Data.define(:n)
end
TRUNCATE_EXCEPTIONS_SQL = <<~'SQL'
TRUNCATE exceptions
SQL
CREATE_LATE_FEELING_SQL = <<~'SQL'
INSERT INTO late.feelings (id, moods) VALUES ($1, $2)
SQL
GET_LATE_FEELING_SQL = <<~'SQL'
SELECT moods FROM late.feelings WHERE id = $1
SQL
class GetLateFeelingRow < ::Data.define(:moods)
end
HAS_AUTHORS_SQL = <<~'SQL'
SELECT EXISTS (SELECT 1 FROM authors) AS has_any
SQL
class HasAuthorsRow < ::Data.define(:has_any)
end
class QuerySql
# Raised by the bang variants (get_author!) when the query returns no row.
class NotFound < ::StandardError; end
# Opens a pool of connections: QuerySql.connect({ dbname: 'app' }, size: 5, timeout: 5, logger: Logger.new($stdout))
# or QuerySql.connect(ENV.fetch('DATABASE_URL')) (pool_options go to ConnectionPool.new). To share an existing
# pool use QuerySql.new(pool).
def self.connect(pg_params, logger: nil, **pool_options)
connect = pg_params.is_a?(::String) ? -> { ::PG.connect(pg_params) } : -> { ::PG.connect(**pg_params) }
new(::ConnectionPool.new(**pool_options, &connect), logger: logger)
end
# db: a ConnectionPool (or anything that responds to #with and yields a PG::Connection).
# logger: optional, anything with #debug (Logger, Rails.logger); logs the name and duration of every query.
def initialize(db, logger: nil)
@db = db
@logger = logger
end
# Runs the block in a transaction on one connection and returns its value: COMMIT when the block returns
# (also through break / return / throw), ROLLBACK when it raises or the thread is killed. A nested call
# becomes a SAVEPOINT. Yields a copy of self whose queries run in the transaction, also from other fibers and
# threads (Enumerator, Async tasks); it raises TransactionEnded when used after the transaction.
def transaction(isolation: nil)
raise ::ArgumentError, "unknown isolation level: #{isolation.inspect}" unless isolation.nil? || ISOLATION_LEVELS.key?(isolation)
with_client('transaction') do |client|
outermost = client.transaction_status == ::PG::PQTRANS_IDLE
raise ::ArgumentError, 'isolation: cannot be set on a nested transaction' if isolation && !outermost
savepoint = outermost ? nil : "sqlc_sp_#{rand(0xffff_ffff).to_s(16)}"
start = if outermost
isolation ? "BEGIN ISOLATION LEVEL #{ISOLATION_LEVELS.fetch(isolation)}" : 'BEGIN'
else
"SAVEPOINT #{savepoint}"
end
rollback = outermost ? 'ROLLBACK' : "ROLLBACK TO SAVEPOINT #{savepoint}"
# Timeout / Thread#raise / Thread#kill wait while BEGIN, COMMIT and ROLLBACK run and only interrupt the
# block: the connection never goes back to the pool inside a transaction.
bound = TransactionConnection.new(client) unless @db.is_a?(TransactionConnection)
::Thread.handle_interrupt(::Object => :never) do
entered = !client.in_transaction
client.in_transaction = true
started = false
failed = false
begin
client.exec(start)
started = true
::Thread.handle_interrupt(::Object => :immediate) do
bound ? yield(bound_to(bound)) : @db.unlocked { yield self }
end
rescue ::Exception # rubocop:disable Lint/RescueException
failed = true
bound&.close
client.cancel if client.transaction_status == ::PG::PQTRANS_ACTIVE
# BEGIN itself may have raised after it ran (an Async task stopped while it waited)
begun = started || (outermost && client.transaction_status != ::PG::PQTRANS_IDLE)
client.exec(rollback) if begun && client.status != ::PG::CONNECTION_BAD # the server already rolled back
raise
ensure
bound&.close
client.in_transaction = false if entered
if failed
nil
elsif client.status == ::PG::CONNECTION_BAD
# the block rescued the error of a lost connection: the server rolled the transaction back
raise ::PG::ConnectionBad, 'transaction rolled back: the connection was lost' if ::Thread.current.status != 'aborting'
else
# a statement failed and the block rescued the error: PostgreSQL can only roll back
rescued = client.transaction_status == ::PG::PQTRANS_INERROR
commit = outermost ? 'COMMIT' : "RELEASE SAVEPOINT #{savepoint}"
begin
client.exec(rescued || ::Thread.current.status == 'aborting' ? rollback : commit)
rescue ::Exception # rubocop:disable Lint/RescueException
# COMMIT did not run (an Async task stopped while it waited): roll back instead of leaving it open
client.cancel if client.transaction_status == ::PG::PQTRANS_ACTIVE
open = client.status != ::PG::CONNECTION_BAD && client.transaction_status != ::PG::PQTRANS_IDLE
client.exec('ROLLBACK') if outermost && open
raise
end
client.exec("RELEASE SAVEPOINT #{savepoint}") if rescued && savepoint
raise ::PG::InFailedSqlTransaction, 'transaction rolled back: a statement in it failed' if rescued && ::Thread.current.status != 'aborting'
end
end
end
end
end
class ExecResult < ::Data.define(:rows_affected, :last_insert_id)
end
# Returns the author with the given id, or nil when there is none.
def get_author(id:)
with_client('get_author') do |client|
query_params = [id]
result = run_prepared(client, 'PgCodegen::QuerySql#get_author', GET_AUTHOR_SQL, query_params)
row = result.first
row && GetAuthorRow.new(row['id'], row['name'], row['bio'])
end
end
# Like #get_author, but raises NotFound when there is no row.
def get_author!(...)
get_author(...) || raise(NotFound, 'GetAuthor returned no row')
end
def list_authors
with_client('list_authors') do |client|
result = run_prepared(client, 'PgCodegen::QuerySql#list_authors', LIST_AUTHORS_SQL)
result.map do |row|
ListAuthorsRow.new(row['id'], row['name'], row['bio'])
end
end
end
def create_author(name:, bio:)
with_client('create_author') do |client|
query_params = [name, bio]
result = run_prepared(client, 'PgCodegen::QuerySql#create_author', CREATE_AUTHOR_SQL, query_params)
row = result.first
row && CreateAuthorRow.new(row['id'], row['name'], row['bio'])
end
end
# Like #create_author, but raises NotFound when there is no row.
def create_author!(...)
create_author(...) || raise(NotFound, 'CreateAuthor returned no row')
end
def delete_author(id:)
with_client('delete_author') do |client|
query_params = [id]
run_prepared(client, 'PgCodegen::QuerySql#delete_author', DELETE_AUTHOR_SQL, query_params)
nil
end
end
def insert_postgres_numeric_types(c_boolean:, c_smallint:, c_integer:, c_bigint:, c_decimal:, c_numeric:, c_real:, c_double_precision:, c_money:, c_oid:, c_positive:)
with_client('insert_postgres_numeric_types') do |client|
query_params = [
c_boolean,
c_smallint,
c_integer,
c_bigint,
c_decimal,
c_numeric,
encode_float(c_real),
encode_float(c_double_precision),
c_money,
c_oid,
c_positive
]
run_prepared(client, 'PgCodegen::QuerySql#insert_postgres_numeric_types', INSERT_POSTGRES_NUMERIC_TYPES_SQL, query_params)
nil
end
end
def get_postgres_numeric_types
with_client('get_postgres_numeric_types') do |client|
result = run_prepared(client, 'PgCodegen::QuerySql#get_postgres_numeric_types', GET_POSTGRES_NUMERIC_TYPES_SQL)
row = result.first
row && GetPostgresNumericTypesRow.new(
row['c_boolean'],
row['c_smallint'],
row['c_integer'],
row['c_bigint'],
row['c_serial'],
row['c_decimal'],
row['c_numeric'],
row['c_real'],
row['c_double_precision'],
row['c_money'],
row['c_oid'],
row['c_positive']
)
end
end
# Like #get_postgres_numeric_types, but raises NotFound when there is no row.
def get_postgres_numeric_types!(...)
get_postgres_numeric_types(...) || raise(NotFound, 'GetPostgresNumericTypes returned no row')
end
def insert_postgres_string_types(c_char:, c_varchar:, c_text:, c_not_null:, c_xml:, c_tsvector:, c_ltree:, c_hstore:, c_regclass:)
with_client('insert_postgres_string_types') do |client|
query_params = [
c_char,
c_varchar,
c_text,
c_not_null,
c_xml,
c_tsvector,
c_ltree,
c_hstore,
c_regclass
]
run_prepared(client, 'PgCodegen::QuerySql#insert_postgres_string_types', INSERT_POSTGRES_STRING_TYPES_SQL, query_params)
nil
end
end
def get_postgres_string_types
with_client('get_postgres_string_types') do |client|
result = run_prepared(client, 'PgCodegen::QuerySql#get_postgres_string_types', GET_POSTGRES_STRING_TYPES_SQL)
row = result.first
row && GetPostgresStringTypesRow.new(
row['c_char'],
row['c_varchar'],
row['c_text'],
row['c_not_null'],
row['c_xml'],
row['c_tsvector'],
row['c_ltree'],
row['c_hstore'],
row['c_regclass']
)
end
end
# Like #get_postgres_string_types, but raises NotFound when there is no row.
def get_postgres_string_types!(...)
get_postgres_string_types(...) || raise(NotFound, 'GetPostgresStringTypes returned no row')
end
def insert_postgres_datetime_types(c_date:, c_time:, c_timetz:, c_timestamp:, c_timestamptz:, c_interval:)
with_client('insert_postgres_datetime_types') do |client|
query_params = [
c_date,
c_time,
c_timetz,
encode_timestamp(c_timestamp),
encode_timestamp(c_timestamptz),
c_interval
]
run_prepared(client, 'PgCodegen::QuerySql#insert_postgres_datetime_types', INSERT_POSTGRES_DATETIME_TYPES_SQL, query_params)
nil
end
end
def get_postgres_datetime_types
with_client('get_postgres_datetime_types') do |client|
result = run_prepared(client, 'PgCodegen::QuerySql#get_postgres_datetime_types', GET_POSTGRES_DATETIME_TYPES_SQL)
row = result.first
row && GetPostgresDatetimeTypesRow.new(
row['c_date'],
row['c_time'],
row['c_timetz'],
row['c_timestamp'],
row['c_timestamptz'],
row['c_interval']
)
end
end
# Like #get_postgres_datetime_types, but raises NotFound when there is no row.
def get_postgres_datetime_types!(...)
get_postgres_datetime_types(...) || raise(NotFound, 'GetPostgresDatetimeTypes returned no row')
end
def insert_postgres_json_types(id:, c_json:, c_jsonb:)
with_client('insert_postgres_json_types') do |client|
query_params = [id, encode_json(c_json), encode_json(c_jsonb)]
run_prepared(client, 'PgCodegen::QuerySql#insert_postgres_json_types', INSERT_POSTGRES_JSON_TYPES_SQL, query_params)
nil
end
end
def get_postgres_json_types(id:)
with_client('get_postgres_json_types') do |client|
query_params = [id]
result = run_prepared(client, 'PgCodegen::QuerySql#get_postgres_json_types', GET_POSTGRES_JSON_TYPES_SQL, query_params)
row = result.first
row && GetPostgresJSONTypesRow.new(row['c_json'], row['c_jsonb'])
end
end
# Like #get_postgres_json_types, but raises NotFound when there is no row.
def get_postgres_json_types!(...)
get_postgres_json_types(...) || raise(NotFound, 'GetPostgresJSONTypes returned no row')
end
def toggle_postgres_jsonb_type(id:)
with_client('toggle_postgres_jsonb_type') do |client|
query_params = [id]
run_prepared(client, 'PgCodegen::QuerySql#toggle_postgres_jsonb_type', TOGGLE_POSTGRES_JSONB_TYPE_SQL, query_params)
nil
end
end
def insert_postgres_array_types(id:, c_boolean:, c_double_precision:, c_text_array:, c_integer_array:, c_uuid_array:, c_bio_type_array:, c_bytea_array:, c_jsonb_array:, c_numeric_array:, c_timestamptz_array:, c_integer_matrix:, c_text_matrix:)
with_client('insert_postgres_array_types') do |client|
query_params = [
id,
c_boolean,
encode_float(c_double_precision),
encode_array(c_text_array),
encode_array(c_integer_array),
encode_array(c_uuid_array),
encode_array(c_bio_type_array),
encode_array(c_bytea_array, :bytea),
encode_array(c_jsonb_array, :json),
encode_array(c_numeric_array),
encode_array(c_timestamptz_array),
encode_array(c_integer_matrix),
encode_array(c_text_matrix)
]
run_prepared(client, 'PgCodegen::QuerySql#insert_postgres_array_types', INSERT_POSTGRES_ARRAY_TYPES_SQL, query_params)
nil
end
end
def list_postgres_array_types
with_client('list_postgres_array_types') do |client|
result = run_prepared(client, 'PgCodegen::QuerySql#list_postgres_array_types', LIST_POSTGRES_ARRAY_TYPES_SQL)
result.map do |row|
ListPostgresArrayTypesRow.new(
row['id'],
row['c_boolean'],
row['c_double_precision'],
row['c_text_array'],
row['c_integer_array'],
row['c_uuid_array'],
row['c_bio_type_array'],
row['c_bytea_array'],
row['c_jsonb_array'],
row['c_numeric_array'],
row['c_timestamptz_array'],
row['c_integer_matrix'],
row['c_text_matrix']
)
end
end
end
def insert_postgres_array_types_batch(rows)
with_client('insert_postgres_array_types_batch') do |client|
rows.each do |args|
query_params = [
args.id,
args.c_boolean,
encode_float(args.c_double_precision),
encode_array(args.c_bytea_array, :bytea),
encode_array(args.c_jsonb_array, :json),
encode_array(args.c_integer_array),
encode_array(args.c_numeric_array),
encode_array(args.c_timestamptz_array)
]
run_prepared(client, 'PgCodegen::QuerySql#insert_postgres_array_types_batch', INSERT_POSTGRES_ARRAY_TYPES_BATCH_SQL, query_params)
end
nil
end
end
def copy_postgres_array_types(rows)
with_client('copy_postgres_array_types') do |client|
encoder = ::PG::TextEncoder::CopyRow.new(type_map: client.query_types)
client.copy_data('COPY "postgres_array_types" ("id", "c_boolean", "c_double_precision", "c_bytea_array", "c_jsonb_array", "c_integer_array", "c_numeric_array", "c_timestamptz_array") FROM STDIN', encoder) do
rows.each do |row|
client.put_copy_data([row.id, row.c_boolean, encode_float(row.c_double_precision), encode_array(row.c_bytea_array, :bytea), encode_array(row.c_jsonb_array, :json), encode_array(row.c_integer_array), encode_array(row.c_numeric_array), encode_array(row.c_timestamptz_array)])
end
end
nil
end
end
def count_postgres_array_types_above(min_id:)
with_client('count_postgres_array_types_above') do |client|
query_params = [min_id]
result = run_prepared(client, 'PgCodegen::QuerySql#count_postgres_array_types_above', COUNT_POSTGRES_ARRAY_TYPES_ABOVE_SQL, query_params)
row = result.first
row && CountPostgresArrayTypesAboveRow.new(row['count'])
end
end
# Like #count_postgres_array_types_above, but raises NotFound when there is no row.
def count_postgres_array_types_above!(...)
count_postgres_array_types_above(...) || raise(NotFound, 'CountPostgresArrayTypesAbove returned no row')
end
def insert_postgres_special_types(c_bytea:, c_bit:, c_varbit:, c_uuid:, c_inet:, c_cidr:, c_macaddr:, c_point:, c_int4range:, c_dimensions:)
with_client('insert_postgres_special_types') do |client|
query_params = [
encode_bytea(c_bytea),
c_bit,
c_varbit,
c_uuid,
c_inet,
c_cidr,
c_macaddr,
c_point,
c_int4range,
c_dimensions
]
run_prepared(client, 'PgCodegen::QuerySql#insert_postgres_special_types', INSERT_POSTGRES_SPECIAL_TYPES_SQL, query_params)
nil
end
end
def get_postgres_special_types
with_client('get_postgres_special_types') do |client|
result = run_prepared(client, 'PgCodegen::QuerySql#get_postgres_special_types', GET_POSTGRES_SPECIAL_TYPES_SQL)
row = result.first
row && GetPostgresSpecialTypesRow.new(
row['c_bytea'],
row['c_bit'],
row['c_varbit'],
row['c_uuid'],
row['c_inet'],
row['c_cidr'],
row['c_macaddr'],
row['c_point'],
row['c_int4range'],
row['c_dimensions']
)
end
end
# Like #get_postgres_special_types, but raises NotFound when there is no row.
def get_postgres_special_types!(...)
get_postgres_special_types(...) || raise(NotFound, 'GetPostgresSpecialTypes returned no row')
end
def truncate_test_tables
with_client('truncate_test_tables') do |client|
run_prepared(client, 'PgCodegen::QuerySql#truncate_test_tables', TRUNCATE_TEST_TABLES_SQL)
nil
end