Repository navigation
Expand file tree
/
Copy pathquery_sql.rb
More file actions
1466 lines (1287 loc) · 40.4 KB
/
Copy pathquery_sql.rb
File metadata and controls
1466 lines (1287 loc) · 40.4 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 'sqlite3'
require 'monitor'
require_relative 'connection'
require_relative 'models'
module Sqlite3Codegen
GET_AUTHOR_SQL = <<~'SQL'
SELECT id, name, bio FROM authors
WHERE id = ? 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 (
?, ?
)
SQL
DELETE_AUTHOR_SQL = <<~'SQL'
DELETE FROM authors
WHERE id = ?
SQL
LIST_AUTHORS_PAGED_SQL = <<~'SQL'
SELECT id, name, bio FROM authors
ORDER BY name
LIMIT ? OFFSET ?
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(?, '%')
SQL
class GetAuthorByNamePatternRow < ::Data.define(:id, :name, :bio)
end
GET_AUTHORS_BY_OPTIONAL_NAME_SQL = <<~'SQL'
SELECT id, name, bio FROM authors
WHERE (? IS NULL OR name = ?)
ORDER BY id
LIMIT ?
SQL
class GetAuthorsByOptionalNameRow < ::Data.define(:id, :name, :bio)
end
CREATE_AUTHOR_RETURN_ID_SQL = <<~'SQL'
INSERT INTO authors (name, bio) VALUES (?, ?) RETURNING id
SQL
class CreateAuthorReturnIdRow < ::Data.define(:id)
end
UPDATE_AUTHOR_BIOS_SQL = <<~'SQL'
UPDATE authors
SET bio = ?
WHERE bio IS NOT NULL
SQL
GET_AUTHORS_BY_IDS_SQL = <<~'SQL'
SELECT id, name, bio FROM authors WHERE id IN (/*SLICE:ids*/?)
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 IN (/*SLICE:ids*/?) AND name IN (/*SLICE:names*/?)
SQL
class GetAuthorsByIdsAndNamesRow < ::Data.define(:id, :name, :bio)
end
GET_AUTHORS_BY_MIXED_PLACEHOLDERS_SQL = <<~'SQL'
SELECT id, name, bio FROM authors
WHERE name = ?
AND id IN (/*SLICE:ids*/?)
AND name = ?
AND id > ?
AND id IN (/*SLICE:more*/?)
AND 'x?' != '?3'
ORDER BY id
SQL
class GetAuthorsByMixedPlaceholdersRow < ::Data.define(:id, :name, :bio)
end
GET_AUTHORS_BY_REPEATED_NAMED_AND_POSITIONAL_SQL = <<~'SQL'
SELECT id, name, bio FROM authors
WHERE name = ?
AND name != ?
AND id > ?
AND name = ?
ORDER BY id
SQL
class GetAuthorsByRepeatedNamedAndPositionalRow < ::Data.define(:id, :name, :bio)
end
GET_AUTHORS_BY_REPEATED_NAMED_AND_POSITIONAL_BATCH_SQL = <<~'SQL'
SELECT id, name, bio FROM authors
WHERE name = ?
AND name != ?
AND id > ?
AND name = ?
ORDER BY id
LIMIT 1
SQL
class GetAuthorsByRepeatedNamedAndPositionalBatchRow < ::Data.define(:id, :name, :bio)
end
class GetAuthorsByRepeatedNamedAndPositionalBatchArgs < ::Data.define(:n, :other, :id)
end
class CopyAuthorsArgs < ::Data.define(:name, :bio)
end
class CopyAuthorsNamedArgs < ::Data.define(:name, :bio)
end
TRUNCATE_AUTHORS_SQL = <<~'SQL'
DELETE FROM authors
SQL
CREATE_BOOK_SQL = <<~'SQL'
INSERT INTO books (name, author_id) VALUES (?, ?) RETURNING id
SQL
class CreateBookRow < ::Data.define(:id)
end
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 = ?
SQL
class GetAuthorsByBookNameRow < ::Data.define(:id, :name, :bio, :book)
end
CREATE_AUTHOR_RESULT_SQL = <<~'SQL'
INSERT INTO authors (name, bio) VALUES (?, ?)
SQL
CREATE_AUTHORS_BATCH_SQL = <<~'SQL'
INSERT INTO authors (name, bio) VALUES (?, ?)
SQL
class CreateAuthorsBatchArgs < ::Data.define(:name, :bio)
end
GET_AUTHOR_BATCH_SQL = <<~'SQL'
SELECT id, name, bio FROM authors WHERE id = ?
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 = ? ORDER BY id
SQL
class ListAuthorsByNameBatchRow < ::Data.define(:id, :name, :bio)
end
class ListAuthorsByNameBatchArgs < ::Data.define(:name)
end
INSERT_DECLARED_TYPES_SQL = <<~'SQL'
INSERT INTO declared_types (c_varchar, c_decimal, c_unsigned_big_int, c_native, c_double, c_json, c_uuid) VALUES (?, ?, ?, ?, ?, ?, ?)
SQL
GET_DECLARED_TYPES_SQL = <<~'SQL'
SELECT c_varchar, c_decimal, c_unsigned_big_int, c_native, c_double, c_json, c_uuid FROM declared_types LIMIT 1
SQL
class GetDeclaredTypesRow < ::Data.define(
:c_varchar,
:c_decimal,
:c_unsigned_big_int,
:c_native,
:c_double,
:c_json,
:c_uuid
)
end
TRUNCATE_DECLARED_TYPES_SQL = <<~'SQL'
DELETE FROM declared_types
SQL
CREATE_REGRESSION_SQL = <<~'SQL'
INSERT INTO regressions ("order", price) VALUES (?, ?) RETURNING id
SQL
class CreateRegressionRow < ::Data.define(:id)
end
UPDATE_REGRESSION_PRICES_SQL = <<~'SQL'
UPDATE regressions SET price = ? RETURNING id
SQL
class UpdateRegressionPricesRow < ::Data.define(:id)
end
class CopyRegressionsArgs < ::Data.define(:order, :price)
end
LIST_REGRESSIONS_SQL = <<~'SQL'
SELECT id, "order", price FROM regressions ORDER BY id
SQL
class ListRegressionsRow < ::Data.define(:id, :order, :price)
end
GET_MAX_REGRESSION_PRICE_SQL = <<~'SQL'
SELECT coalesce(max(price), 0) AS max_price FROM regressions
SQL
class GetMaxRegressionPriceRow < ::Data.define(:max_price)
end
TRUNCATE_REGRESSIONS_SQL = <<~'SQL'
DELETE FROM regressions
SQL
class CopyRegressionRowsArgs < ::Data.define(:id, :order, :price, :payload)
end
LIST_REGRESSION_ROWS_SQL = <<~'SQL'
SELECT id, "order", price, payload FROM regressions ORDER BY id
SQL
class ListRegressionRowsRow < ::Data.define(:id, :order, :price, :payload)
end
TRUNCATE_REGRESSION_ROWS_SQL = <<~'SQL'
DELETE FROM regressions
SQL
PAUSE_QUERY_SQL = <<~'SQL'
SELECT sleep(?)
SQL
class PauseQueryRow < ::Data.define(:sleep)
end
class CopyTagsOrReplaceArgs < ::Data.define(:name, :uses)
end
class CopyTagsOrIgnoreArgs < ::Data.define(:name, :uses)
end
class CopyTagsAddingUsesArgs < ::Data.define(:name, :uses)
end
LIST_TAGS_SQL = <<~'SQL'
SELECT name, uses FROM tags ORDER BY name
SQL
class ListTagsRow < ::Data.define(:name, :uses)
end
TRUNCATE_TAGS_SQL = <<~'SQL'
DELETE FROM tags
SQL
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.id
SQL
class ListAuthorsWithOptionalBookRow < ::Data.define(:author, :book)
end
INSERT_NAME_CASE_SQL = <<~'SQL'
INSERT INTO name_cases (id, "class", "end", "hash", "method", "count", "camelCase", "HTTPServer", "initialize")
VALUES (?, ?, ?, ?, ?, ?,
?, ?, ?)
SQL
GET_NAME_CASE_SQL = <<~'SQL'
SELECT id, class, "end", hash, method, count, camelCase, HTTPServer, initialize FROM name_cases
WHERE id = ? AND "class" = ? AND "end" = ? AND "hash" = ?
AND "method" = ? AND "count" = ?
AND "HTTPServer" = ? AND "camelCase" = ?
AND "initialize" = ?
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 = ?
SQL
# rubocop:disable Naming/MethodName
class GetHTTPServerRow < ::Data.define(
:id,
:class_,
:end,
:hash_,
:method_,
:count,
:camelCase,
:HTTPServer,
:initialize_
)
end
# rubocop:enable Naming/MethodName
TRUNCATE_NAME_CASES_SQL = <<~'SQL'
DELETE FROM name_cases
SQL
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
GET_AUTHORS_NOT_IN_IDS_SQL = <<~'SQL'
SELECT id, name, bio FROM authors WHERE id NOT IN (/*SLICE:ids*/?) ORDER BY id
SQL
class GetAuthorsNotInIdsRow < ::Data.define(:id, :name, :bio)
end
CREATE_AUTHOR_OR_ROLLBACK_SQL = <<~'SQL'
INSERT OR ROLLBACK INTO authors (id, name) VALUES (?, ?)
SQL
CREATE_TAG_RESULT_SQL = <<~'SQL'
INSERT INTO tags (name, uses) VALUES (?, ?) RETURNING name
SQL
class CreateTagResultRow < ::Data.define(:name)
end
CREATE_EXCEPTION_SQL = <<~'SQL'
INSERT INTO exceptions (id) VALUES (NULL)
SQL
COUNT_EXCEPTIONS_SQL = <<~'SQL'
SELECT COUNT(*) AS n FROM exceptions
SQL
class CountExceptionsRow < ::Data.define(:n)
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
# db: a SQLite3::Database (a single connection; threads and fibers using it take turns).
# 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
@lock = ConnectionLock.for(db)
end
# Runs the block in a transaction 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. mode: :deferred (default), :immediate or :exclusive. Other threads / fibers using the same
# database wait until it ends. 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(mode: nil)
raise ::ArgumentError, "unknown transaction mode: #{mode.inspect}" unless [nil, *TRANSACTION_MODES].include?(mode)
instrument('transaction') do
@lock.synchronize do
outermost = !@db.transaction_active?
raise ::ArgumentError, 'mode: cannot be set on a nested transaction' if mode && !outermost
savepoint = outermost ? nil : "sqlc_sp_#{rand(0xffff_ffff).to_s(16)}"
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 database is never left inside a transaction.
bound = TransactionConnection.new(@db) unless @lock.is_a?(TransactionConnection)
::Thread.handle_interrupt(::Object => :never) do
started = false
failed = false
begin
@db.execute(outermost ? "BEGIN#{" #{mode.to_s.upcase}" if mode}" : "SAVEPOINT #{savepoint}")
started = true
::Thread.handle_interrupt(::Object => :immediate) do
bound ? yield(bound_to(bound)) : @lock.unlocked { yield self }
end
rescue ::Exception # rubocop:disable Lint/RescueException
failed = true
bound&.close
# ON CONFLICT ROLLBACK already ended it
@db.execute(rollback) if (started || outermost) && @db.transaction_active?
raise
ensure
bound&.close
unless failed
commit = outermost ? 'COMMIT' : "RELEASE SAVEPOINT #{savepoint}"
begin
@db.execute(::Thread.current.status == 'aborting' ? rollback : commit)
rescue ::Exception # rubocop:disable Lint/RescueException
# COMMIT failed (SQLITE_BUSY) or did not run: roll back instead of leaving the transaction open
@db.execute('ROLLBACK') if outermost && @db.transaction_active?
raise
end
end
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]
stmt = client.prepare(GET_AUTHOR_SQL)
begin
result = execute_statement(stmt, *query_params)
row = result.first
row && GetAuthorRow.new(row[0], row[1], row[2])
ensure
stmt.close
end
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|
stmt = client.prepare(LIST_AUTHORS_SQL)
begin
result = execute_statement(stmt)
result.map do |row|
ListAuthorsRow.new(row[0], row[1], row[2])
end
ensure
stmt.close
end
end
end
def create_author(name:, bio:)
with_client('create_author') do |client|
query_params = [name, bio]
stmt = client.prepare(CREATE_AUTHOR_SQL)
begin
execute_statement(stmt, *query_params)
nil
ensure
stmt.close
end
end
end
def delete_author(id:)
with_client('delete_author') do |client|
query_params = [id]
stmt = client.prepare(DELETE_AUTHOR_SQL)
begin
execute_statement(stmt, *query_params)
nil
ensure
stmt.close
end
end
end
def list_authors_paged(offset:, limit:)
with_client('list_authors_paged') do |client|
query_params = [limit, offset]
stmt = client.prepare(LIST_AUTHORS_PAGED_SQL)
begin
result = execute_statement(stmt, *query_params)
result.map do |row|
ListAuthorsPagedRow.new(row[0], row[1], row[2])
end
ensure
stmt.close
end
end
end
def get_author_by_name_pattern(name_pattern: nil)
with_client('get_author_by_name_pattern') do |client|
query_params = [name_pattern]
stmt = client.prepare(GET_AUTHOR_BY_NAME_PATTERN_SQL)
begin
result = execute_statement(stmt, *query_params)
result.map do |row|
GetAuthorByNamePatternRow.new(row[0], row[1], row[2])
end
ensure
stmt.close
end
end
end
def get_authors_by_optional_name(lim:, name_filter: nil)
with_client('get_authors_by_optional_name') do |client|
query_params = [name_filter, name_filter, lim]
stmt = client.prepare(GET_AUTHORS_BY_OPTIONAL_NAME_SQL)
begin
result = execute_statement(stmt, *query_params)
result.map do |row|
GetAuthorsByOptionalNameRow.new(row[0], row[1], row[2])
end
ensure
stmt.close
end
end
end
def create_author_return_id(name:, bio:)
with_client('create_author_return_id') do |client|
query_params = [name, bio]
stmt = client.prepare(CREATE_AUTHOR_RETURN_ID_SQL)
begin
result = execute_statement(stmt, *query_params)
row = result.first
row && row[0]
ensure
stmt.close
end
end
end
# Sets the bio of every author that has one and returns how many were changed.
def update_author_bios(bio:)
with_client('update_author_bios') do |client|
query_params = [bio]
stmt = client.prepare(UPDATE_AUTHOR_BIOS_SQL)
begin
execute_statement(stmt, *query_params)
client.changes
ensure
stmt.close
end
end
end
def get_authors_by_ids(ids:)
with_client('get_authors_by_ids') do |client|
query_params = [*ids]
sql = GET_AUTHORS_BY_IDS_SQL.gsub('/*SLICE:ids*/?', slice_placeholders(ids))
stmt = client.prepare(sql)
begin
result = execute_statement(stmt, *query_params)
result.map do |row|
GetAuthorsByIdsRow.new(row[0], row[1], row[2])
end
ensure
stmt.close
end
end
end
def get_authors_by_ids_and_names(ids:, names:)
with_client('get_authors_by_ids_and_names') do |client|
query_params = [*ids, *names]
sql = GET_AUTHORS_BY_IDS_AND_NAMES_SQL.gsub('/*SLICE:ids*/?', slice_placeholders(ids))
sql = sql.gsub('/*SLICE:names*/?', slice_placeholders(names))
stmt = client.prepare(sql)
begin
result = execute_statement(stmt, *query_params)
result.map do |row|
GetAuthorsByIdsAndNamesRow.new(row[0], row[1], row[2])
end
ensure
stmt.close
end
end
end
# rubocop:disable Naming/MethodParameterName
def get_authors_by_mixed_placeholders(n:, ids:, id:, more:)
with_client('get_authors_by_mixed_placeholders') do |client|
query_params = [
n,
*ids,
n,
id,
*more
]
sql = GET_AUTHORS_BY_MIXED_PLACEHOLDERS_SQL.gsub('/*SLICE:ids*/?', slice_placeholders(ids))
sql = sql.gsub('/*SLICE:more*/?', slice_placeholders(more))
stmt = client.prepare(sql)
begin
result = execute_statement(stmt, *query_params)
result.map do |row|
GetAuthorsByMixedPlaceholdersRow.new(row[0], row[1], row[2])
end
ensure
stmt.close
end
end
end
# rubocop:enable Naming/MethodParameterName
# rubocop:disable Naming/MethodParameterName
def get_authors_by_repeated_named_and_positional(n:, other:, id:)
with_client('get_authors_by_repeated_named_and_positional') do |client|
query_params = [n, other, id, n]
stmt = client.prepare(GET_AUTHORS_BY_REPEATED_NAMED_AND_POSITIONAL_SQL)
begin
result = execute_statement(stmt, *query_params)
result.map do |row|
GetAuthorsByRepeatedNamedAndPositionalRow.new(row[0], row[1], row[2])
end
ensure
stmt.close
end
end
end
# rubocop:enable Naming/MethodParameterName
def get_authors_by_repeated_named_and_positional_batch(rows)
with_client('get_authors_by_repeated_named_and_positional_batch') do |client|
stmt = client.prepare(GET_AUTHORS_BY_REPEATED_NAMED_AND_POSITIONAL_BATCH_SQL)
begin
rows.map do |args|
query_params = [args.n, args.other, args.id, args.n]
result = execute_statement(stmt, *query_params)
row = result.first
row && GetAuthorsByRepeatedNamedAndPositionalBatchRow.new(row[0], row[1], row[2])
end
ensure
stmt.close
end
end
end
# Bulk insert: pass an Array of CopyAuthorsArgs.
def copy_authors(rows)
with_client('copy_authors') do |client|
atomically(client) do
rows.each_slice(499) do |batch|
sql = %(INSERT INTO "authors" ("name", "bio") VALUES #{::Array.new(batch.size, '(?, ?)').join(', ')})
client.execute(sql, batch.flat_map { |row| [row.name, row.bio] })
end
end
nil
end
end
def copy_authors_named(rows)
with_client('copy_authors_named') do |client|
atomically(client) do
rows.each_slice(499) do |batch|
sql = %(INSERT INTO "authors" ("name", "bio") VALUES #{::Array.new(batch.size, '(?, ?)').join(', ')})
client.execute(sql, batch.flat_map { |row| [row.name, row.bio] })
end
end
nil
end
end
def truncate_authors
with_client('truncate_authors') do |client|
stmt = client.prepare(TRUNCATE_AUTHORS_SQL)
begin
execute_statement(stmt)
nil
ensure
stmt.close
end
end
end
def create_book(name:, author_id:)
with_client('create_book') do |client|
query_params = [name, author_id]
stmt = client.prepare(CREATE_BOOK_SQL)
begin
result = execute_statement(stmt, *query_params)
row = result.first
row && row[0]
ensure
stmt.close
end
end
end
def list_all_authors_books
with_client('list_all_authors_books') do |client|
stmt = client.prepare(LIST_ALL_AUTHORS_BOOKS_SQL)
begin
result = execute_statement(stmt)
result.map do |row|
ListAllAuthorsBooksRow.new(
Author.new(row[0], row[1], row[2]),
Book.new(row[3], row[4], row[5], row[6])
)
end
ensure
stmt.close
end
end
end
def get_duplicate_authors
with_client('get_duplicate_authors') do |client|
stmt = client.prepare(GET_DUPLICATE_AUTHORS_SQL)
begin
result = execute_statement(stmt)
result.map do |row|
GetDuplicateAuthorsRow.new(Author.new(row[0], row[1], row[2]), Author.new(row[3], row[4], row[5]))
end
ensure
stmt.close
end
end
end
def get_authors_by_book_name(name:)
with_client('get_authors_by_book_name') do |client|
query_params = [name]
stmt = client.prepare(GET_AUTHORS_BY_BOOK_NAME_SQL)
begin
result = execute_statement(stmt, *query_params)
result.map do |row|
GetAuthorsByBookNameRow.new(row[0], row[1], row[2], Book.new(row[3], row[4], row[5], row[6]))
end
ensure
stmt.close
end
end
end
def create_author_result(name:, bio:)
with_client('create_author_result') do |client|
query_params = [name, bio]
stmt = client.prepare(CREATE_AUTHOR_RESULT_SQL)
begin
execute_statement(stmt, *query_params)
ExecResult.new(client.changes, client.last_insert_row_id)
ensure
stmt.close
end
end
end
def create_authors_batch(rows)
with_client('create_authors_batch') do |client|
stmt = client.prepare(CREATE_AUTHORS_BATCH_SQL)
begin
rows.each do |args|
query_params = [args.name, args.bio]
execute_statement(stmt, *query_params)
end
nil
ensure
stmt.close
end
end
end
def get_author_batch(rows)
with_client('get_author_batch') do |client|
stmt = client.prepare(GET_AUTHOR_BATCH_SQL)
begin
rows.map do |args|
query_params = [args.id]
result = execute_statement(stmt, *query_params)
row = result.first
row && GetAuthorBatchRow.new(row[0], row[1], row[2])
end
ensure
stmt.close
end
end
end
def list_authors_by_name_batch(rows)
with_client('list_authors_by_name_batch') do |client|
stmt = client.prepare(LIST_AUTHORS_BY_NAME_BATCH_SQL)
begin
rows.map do |args|
query_params = [args.name]
result = execute_statement(stmt, *query_params)
result.map do |row|
ListAuthorsByNameBatchRow.new(row[0], row[1], row[2])
end
end
ensure
stmt.close
end
end
end
def insert_declared_types(c_varchar:, c_decimal:, c_unsigned_big_int:, c_native:, c_double:, c_json:, c_uuid:)
with_client('insert_declared_types') do |client|
query_params = [
c_varchar,
c_decimal,
c_unsigned_big_int,
c_native,
c_double,
c_json,
c_uuid
]
stmt = client.prepare(INSERT_DECLARED_TYPES_SQL)
begin
execute_statement(stmt, *query_params)
nil
ensure
stmt.close
end
end
end
def get_declared_types
with_client('get_declared_types') do |client|
stmt = client.prepare(GET_DECLARED_TYPES_SQL)
begin
result = execute_statement(stmt)
row = result.first
row && GetDeclaredTypesRow.new(
row[0],
row[1],
row[2],
row[3],
row[4],
row[5]&.to_s,
row[6]&.to_s
)
ensure
stmt.close
end
end
end
# Like #get_declared_types, but raises NotFound when there is no row.
def get_declared_types!(...)
get_declared_types(...) || raise(NotFound, 'GetDeclaredTypes returned no row')
end
def truncate_declared_types
with_client('truncate_declared_types') do |client|
stmt = client.prepare(TRUNCATE_DECLARED_TYPES_SQL)
begin
execute_statement(stmt)
nil
ensure
stmt.close
end
end
end
def create_regression(order:, price:)
with_client('create_regression') do |client|
query_params = [order, price]
stmt = client.prepare(CREATE_REGRESSION_SQL)
begin
execute_statement(stmt, *query_params).to_a
nil
ensure
stmt.close
end
end
end
def update_regression_prices(price:)
with_client('update_regression_prices') do |client|
query_params = [price]
stmt = client.prepare(UPDATE_REGRESSION_PRICES_SQL)
begin
execute_statement(stmt, *query_params).to_a
client.changes
ensure
stmt.close
end
end
end
def copy_regressions(rows)
with_client('copy_regressions') do |client|
atomically(client) do
rows.each_slice(499) do |batch|
sql = %(INSERT INTO "regressions" ("order", "price") VALUES #{::Array.new(batch.size, '(?, ?)').join(', ')})
client.execute(sql, batch.flat_map { |row| [row.order, row.price] })
end
end
nil
end
end
def list_regressions
with_client('list_regressions') do |client|
stmt = client.prepare(LIST_REGRESSIONS_SQL)
begin
result = execute_statement(stmt)
result.map do |row|
ListRegressionsRow.new(row[0], row[1], row[2])
end
ensure
stmt.close
end
end
end