Repository navigation
Expand file tree
/
Copy pathquery_sql.rb
More file actions
1663 lines (1455 loc) · 53.8 KB
/
Copy pathquery_sql.rb
File metadata and controls
1663 lines (1455 loc) · 53.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 'mysql2'
require 'bigdecimal'
require 'date'
require 'tempfile'
require_relative 'connection'
require_relative 'models'
module Mysql2Codegen
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
UPDATE_AUTHOR_SQL = <<~'SQL'
UPDATE authors
SET bio = ?
WHERE id = ?
SQL
CREATE_AUTHOR_RETURN_ID_SQL = <<~'SQL'
INSERT INTO authors (
name, bio
) VALUES (
?, ?
)
SQL
DELETE_AUTHOR_SQL = <<~'SQL'
DELETE FROM authors
WHERE id = ?
SQL
INSERT_MYSQL_NUMERIC_TYPES_SQL = <<~'SQL'
INSERT INTO mysql_numeric_types (
id, c_bool, c_boolean, c_tinyint, c_smallint, c_mediumint, c_int, c_integer, c_bigint, c_bigint_unsigned, c_decimal, c_dec, c_numeric, c_fixed, c_decimal_wide, c_float, c_double, c_double_precision
) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
)
SQL
GET_MYSQL_NUMERIC_TYPES_SQL = <<~'SQL'
SELECT id, c_bool, c_boolean, c_tinyint, c_smallint, c_mediumint, c_int, c_integer, c_bigint, c_bigint_unsigned, c_serial, c_decimal, c_dec, c_numeric, c_fixed, c_decimal_wide, c_float, c_double, c_double_precision FROM mysql_numeric_types WHERE id = ?
SQL
class GetMysqlNumericTypesRow < ::Data.define(
:id,
:c_bool,
:c_boolean,
:c_tinyint,
:c_smallint,
:c_mediumint,
:c_int,
:c_integer,
:c_bigint,
:c_bigint_unsigned,
:c_serial,
:c_decimal,
:c_dec,
:c_numeric,
:c_fixed,
:c_decimal_wide,
:c_float,
:c_double,
:c_double_precision
)
end
INSERT_MYSQL_STRING_TYPES_SQL = <<~'SQL'
INSERT INTO mysql_string_types (
id, c_char, c_nchar, c_national_char, c_varchar, c_tinytext, c_text, c_mediumtext, c_longtext, c_json
) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?
)
SQL
GET_MYSQL_STRING_TYPES_SQL = <<~'SQL'
SELECT id, c_char, c_nchar, c_national_char, c_varchar, c_tinytext, c_text, c_mediumtext, c_longtext, c_json FROM mysql_string_types WHERE id = ?
SQL
class GetMysqlStringTypesRow < ::Data.define(
:id,
:c_char,
:c_nchar,
:c_national_char,
:c_varchar,
:c_tinytext,
:c_text,
:c_mediumtext,
:c_longtext,
:c_json
)
end
INSERT_MYSQL_DATETIME_TYPES_SQL = <<~'SQL'
INSERT INTO mysql_datetime_types (
id, c_date, c_time, c_datetime, c_datetime_6, c_timestamp, c_year
) VALUES (
?, ?, ?, ?, ?, ?, ?
)
SQL
GET_MYSQL_DATETIME_TYPES_SQL = <<~'SQL'
SELECT id, c_date, c_time, c_datetime, c_datetime_6, c_timestamp, c_year FROM mysql_datetime_types WHERE id = ?
SQL
# rubocop:disable Naming/VariableNumber
class GetMysqlDatetimeTypesRow < ::Data.define(
:id,
:c_date,
:c_time,
:c_datetime,
:c_datetime_6,
:c_timestamp,
:c_year
)
end
# rubocop:enable Naming/VariableNumber
# rubocop:disable Naming/VariableNumber
class CopyMysqlDatetimeTypesArgs < ::Data.define(:id, :c_datetime_6)
end
# rubocop:enable Naming/VariableNumber
INSERT_MYSQL_BINARY_TYPES_SQL = <<~'SQL'
INSERT INTO mysql_binary_types (
id, c_bit, c_bit_16, c_binary, c_varbinary, c_tinyblob, c_blob, c_mediumblob, c_longblob
) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?
)
SQL
GET_MYSQL_BINARY_TYPES_SQL = <<~'SQL'
SELECT id, c_bit, c_bit_16, c_binary, c_varbinary, c_tinyblob, c_blob, c_mediumblob, c_longblob FROM mysql_binary_types WHERE id = ?
SQL
# rubocop:disable Naming/VariableNumber
class GetMysqlBinaryTypesRow < ::Data.define(
:id,
:c_bit,
:c_bit_16,
:c_binary,
:c_varbinary,
:c_tinyblob,
:c_blob,
:c_mediumblob,
:c_longblob
)
end
# rubocop:enable Naming/VariableNumber
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
PAUSE_QUERY_SQL = <<~'SQL'
SELECT SLEEP(?)
SQL
class PauseQueryRow < ::Data.define(:sleep)
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
class CopyAuthorsArgs < ::Data.define(:name, :bio)
end
TRUNCATE_AUTHORS_SQL = <<~'SQL'
DELETE FROM authors
SQL
CREATE_BOOK_SQL = <<~'SQL'
INSERT INTO books (name, author_id) VALUES (?, ?)
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 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 authors1 JOIN authors 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 JOIN books ON authors.id = books.author_id
WHERE books.name = ?
SQL
class GetAuthorsByBookNameRow < ::Data.define(:id, :name, :bio, :book)
end
CREATE_EXTENDED_BIO_SQL = <<~'SQL'
INSERT INTO extended_bios (author_name, name, bio_type, author_type) VALUES (?, ?, ?, ?)
SQL
GET_FIRST_EXTENDED_BIO_BY_TYPE_SQL = <<~'SQL'
SELECT author_name, name, bio_type, author_type FROM extended_bios WHERE bio_type = ? LIMIT 1
SQL
class GetFirstExtendedBioByTypeRow < ::Data.define(:author_name, :name, :bio_type, :author_type)
end
TRUNCATE_EXTENDED_BIOS_SQL = <<~'SQL'
DELETE FROM extended_bios
SQL
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
COUNT_REGRESSIONS_BY_TEXT_SQL = <<~'SQL'
SELECT count(*) FROM regressions WHERE `order` = ? OR note = ?
SQL
class CountRegressionsByTextRow < ::Data.define(:count)
end
LIST_REGRESSIONS_BY_IDS_SQL = <<~'SQL'
SELECT id, `order`, note FROM regressions WHERE id IN (?, ?, ?) ORDER BY id
SQL
class ListRegressionsByIdsRow < ::Data.define(:id, :order, :note)
end
class CopyRegressionsArgs < ::Data.define(:order, :note)
end
class CopyRegressionRowsArgs < ::Data.define(:id, :order, :note, :payload)
end
SET_REGRESSION_STEP_SQL = <<~'SQL'
UPDATE regressions SET step = ? WHERE id = ?
SQL
GET_REGRESSION_STEP_SQL = <<~'SQL'
SELECT step FROM regressions WHERE id = ?
SQL
class GetRegressionStepRow < ::Data.define(:step)
end
LIST_REGRESSION_ROWS_SQL = <<~'SQL'
SELECT id, `order`, note, payload, code, doc, flags, amount FROM regressions ORDER BY id
SQL
class ListRegressionRowsRow < ::Data.define(
:id,
:order,
:note,
:payload,
:code,
:doc,
:flags,
:amount
)
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.id
SQL
class ListAuthorsWithOptionalBookRow < ::Data.define(:author, :book)
end
TRUNCATE_REGRESSIONS_SQL = <<~'SQL'
TRUNCATE TABLE regressions
SQL
class CopyRegressionTypesArgs < ::Data.define(
:id,
:code,
:doc,
:flags,
:amount
)
end
class CopyRegressionsIgnoreArgs < ::Data.define(:id, :code)
end
class CopyRegressionsReplaceArgs < ::Data.define(:id, :code)
end
CREATE_REGRESSIONS_BATCH_SQL = <<~'SQL'
INSERT INTO regressions (id, code, flags, amount) VALUES (?, ?, ?, ?)
SQL
class CreateRegressionsBatchArgs < ::Data.define(:id, :code, :flags, :amount)
end
COUNT_REGRESSIONS_BY_CODES_SQL = <<~'SQL'
SELECT count(*) AS matches FROM regressions WHERE code = ? OR code = ?
SQL
class CountRegressionsByCodesRow < ::Data.define(:matches)
end
# rubocop:disable Naming/VariableNumber
class CountRegressionsByCodesArgs < ::Data.define(:code, :code_2)
end
# rubocop:enable Naming/VariableNumber
FIND_AUTHORS_BY_EXACT_NAME_SQL = <<~'SQL'
SELECT id FROM authors WHERE name = ?
SQL
class FindAuthorsByExactNameRow < ::Data.define(:id)
end
GET_AUTHOR_WITH_QUESTION_MARKS_SQL = <<~'SQL'
SELECT id FROM authors AS `?`
WHERE name = ? AND '?' = '?' AND "?" = "?" /* ? */
ORDER BY id
SQL
class GetAuthorWithQuestionMarksRow < ::Data.define(:id)
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
class GetNameCaseRow < ::Data.define(
:id,
:class_,
:end,
:hash_,
:method_,
:count,
:camelcase,
:httpserver,
:initialize_
)
end
GET_HTTP_SERVER_SQL = <<~'SQL'
SELECT id, class, end, hash, method, count, camelcase, httpserver, initialize FROM name_cases WHERE id = ?
SQL
class GetHTTPServerRow < ::Data.define(
:id,
:class_,
:end,
:hash_,
:method_,
:count,
:camelcase,
:httpserver,
:initialize_
)
end
TRUNCATE_NAME_CASES_SQL = <<~'SQL'
TRUNCATE TABLE name_cases
SQL
class CopyMixedCaseCopiesArgs < ::Data.define(:id, :somevalue)
end
class CopyMixedCaseCopiesUnquotedArgs < ::Data.define(:somevalue, :id)
end
LIST_MIXED_CASE_COPIES_SQL = <<~'SQL'
SELECT id, somevalue FROM `MixedCaseCopies` ORDER BY `Id`
SQL
class ListMixedCaseCopiesRow < ::Data.define(:id, :somevalue)
end
TRUNCATE_MIXED_CASE_COPIES_SQL = <<~'SQL'
TRUNCATE TABLE `MixedCaseCopies`
SQL
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_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
TRUNCATE_EXCEPTIONS_SQL = <<~'SQL'
TRUNCATE TABLE exceptions
SQL
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({ database: 'app' }, size: 5, timeout: 5, logger: Logger.new($stdout))
# (pool_options go to ConnectionPool.new). To share an existing pool use QuerySql.new(pool).
def self.connect(mysql2_params, logger: nil, **pool_options)
new(::ConnectionPool.new(**pool_options) { ::Mysql2::Client.new(**mysql2_params) }, logger: logger)
end
# db: a ConnectionPool (or anything that responds to #with and yields a Mysql2::Client).
# 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.in_transaction
raise ::ArgumentError, 'isolation: cannot be set on a nested transaction' if isolation && !outermost
savepoint = outermost ? nil : "sqlc_sp_#{rand(0xffff_ffff).to_s(16)}"
level = "SET TRANSACTION ISOLATION LEVEL #{ISOLATION_LEVELS.fetch(isolation)}" if isolation
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
started = false
failed = false
begin
if outermost
client.in_transaction = true
client.query(level) if level
client.query('BEGIN')
else
client.query("SAVEPOINT #{savepoint}")
end
started = true
::Thread.handle_interrupt(::Object => :immediate) do
bound ? yield(bound_to(bound)) : @db.unlocked { yield self }
end
rescue ::Exception => e # rubocop:disable Lint/RescueException
failed = true
bound&.close
begin
client.query(rollback) if (started || outermost) && !client.rolled_back_by
rescue ::Mysql2::Error
# a deadlock / lock wait timeout already rolled back the transaction: its savepoints are gone;
# an interrupted query closed the connection: the server rolls back
raise unless e.is_a?(::Mysql2::Error) || client.closed?
end
raise
ensure
bound&.close
begin
unless failed
if ::Thread.current.status == 'aborting' && client.query_running?
# Thread#kill interrupted a query: the client still waits for its result and cannot send
# ROLLBACK. Closing it makes the server roll back; #with_client discards it.
client.close
elsif client.rolled_back_by
# the server already rolled the whole transaction back (its savepoints too): COMMIT would only
# end the statements run since, so raise instead of reporting a commit
raise client.rolled_back_error if ::Thread.current.status != 'aborting'
else
commit = outermost ? 'COMMIT' : "RELEASE SAVEPOINT #{savepoint}"
begin
client.query(::Thread.current.status == 'aborting' ? rollback : commit)
rescue ::Exception # rubocop:disable Lint/RescueException
# COMMIT did not run: roll back instead of leaving the transaction open (a closed client is
# discarded and the server rolls back)
begin
client.query('ROLLBACK') if outermost && !client.closed?
rescue ::Mysql2::Error
nil
end
raise
end
end
end
ensure
if outermost
client.in_transaction = false
client.rolled_back_by = nil
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]
result = client.query(bind_params(client, GET_AUTHOR_SQL, query_params), as: :array, cast: true, cast_booleans: false)
row = result.first
row && GetAuthorRow.new(row[0], row[1], row[2])
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 = client.query(bind_params(client, LIST_AUTHORS_SQL, []), as: :array, cast: true, cast_booleans: false)
result.map do |row|
ListAuthorsRow.new(row[0], row[1], row[2])
end
end
end
def create_author(name:, bio:)
with_client('create_author') do |client|
query_params = [name, bio]
client.query(bind_params(client, CREATE_AUTHOR_SQL, query_params))
nil
end
end
def update_author(bio:, id:)
with_client('update_author') do |client|
query_params = [bio, id]
client.query(bind_params(client, UPDATE_AUTHOR_SQL, query_params))
nil
end
end
def create_author_return_id(name:, bio:)
with_client('create_author_return_id') do |client|
query_params = [name, bio]
client.query(bind_params(client, CREATE_AUTHOR_RETURN_ID_SQL, query_params))
client.last_id
end
end
def delete_author(id:)
with_client('delete_author') do |client|
query_params = [id]
client.query(bind_params(client, DELETE_AUTHOR_SQL, query_params))
nil
end
end
def insert_mysql_numeric_types(id:, c_bool:, c_boolean:, c_tinyint:, c_smallint:, c_mediumint:, c_int:, c_integer:, c_bigint:, c_bigint_unsigned:, c_decimal:, c_dec:, c_numeric:, c_fixed:, c_decimal_wide:, c_float:, c_double:, c_double_precision:)
with_client('insert_mysql_numeric_types') do |client|
query_params = [
id,
c_bool,
c_boolean,
c_tinyint,
c_smallint,
c_mediumint,
c_int,
c_integer,
c_bigint,
c_bigint_unsigned,
c_decimal,
c_dec,
c_numeric,
c_fixed,
c_decimal_wide,
c_float,
c_double,
c_double_precision
]
client.query(bind_params(client, INSERT_MYSQL_NUMERIC_TYPES_SQL, query_params))
nil
end
end
def get_mysql_numeric_types(id:)
with_client('get_mysql_numeric_types') do |client|
query_params = [id]
result = client.query(bind_params(client, GET_MYSQL_NUMERIC_TYPES_SQL, query_params), as: :array, cast: true, cast_booleans: false)
row = result.first
row && GetMysqlNumericTypesRow.new(
row[0],
row[1],
row[2],
row[3],
row[4],
row[5],
row[6],
row[7],
row[8],
row[9],
row[10],
row[11],
row[12],
row[13],
row[14],
row[15],
row[16],
row[17],
row[18]
)
end
end
# Like #get_mysql_numeric_types, but raises NotFound when there is no row.
def get_mysql_numeric_types!(...)
get_mysql_numeric_types(...) || raise(NotFound, 'GetMysqlNumericTypes returned no row')
end
def insert_mysql_string_types(id:, c_char:, c_nchar:, c_national_char:, c_varchar:, c_tinytext:, c_text:, c_mediumtext:, c_longtext:, c_json:)
with_client('insert_mysql_string_types') do |client|
query_params = [
id,
c_char,
c_nchar,
c_national_char,
c_varchar,
c_tinytext,
c_text,
c_mediumtext,
c_longtext,
c_json
]
client.query(bind_params(client, INSERT_MYSQL_STRING_TYPES_SQL, query_params))
nil
end
end
def get_mysql_string_types(id:)
with_client('get_mysql_string_types') do |client|
query_params = [id]
result = client.query(bind_params(client, GET_MYSQL_STRING_TYPES_SQL, query_params), as: :array, cast: true, cast_booleans: false)
row = result.first
row && GetMysqlStringTypesRow.new(
row[0],
row[1],
row[2],
row[3],
row[4],
row[5],
row[6],
row[7],
row[8],
row[9]
)
end
end
# Like #get_mysql_string_types, but raises NotFound when there is no row.
def get_mysql_string_types!(...)
get_mysql_string_types(...) || raise(NotFound, 'GetMysqlStringTypes returned no row')
end
def insert_mysql_datetime_types(id:, c_date:, c_time:, c_datetime:, c_datetime_6:, c_timestamp:, c_year:)
with_client('insert_mysql_datetime_types') do |client|
query_params = [
id,
c_date,
c_time,
c_datetime,
c_datetime_6,
c_timestamp,
c_year
]
client.query(bind_params(client, INSERT_MYSQL_DATETIME_TYPES_SQL, query_params))
nil
end
end
def get_mysql_datetime_types(id:)
with_client('get_mysql_datetime_types') do |client|
query_params = [id]
result = client.query(bind_params(client, GET_MYSQL_DATETIME_TYPES_SQL, query_params), as: :array, cast: true, cast_booleans: false)
row = result.first
row && GetMysqlDatetimeTypesRow.new(
row[0],
row[1],
row[2],
row[3],
row[4],
row[5],
row[6]
)
end
end
# Like #get_mysql_datetime_types, but raises NotFound when there is no row.
def get_mysql_datetime_types!(...)
get_mysql_datetime_types(...) || raise(NotFound, 'GetMysqlDatetimeTypes returned no row')
end
def copy_mysql_datetime_types(rows)
with_client('copy_mysql_datetime_types') do |client|
::Tempfile.create(['copy_mysql_datetime_types', '.csv']) do |file|
rows.each do |row|
file.write(csv_line(client, [row.id, row.c_datetime_6]))
end
file.flush
load_data(client, "LOAD DATA LOCAL INFILE '#{client.escape(file.path)}' INTO TABLE `mysql_datetime_types` CHARACTER SET binary FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '\\\\' LINES TERMINATED BY '\\n' (`id`, `c_datetime_6`)") if file.pos.positive?
end
nil
end
end
def insert_mysql_binary_types(id:, c_bit:, c_bit_16:, c_binary:, c_varbinary:, c_tinyblob:, c_blob:, c_mediumblob:, c_longblob:)
with_client('insert_mysql_binary_types') do |client|
query_params = [
id,
c_bit,
c_bit_16,
c_binary,
c_varbinary,
c_tinyblob,
c_blob,
c_mediumblob,
c_longblob
]
client.query(bind_params(client, INSERT_MYSQL_BINARY_TYPES_SQL, query_params))
nil
end
end
def get_mysql_binary_types(id:)
with_client('get_mysql_binary_types') do |client|
query_params = [id]
result = client.query(bind_params(client, GET_MYSQL_BINARY_TYPES_SQL, query_params), as: :array, cast: true, cast_booleans: false)
row = result.first
row && GetMysqlBinaryTypesRow.new(
row[0],
row[1],
row[2],
row[3],
row[4],
row[5],
row[6],
row[7],
row[8]
)
end
end
# Like #get_mysql_binary_types, but raises NotFound when there is no row.
def get_mysql_binary_types!(...)
get_mysql_binary_types(...) || raise(NotFound, 'GetMysqlBinaryTypes returned no row')
end
def list_authors_paged(limit:, offset:)
with_client('list_authors_paged') do |client|
query_params = [limit, offset]
result = client.query(bind_params(client, LIST_AUTHORS_PAGED_SQL, query_params), as: :array, cast: true, cast_booleans: false)
result.map do |row|
ListAuthorsPagedRow.new(row[0], row[1], row[2])
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]
result = client.query(bind_params(client, GET_AUTHOR_BY_NAME_PATTERN_SQL, query_params), as: :array, cast: true, cast_booleans: false)
result.map do |row|
GetAuthorByNamePatternRow.new(row[0], row[1], row[2])
end
end
end
def get_authors_by_optional_name(limit:, name_filter: nil)
with_client('get_authors_by_optional_name') do |client|
query_params = [name_filter, name_filter, limit]
result = client.query(bind_params(client, GET_AUTHORS_BY_OPTIONAL_NAME_SQL, query_params), as: :array, cast: true, cast_booleans: false)
result.map do |row|
GetAuthorsByOptionalNameRow.new(row[0], row[1], row[2])
end
end
end
def pause_query(seconds:)
with_client('pause_query') do |client|
query_params = [seconds]
client.query(bind_params(client, PAUSE_QUERY_SQL, query_params), as: :array, cast: true, cast_booleans: false)
nil
end
end
# Sets the bio of every author that has one and returns how many were changed.
def update_author_bios(bio: nil)
with_client('update_author_bios') do |client|
query_params = [bio]
client.query(bind_params(client, UPDATE_AUTHOR_BIOS_SQL, query_params))
client.affected_rows
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))
result = client.query(bind_params(client, sql, query_params), as: :array, cast: true, cast_booleans: false)
result.map do |row|
GetAuthorsByIdsRow.new(row[0], row[1], row[2])
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))
result = client.query(bind_params(client, sql, query_params), as: :array, cast: true, cast_booleans: false)
result.map do |row|
GetAuthorsByIdsAndNamesRow.new(row[0], row[1], row[2])
end
end
end
# Bulk insert: pass an Array of CopyAuthorsArgs.
def copy_authors(rows)
with_client('copy_authors') do |client|
::Tempfile.create(['copy_authors', '.csv']) do |file|
rows.each do |row|
file.write(csv_line(client, [row.name, row.bio]))
end
file.flush
load_data(client, "LOAD DATA LOCAL INFILE '#{client.escape(file.path)}' INTO TABLE `authors` CHARACTER SET binary FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '\\\\' LINES TERMINATED BY '\\n' (`name`, `bio`)") if file.pos.positive?
end
nil
end
end
def truncate_authors
with_client('truncate_authors') do |client|
client.query(bind_params(client, TRUNCATE_AUTHORS_SQL, []))
nil
end
end
def create_book(name:, author_id:)
with_client('create_book') do |client|
query_params = [name, author_id]
client.query(bind_params(client, CREATE_BOOK_SQL, query_params))
client.last_id
end
end
def list_all_authors_books
with_client('list_all_authors_books') do |client|
result = client.query(bind_params(client, LIST_ALL_AUTHORS_BOOKS_SQL, []), as: :array, cast: true, cast_booleans: false)
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
end
end
def get_duplicate_authors