quill-sql 0.1.8 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/lib/db/mysql.rb ADDED
@@ -0,0 +1,934 @@
1
+ require 'date'
2
+ require 'json'
3
+ require 'set'
4
+ require 'uri'
5
+
6
+ # MySQL driver, mirroring node-sdk/src/db/Mysql.ts.
7
+ #
8
+ # Node uses mysql2 and then round-trips every row through
9
+ # JSON.parse(JSON.stringify(row)). Cells are decoded the same way here:
10
+ # integers and floats are numbers, DECIMAL stays text, TIME stays text,
11
+ # JSON is parsed, BIT and binary-charset columns become
12
+ # { "type": "Buffer", "data": [...] }, and DATE/DATETIME/TIMESTAMP are
13
+ # local civil times rendered as UTC ISO strings.
14
+ #
15
+ # Field dataTypeIDs use Node's numeric map, including the entries whose
16
+ # comments don't match real MySQL codes (245 is JSON and 246 is NEWDECIMAL,
17
+ # and both land on bytea). `field.type || 1043` treats DECIMAL code 0 as
18
+ # missing, so that column's dataTypeID is varchar while the cell is still
19
+ # a decimal string. Information-schema DATA_TYPE strings use the other map.
20
+ #
21
+ # The mysql2 gem is required only when a connection is opened, so the rest
22
+ # of the SDK loads without it.
23
+ module MysqlHelper
24
+ MYSQL_CONNECTION_LIMIT = 24
25
+ MYSQL_DEFAULT_PORT = 3306
26
+ BINARY_CHARSET = 63
27
+ # mysql2 names every TINY/MEDIUM/LONG_BLOB-coded column "<x>blob" even when
28
+ # its charset is text (MySQL 8 sends LONGTEXT and the information_schema
29
+ # string columns that way), so for those the cell's encoding decides.
30
+ BLOB_CODED = :blob_coded
31
+ DEFAULT_OID = 1043
32
+ # Pieces of the UTC ISO string. Joining these beats formatting each integer.
33
+ ISO_YEAR = (0..9999).map { |number| format('%04d', number) }.freeze
34
+ ISO_2 = (0..59).map { |number| format('%02d', number) }.freeze
35
+ ISO_3 = (0..999).map { |number| format('%03d', number) }.freeze
36
+ MONTH_DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31].freeze
37
+ LOCAL_OFFSETS = {}
38
+ LOCAL_OFFSETS_LOCK = Mutex.new
39
+ DECODER_CACHE = {}
40
+
41
+ # MySQL protocol column type codes (mysql2 `Types`).
42
+ DECIMAL = 0
43
+ TINY = 1
44
+ SHORT = 2
45
+ LONG = 3
46
+ FLOAT = 4
47
+ DOUBLE = 5
48
+ NULL = 6
49
+ TIMESTAMP = 7
50
+ LONGLONG = 8
51
+ INT24 = 9
52
+ DATE = 10
53
+ TIME = 11
54
+ DATETIME = 12
55
+ YEAR = 13
56
+ NEWDATE = 14
57
+ VARCHAR = 15
58
+ BIT = 16
59
+ JSON_TYPE = 245
60
+ NEWDECIMAL = 246
61
+ ENUM = 247
62
+ SET_TYPE = 248
63
+ TINY_BLOB = 249
64
+ MEDIUM_BLOB = 250
65
+ LONG_BLOB = 251
66
+ BLOB = 252
67
+ VAR_STRING = 253
68
+ STRING = 254
69
+ GEOMETRY = 255
70
+
71
+ INTEGER_TYPES = [TINY, SHORT, LONG, LONGLONG, INT24, YEAR].freeze
72
+ FLOAT_TYPES = [FLOAT, DOUBLE].freeze
73
+ DECIMAL_TYPES = [DECIMAL, NEWDECIMAL].freeze
74
+ DATETIME_TYPES = [TIMESTAMP, DATETIME].freeze
75
+
76
+ # Node's mysqlDataTypeIdToPostgresType, verbatim.
77
+ MYSQL_DATATYPE_ID_MAP = {
78
+ 0 => 23, # DECIMAL
79
+ 1 => 23, # TINY
80
+ 2 => 23, # SHORT
81
+ 3 => 23, # LONG
82
+ 8 => 23, # LONGLONG
83
+ 9 => 23, # INT24
84
+ 13 => 23, # YEAR
85
+ 4 => 701, # FLOAT
86
+ 5 => 701, # DOUBLE
87
+ 7 => 1114, # TIMESTAMP
88
+ 12 => 1114, # DATETIME
89
+ 10 => 1082, # DATE
90
+ 242 => 1082, # NEWDATE
91
+ 15 => 1043, # VARCHAR
92
+ 25 => 1043, # VAR_STRING
93
+ 250 => 1043, # STRING
94
+ 254 => 1043, # ENUM
95
+ 255 => 1043, # SET
96
+ 16 => 17, # BIT
97
+ 245 => 17, # TINY_BLOB
98
+ 246 => 17, # MEDIUM_BLOB
99
+ 247 => 17, # LONG_BLOB
100
+ 248 => 17, # BLOB
101
+ 251 => 17 # GEOMETRY
102
+ }.freeze
103
+
104
+ # Node's mysqlTextDataTypeToPostgresOID (information_schema DATA_TYPE).
105
+ MYSQL_TEXT_DATATYPE_MAP = {
106
+ 'bigint' => 20,
107
+ 'tinyint' => 21,
108
+ 'smallint' => 21,
109
+ 'int' => 23,
110
+ 'float' => 701,
111
+ 'double' => 701,
112
+ 'varchar' => 1043,
113
+ 'char' => 1042,
114
+ 'timestamp' => 1114,
115
+ 'date' => 1082,
116
+ 'datetime' => 1114,
117
+ 'time' => 1083,
118
+ 'year' => 23,
119
+ 'binary' => 17,
120
+ 'blob' => 17,
121
+ 'text' => 25,
122
+ 'json' => 114
123
+ }.freeze
124
+
125
+ # CR_CONNECTION_ERROR, CR_CONN_HOST_ERROR, CR_SERVER_GONE_ERROR,
126
+ # CR_SERVER_LOST, CR_SERVER_LOST_EXTENDED. A dead socket is not returned
127
+ # to the pool.
128
+ CONNECTION_ERROR_NUMBERS = [2002, 2003, 2006, 2013, 2055].freeze
129
+
130
+ # Raised for a lost connection so the pool can drop it. mysql2's own
131
+ # Mysql2::Error is recognized by error number when the gem is loaded.
132
+ class MysqlConnectionError < RuntimeError; end
133
+
134
+ # Lazy, thread-safe pool with mysql2's defaults: connectionLimit 24,
135
+ # waitForConnections, queueLimit 0. `close` drops idle connections and
136
+ # further use raises "Pool is closed."
137
+ class MysqlPool
138
+ attr_reader :in_use, :idle, :limit
139
+
140
+ def initialize(config = nil, connection_limit = MYSQL_CONNECTION_LIMIT)
141
+ @config = config || {}
142
+ @limit = connection_limit
143
+ @idle = []
144
+ @in_use = 0
145
+ @mutex = Mutex.new
146
+ @condition = ConditionVariable.new
147
+ @closed = false
148
+ end
149
+
150
+ def closed?
151
+ @closed
152
+ end
153
+
154
+ def acquire
155
+ @mutex.synchronize do
156
+ loop do
157
+ raise 'Pool is closed.' if @closed
158
+
159
+ connection = @idle.pop
160
+ if connection
161
+ @in_use += 1
162
+ return connection
163
+ end
164
+ if @in_use < @limit
165
+ @in_use += 1
166
+ break
167
+ end
168
+ @condition.wait(@mutex)
169
+ end
170
+ end
171
+ begin
172
+ connect_client
173
+ rescue StandardError
174
+ @mutex.synchronize do
175
+ @in_use -= 1
176
+ @condition.signal
177
+ end
178
+ raise
179
+ end
180
+ end
181
+
182
+ def release(connection, discard: false)
183
+ @mutex.synchronize do
184
+ @in_use -= 1
185
+ if @closed || discard
186
+ MysqlHelper.close_quietly(connection)
187
+ else
188
+ @idle << connection
189
+ end
190
+ @condition.signal
191
+ end
192
+ end
193
+
194
+ def close
195
+ idle = @mutex.synchronize do
196
+ @closed = true
197
+ idle = @idle
198
+ @idle = []
199
+ @condition.broadcast
200
+ idle
201
+ end
202
+ idle.each { |connection| MysqlHelper.close_quietly(connection) }
203
+ end
204
+
205
+ def connect_client
206
+ config = @config || {}
207
+ host = MysqlHelper.config_value(config, :host)
208
+ host = 'localhost' if host.nil? || host.to_s.empty?
209
+ kwargs = {
210
+ host: host,
211
+ username: MysqlHelper.config_value(config, :user).to_s,
212
+ password: MysqlHelper.config_value(config, :password).to_s,
213
+ port: (MysqlHelper.config_value(config, :port) || MYSQL_DEFAULT_PORT).to_i
214
+ }
215
+ database = MysqlHelper.config_value(config, :database)
216
+ kwargs[:database] = database unless database.nil? || database.to_s.empty?
217
+ ssl_mode = MysqlHelper.mysql_ssl_mode(MysqlHelper.config_value(config, :ssl))
218
+ kwargs[:ssl_mode] = ssl_mode unless ssl_mode.nil?
219
+ MysqlHelper.mysql2_client_class.new(**kwargs)
220
+ end
221
+ end
222
+
223
+ class << self
224
+ def mysql_data_type_id_to_postgres_type(type_code)
225
+ MYSQL_DATATYPE_ID_MAP[type_code] || DEFAULT_OID
226
+ end
227
+
228
+ def mysql_text_data_type_to_postgres_oid(data_type)
229
+ MYSQL_TEXT_DATATYPE_MAP[data_type] || DEFAULT_OID
230
+ end
231
+
232
+ # `mysql://user:password@host:3306/database` -> pool options.
233
+ # Credentials are percent-decoded like Node's url.parse. A missing port
234
+ # is 3306; Ruby's URI does not invent one for the mysql scheme.
235
+ # Node's mysqlSsl. The mysql2 gem does not read sslmode.
236
+ # Omitted and no-verify keep TLS without certificate checks. disable is
237
+ # plaintext. Anything else checks the certificate, like mysql2's {}.
238
+ def mysql_ssl(query)
239
+ sslmode = URI.decode_www_form(query.to_s).to_h['sslmode']
240
+ return { rejectUnauthorized: false } if sslmode.nil? || sslmode.empty?
241
+ return false if sslmode == 'disable'
242
+ return { rejectUnauthorized: false } if sslmode == 'no-verify'
243
+
244
+ {}
245
+ end
246
+
247
+ # :required is TLS without certificate checks. :verify_identity checks
248
+ # the certificate and hostname. nil leaves the client library default.
249
+ def mysql_ssl_mode(ssl)
250
+ return nil if ssl.nil?
251
+ return :disabled if ssl == false
252
+ return :verify_identity unless ssl.is_a?(Hash)
253
+
254
+ reject = if ssl.key?(:rejectUnauthorized)
255
+ ssl[:rejectUnauthorized]
256
+ else
257
+ ssl['rejectUnauthorized']
258
+ end
259
+ return :required if reject == false
260
+
261
+ :verify_identity
262
+ end
263
+
264
+ def format_mysql_config(connection_string)
265
+ parsed = URI.parse(connection_string)
266
+ path = parsed.path.to_s
267
+ database = path.start_with?('/') ? path[1..].to_s : path
268
+ {
269
+ host: parsed.host || '',
270
+ user: percent_decode(parsed.user),
271
+ password: percent_decode(parsed.password),
272
+ database: database,
273
+ port: parsed.port || MYSQL_DEFAULT_PORT,
274
+ ssl: mysql_ssl(parsed.query)
275
+ }
276
+ end
277
+
278
+ def connect_to_mysql(config)
279
+ MysqlPool.new(config)
280
+ end
281
+
282
+ def disconnect_from_mysql(pool)
283
+ return if pool.nil?
284
+
285
+ pool.close if pool.respond_to?(:close)
286
+ end
287
+
288
+ def mysql2_client_class
289
+ require 'mysql2'
290
+ Mysql2::Client
291
+ end
292
+
293
+ def connection_error?(error)
294
+ return true if error.is_a?(MysqlConnectionError)
295
+ return false unless error.class.name == 'Mysql2::Error'
296
+
297
+ number = error.respond_to?(:error_number) ? error.error_number : nil
298
+ CONNECTION_ERROR_NUMBERS.include?(number)
299
+ end
300
+
301
+ def close_quietly(connection)
302
+ connection.close if connection.respond_to?(:close)
303
+ rescue StandardError
304
+ nil
305
+ end
306
+
307
+ def config_value(config, key)
308
+ return nil if config.nil?
309
+
310
+ config[key].nil? ? config[key.to_s] : config[key]
311
+ end
312
+
313
+ # mysql2's Result#field_types is a SQL type name ("int(11)",
314
+ # "decimal(10,2)"), not the protocol code Node reads from field.type.
315
+ # These are the codes the JavaScript client reports for those names.
316
+ def type_name_to_code(type_name)
317
+ case type_name.to_s.downcase.split('(').first
318
+ when 'null' then NULL
319
+ when 'tinyint' then TINY
320
+ when 'smallint' then SHORT
321
+ when 'year' then YEAR
322
+ when 'mediumint' then INT24
323
+ when 'int', 'integer' then LONG
324
+ when 'bigint' then LONGLONG
325
+ when 'float' then FLOAT
326
+ when 'double' then DOUBLE
327
+ when 'time' then TIME
328
+ when 'date' then DATE
329
+ when 'datetime' then DATETIME
330
+ when 'timestamp' then TIMESTAMP
331
+ when 'decimal', 'numeric' then NEWDECIMAL
332
+ when 'json' then JSON_TYPE
333
+ when 'enum' then ENUM
334
+ when 'set' then SET_TYPE
335
+ when 'bit' then BIT
336
+ when 'binary', 'char' then STRING
337
+ when 'varbinary', 'varchar' then VAR_STRING
338
+ when 'tinyblob' then TINY_BLOB
339
+ when 'mediumblob' then MEDIUM_BLOB
340
+ when 'longblob' then LONG_BLOB
341
+ when 'blob', 'tinytext', 'text', 'mediumtext', 'longtext' then BLOB
342
+ when 'geometry' then GEOMETRY
343
+ end
344
+ end
345
+
346
+ def charset_for_type_name(type_name)
347
+ base = type_name.to_s.downcase.split('(').first
348
+ return BINARY_CHARSET if %w[binary varbinary geometry bit].include?(base)
349
+ return BLOB_CODED if %w[tinyblob blob mediumblob longblob].include?(base)
350
+
351
+ nil
352
+ end
353
+
354
+ def mysql2_value(value, type_code, charset = nil)
355
+ return nil if value.nil?
356
+
357
+ decoder_for(type_code, charset).call(value)
358
+ end
359
+
360
+ def run_query_mysql(sql, pool)
361
+ connection = pool.acquire
362
+ discard = false
363
+ begin
364
+ result = execute_query(connection, sql)
365
+ rescue StandardError => e
366
+ discard = connection_error?(e)
367
+ raise
368
+ ensure
369
+ pool.release(connection, discard: discard)
370
+ end
371
+ shape_query_result(result)
372
+ end
373
+
374
+ def get_schemas_mysql(pool)
375
+ sql = <<~SQL
376
+ SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA
377
+ WHERE schema_name != 'information_schema'
378
+ AND schema_name != 'performance_schema'
379
+ and schema_name != 'sys';
380
+ SQL
381
+ results = run_query_mysql(sql, pool)
382
+ results[:rows].map { |row| row_value(row, 'SCHEMA_NAME') }
383
+ end
384
+
385
+ def get_tables_by_schema_mysql(pool, schema_names)
386
+ schema_names.flat_map do |schema|
387
+ sql = "SELECT TABLE_NAME, TABLE_SCHEMA FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '#{schema}'"
388
+ results = run_query_mysql(sql, pool)
389
+ results[:rows].map do |row|
390
+ {
391
+ tableName: row_value(row, 'TABLE_NAME'),
392
+ schemaName: row_value(row, 'TABLE_SCHEMA')
393
+ }
394
+ end
395
+ end
396
+ end
397
+
398
+ def get_columns_by_table_mysql(pool, schema_name, table_name)
399
+ sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '#{schema_name}' AND TABLE_NAME = '#{table_name}'"
400
+ results = run_query_mysql(sql, pool)
401
+ results[:rows].map { |row| row_value(row, 'COLUMN_NAME') }
402
+ end
403
+
404
+ def get_foreign_keys_mysql(pool, schema_name, table_name, primary_key)
405
+ depluralized = mysql_depluralize(table_name)
406
+ capitalized = mysql_capitalize(primary_key)
407
+ sql = <<~SQL
408
+ SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
409
+ WHERE TABLE_SCHEMA = '#{schema_name}'
410
+ and table_name != '#{table_name}'
411
+ and (column_name = '#{primary_key}'
412
+ or column_name = '#{depluralized}\\_#{primary_key}'
413
+ or column_name = '#{depluralized}#{capitalized}' )
414
+ SQL
415
+ foreign_keys = foreign_key_names(run_query_mysql(sql, pool))
416
+ if foreign_keys.empty?
417
+ sql = <<~SQL
418
+ SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
419
+ WHERE TABLE_SCHEMA = '#{schema_name}'
420
+ and table_name != '#{table_name}'
421
+ and (column_name like '#{depluralized}%'
422
+ or column_name like '%\\_id'
423
+ or column_name like '%Id'
424
+ or column_name like '%\\_#{primary_key}'
425
+ or column_name like '%#{capitalized}')
426
+ SQL
427
+ foreign_keys = foreign_key_names(run_query_mysql(sql, pool), filter_ids: false)
428
+ end
429
+ foreign_keys
430
+ end
431
+
432
+ def get_schema_column_info_mysql(pool, _schema_name, table_names)
433
+ table_names.map do |table|
434
+ table_schema, table_name = table_identity(table)
435
+ sql = <<~SQL
436
+ SELECT COLUMN_NAME as columnName,
437
+ DATA_TYPE as dataType FROM INFORMATION_SCHEMA.COLUMNS
438
+ WHERE TABLE_SCHEMA = '#{table_schema}'
439
+ AND TABLE_NAME = '#{table_name}'
440
+ SQL
441
+ results = run_query_mysql(sql, pool)
442
+ {
443
+ tableName: "#{table_schema}.#{table_name}",
444
+ displayName: "#{table_schema}.#{table_name}",
445
+ columns: results[:rows].map do |row|
446
+ data_type = row_value(row, 'dataType')
447
+ column_name = row_value(row, 'columnName')
448
+ {
449
+ columnName: column_name,
450
+ displayName: column_name,
451
+ dataTypeID: mysql_text_data_type_to_postgres_oid(data_type),
452
+ fieldType: data_type
453
+ }
454
+ end
455
+ }
456
+ end
457
+ end
458
+
459
+ def shape_query_result(result)
460
+ description, rows = extract_description_and_rows(result)
461
+ return { fields: [], rows: [] } if description.nil?
462
+
463
+ fields = []
464
+ names = []
465
+ decoders = []
466
+ description.each do |column|
467
+ name, type_code, charset = column_parts(column)
468
+ reported = type_code.nil? || type_code == 0 ? DEFAULT_OID : type_code
469
+ fields << {
470
+ name: name,
471
+ dataTypeID: mysql_data_type_id_to_postgres_type(reported)
472
+ }
473
+ names << name
474
+ decoders << decoder_for(type_code, charset)
475
+ end
476
+ { fields: fields, rows: build_rows(rows, names, decoders) }
477
+ end
478
+
479
+ private
480
+
481
+ def execute_query(connection, sql)
482
+ if connection.class.name == 'Mysql2::Client'
483
+ connection.query(sql, cast: false, symbolize_keys: false, as: :hash)
484
+ else
485
+ connection.query(sql)
486
+ end
487
+ end
488
+
489
+ def extract_description_and_rows(result)
490
+ return [nil, []] if result.nil?
491
+ # mysql2::Result exposes field_types (SQL names) rather than protocol
492
+ # codes. A description wins when a test double provides both.
493
+ if result.respond_to?(:field_types) && !result.respond_to?(:description)
494
+ return mysql2_description_and_rows(result)
495
+ end
496
+ return [nil, []] unless result.respond_to?(:description)
497
+ return [nil, []] if result.description.nil?
498
+
499
+ rows = result.respond_to?(:rows) ? result.rows : []
500
+ [result.description, rows || []]
501
+ end
502
+
503
+ def mysql2_description_and_rows(result)
504
+ names = result.fields || []
505
+ type_names = result.field_types || []
506
+ description = names.each_with_index.map do |name, index|
507
+ type_name = type_names[index].to_s
508
+ [name, type_name_to_code(type_name), charset_for_type_name(type_name)]
509
+ end
510
+ rows = []
511
+ result.each { |row| rows << row }
512
+ [description, rows]
513
+ end
514
+
515
+ def column_parts(column)
516
+ if column.is_a?(Array)
517
+ charset = column.length > 8 ? column[8] : column[2]
518
+ [column[0], column[1], charset]
519
+ else
520
+ name = column[:name] || column['name']
521
+ type_code = column.key?(:type_code) ? column[:type_code] : (column['type_code'] || column[:type] || column['type'])
522
+ charset = column.key?(:charset) ? column[:charset] : column['charset']
523
+ [name, type_code, charset]
524
+ end
525
+ end
526
+
527
+ def decoder_for(type_code, charset)
528
+ DECODER_CACHE[[type_code, charset]] ||= resolve_decoder(type_code, charset)
529
+ end
530
+
531
+ def resolve_decoder(type_code, charset)
532
+ return method(:decode_int) if INTEGER_TYPES.include?(type_code)
533
+ return method(:decode_float) if FLOAT_TYPES.include?(type_code)
534
+ return method(:decode_decimal) if DECIMAL_TYPES.include?(type_code)
535
+ return method(:decode_date_value) if type_code == DATE
536
+ return method(:decode_datetime_value) if DATETIME_TYPES.include?(type_code)
537
+ return method(:decode_time) if type_code == TIME
538
+ return method(:decode_json) if type_code == JSON_TYPE
539
+ return method(:decode_bit) if type_code == BIT
540
+ return method(:decode_null) if type_code == NULL
541
+ return method(:decode_blob_coded) if charset == BLOB_CODED
542
+ return method(:decode_binary) if charset == BINARY_CHARSET
543
+
544
+ method(:decode_text)
545
+ end
546
+
547
+ def build_rows(rows, names, decoders)
548
+ return [] if rows.nil?
549
+
550
+ rows.map do |row|
551
+ built = {}
552
+ names.each_with_index do |name, index|
553
+ cell = if row.is_a?(Hash)
554
+ row_cell(row, name)
555
+ else
556
+ row[index]
557
+ end
558
+ built[name.to_s] = decoders[index].call(cell)
559
+ end
560
+ built
561
+ end
562
+ end
563
+
564
+ def row_cell(row, name)
565
+ return row[name] if row.key?(name)
566
+
567
+ symbol = name.to_sym
568
+ return row[symbol] if row.key?(symbol)
569
+
570
+ nil
571
+ end
572
+
573
+ def decode_null(_value)
574
+ nil
575
+ end
576
+
577
+ def decode_int(value)
578
+ return nil if value.nil?
579
+ return 1 if value == true
580
+ return 0 if value == false
581
+ return value if value.is_a?(Integer)
582
+
583
+ Integer(value.to_s)
584
+ end
585
+
586
+ def decode_float(value)
587
+ return nil if value.nil?
588
+ return value if value.is_a?(Float)
589
+
590
+ Float(value.to_s)
591
+ end
592
+
593
+ def decode_decimal(value)
594
+ return nil if value.nil?
595
+ return value if value.is_a?(String)
596
+ return value.to_s('F') if defined?(BigDecimal) && value.is_a?(BigDecimal)
597
+
598
+ value.to_s
599
+ end
600
+
601
+ def decode_date_value(value)
602
+ return nil if value.nil?
603
+ if value.is_a?(Time)
604
+ return format_time(value)
605
+ end
606
+ if value.is_a?(DateTime)
607
+ return format_local(value.year, value.month, value.day, value.hour, value.min, value.sec, fraction_millis(value))
608
+ end
609
+ if value.is_a?(Date)
610
+ return format_local(value.year, value.month, value.day, 0, 0, 0, 0)
611
+ end
612
+
613
+ decode_date(value.to_s)
614
+ end
615
+
616
+ def decode_datetime_value(value)
617
+ return nil if value.nil?
618
+ if value.is_a?(Time)
619
+ return format_time(value)
620
+ end
621
+ if value.is_a?(DateTime)
622
+ return format_local(value.year, value.month, value.day, value.hour, value.min, value.sec, fraction_millis(value))
623
+ end
624
+ if value.is_a?(Date)
625
+ return format_local(value.year, value.month, value.day, 0, 0, 0, 0)
626
+ end
627
+
628
+ decode_datetime(value.to_s)
629
+ end
630
+
631
+ def decode_date(text)
632
+ return nil unless text.bytesize == 10 && text.getbyte(4) == 45 && text.getbyte(7) == 45
633
+
634
+ y1 = text.getbyte(0)
635
+ y2 = text.getbyte(1)
636
+ y3 = text.getbyte(2)
637
+ y4 = text.getbyte(3)
638
+ m1 = text.getbyte(5)
639
+ m2 = text.getbyte(6)
640
+ d1 = text.getbyte(8)
641
+ d2 = text.getbyte(9)
642
+ return nil if y1 < 48 || y1 > 57 || y2 < 48 || y2 > 57 || y3 < 48 || y3 > 57 || y4 < 48 || y4 > 57
643
+ return nil if m1 < 48 || m1 > 57 || m2 < 48 || m2 > 57 || d1 < 48 || d1 > 57 || d2 < 48 || d2 > 57
644
+
645
+ format_local(
646
+ ((y1 - 48) * 1000) + ((y2 - 48) * 100) + ((y3 - 48) * 10) + (y4 - 48),
647
+ ((m1 - 48) * 10) + (m2 - 48),
648
+ ((d1 - 48) * 10) + (d2 - 48),
649
+ 0, 0, 0, 0
650
+ )
651
+ end
652
+
653
+ def decode_datetime(text)
654
+ size = text.bytesize
655
+ if size >= 19 && text.getbyte(4) == 45 && text.getbyte(7) == 45 && text.getbyte(10) == 32 &&
656
+ text.getbyte(13) == 58 && text.getbyte(16) == 58 && (size == 19 || text.getbyte(19) == 46)
657
+ y1 = text.getbyte(0)
658
+ y2 = text.getbyte(1)
659
+ y3 = text.getbyte(2)
660
+ y4 = text.getbyte(3)
661
+ mo1 = text.getbyte(5)
662
+ mo2 = text.getbyte(6)
663
+ d1 = text.getbyte(8)
664
+ d2 = text.getbyte(9)
665
+ h1 = text.getbyte(11)
666
+ h2 = text.getbyte(12)
667
+ mi1 = text.getbyte(14)
668
+ mi2 = text.getbyte(15)
669
+ s1 = text.getbyte(17)
670
+ s2 = text.getbyte(18)
671
+ unless y1 >= 48 && y1 <= 57 && y2 >= 48 && y2 <= 57 && y3 >= 48 && y3 <= 57 && y4 >= 48 && y4 <= 57 &&
672
+ mo1 >= 48 && mo1 <= 57 && mo2 >= 48 && mo2 <= 57 && d1 >= 48 && d1 <= 57 && d2 >= 48 && d2 <= 57 &&
673
+ h1 >= 48 && h1 <= 57 && h2 >= 48 && h2 <= 57 && mi1 >= 48 && mi1 <= 57 && mi2 >= 48 && mi2 <= 57 &&
674
+ s1 >= 48 && s1 <= 57 && s2 >= 48 && s2 <= 57
675
+ return nil
676
+ end
677
+
678
+ year = ((y1 - 48) * 1000) + ((y2 - 48) * 100) + ((y3 - 48) * 10) + (y4 - 48)
679
+ month = ((mo1 - 48) * 10) + (mo2 - 48)
680
+ day = ((d1 - 48) * 10) + (d2 - 48)
681
+ hour = ((h1 - 48) * 10) + (h2 - 48)
682
+ minute = ((mi1 - 48) * 10) + (mi2 - 48)
683
+ second = ((s1 - 48) * 10) + (s2 - 48)
684
+ milli = 0
685
+ if size > 19
686
+ frac = 0
687
+ digits = 0
688
+ index = 20
689
+ while digits < 6 && index < size
690
+ byte = text.getbyte(index)
691
+ break if byte < 48 || byte > 57
692
+
693
+ frac = frac * 10 + (byte - 48)
694
+ digits += 1
695
+ index += 1
696
+ end
697
+ frac *= 10**(6 - digits) if digits.positive?
698
+ milli = frac / 1000
699
+ end
700
+ return format_local(year, month, day, hour, minute, second, milli)
701
+ end
702
+ decode_datetime_loose(text)
703
+ end
704
+
705
+ def decode_datetime_loose(text)
706
+ date_part, time_part = text.split(' ', 2)
707
+ return nil if time_part.nil? || time_part.empty?
708
+
709
+ hms, fraction = time_part.split('.', 2)
710
+ year, month, day = date_part.split('-').map { |part| Integer(part, 10) }
711
+ hour, minute, second = hms.split(':').map { |part| Integer(part, 10) }
712
+ milli = fraction ? fraction_to_millis(fraction) : 0
713
+ format_local(year, month, day, hour, minute, second, milli)
714
+ rescue ArgumentError
715
+ nil
716
+ end
717
+
718
+ def fraction_to_millis(fraction)
719
+ return 0 if fraction.nil? || fraction.empty?
720
+
721
+ (fraction + '000000')[0, 6].to_i / 1000
722
+ end
723
+
724
+ def fraction_millis(value)
725
+ (value.sec_fraction * 1000).to_i
726
+ end
727
+
728
+ def read_digits(text, start, count)
729
+ number = 0
730
+ count.times do |offset|
731
+ byte = text.getbyte(start + offset)
732
+ return nil if byte.nil? || byte < 48 || byte > 57
733
+
734
+ number = number * 10 + (byte - 48)
735
+ end
736
+ number
737
+ end
738
+
739
+ # Local civil time -> Date#toISOString(). Invalid calendar dates are nil.
740
+ # The zone offset is constant for a civil hour, so it is resolved once and
741
+ # every later cell in that hour is arithmetic plus a string join.
742
+ def format_local(year, month, day, hour, minute, second, milli)
743
+ return nil if hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59
744
+ return nil if milli < 0 || milli > 999
745
+ return nil if month < 1 || month > 12 || day < 1
746
+
747
+ limit = MONTH_DAYS[month]
748
+ if month == 2 && (year % 4).zero? && ((year % 100) != 0 || (year % 400).zero?)
749
+ limit = 29
750
+ end
751
+ return nil if day > limit
752
+
753
+ key = (year << 14) | (month << 10) | (day << 5) | hour
754
+ offset = LOCAL_OFFSETS[key]
755
+ if offset.nil?
756
+ begin
757
+ offset = Time.local(year, month, day, hour, 0, 0).utc_offset
758
+ rescue ArgumentError, RangeError
759
+ offset = false
760
+ end
761
+ LOCAL_OFFSETS_LOCK.synchronize { LOCAL_OFFSETS[key] = offset }
762
+ end
763
+ return nil unless offset
764
+
765
+ total = (hour * 3600 + minute * 60 + second) - offset
766
+ day_delta, total = total.divmod(86_400)
767
+ hour, remainder = total.divmod(3600)
768
+ minute, second = remainder.divmod(60)
769
+ if day_delta != 0
770
+ shifted = Date.new(year, month, day) + day_delta
771
+ year = shifted.year
772
+ month = shifted.month
773
+ day = shifted.day
774
+ return nil if year < 0 || year > 9999
775
+ end
776
+
777
+ "#{ISO_YEAR[year]}-#{ISO_2[month]}-#{ISO_2[day]}T#{ISO_2[hour]}:#{ISO_2[minute]}:#{ISO_2[second]}.#{ISO_3[milli]}Z"
778
+ end
779
+
780
+ def civil_date?(year, month, day)
781
+ return false unless month.between?(1, 12) && day >= 1
782
+
783
+ limit = MONTH_DAYS[month]
784
+ limit = 29 if month == 2 && leap_year?(year)
785
+ day <= limit
786
+ end
787
+
788
+ def leap_year?(year)
789
+ (year % 4).zero? && ((year % 100).nonzero? || (year % 400).zero?)
790
+ end
791
+
792
+ # Seconds east of UTC, or false when that civil hour does not exist.
793
+ def local_offset(year, month, day, hour)
794
+ key = (year << 14) | (month << 10) | (day << 5) | hour
795
+ cached = LOCAL_OFFSETS[key]
796
+ return cached unless cached.nil?
797
+
798
+ offset = Time.local(year, month, day, hour, 0, 0).utc_offset
799
+ LOCAL_OFFSETS_LOCK.synchronize { LOCAL_OFFSETS[key] = offset }
800
+ offset
801
+ rescue ArgumentError, RangeError
802
+ LOCAL_OFFSETS_LOCK.synchronize { LOCAL_OFFSETS[key] = false }
803
+ false
804
+ end
805
+
806
+ def format_time(value)
807
+ utc = value.getutc
808
+ format(
809
+ '%04d-%02d-%02dT%02d:%02d:%02d.%03dZ',
810
+ utc.year, utc.month, utc.day, utc.hour, utc.min, utc.sec, utc.usec / 1000
811
+ )
812
+ end
813
+
814
+ def decode_time(value)
815
+ return nil if value.nil?
816
+ if !value.is_a?(String) && value.respond_to?(:days) && value.respond_to?(:seconds)
817
+ return timedelta_to_mysql_time(value)
818
+ end
819
+
820
+ value.to_s
821
+ end
822
+
823
+ def timedelta_to_mysql_time(value)
824
+ days = value.days.to_i
825
+ seconds = value.seconds.to_i
826
+ microseconds = value.respond_to?(:microseconds) ? value.microseconds.to_i : 0
827
+ total = days * 86_400 + seconds
828
+ sign = total.negative? || (total.zero? && microseconds.negative?) ? '-' : ''
829
+ hours, remainder = total.abs.divmod(3600)
830
+ minutes, secs = remainder.divmod(60)
831
+ text = format('%s%02d:%02d:%02d', sign, hours, minutes, secs)
832
+ text += format('.%06d', microseconds.abs) unless microseconds.zero?
833
+ text
834
+ end
835
+
836
+ def decode_json(value)
837
+ return nil if value.nil?
838
+ return value if value.is_a?(Hash) || value.is_a?(Array) || value.is_a?(Numeric) || value == true || value == false
839
+
840
+ JSON.parse(value.is_a?(String) ? value : value.to_s)
841
+ end
842
+
843
+ def decode_bit(value)
844
+ return nil if value.nil?
845
+ return buffer_from_int(value) if value.is_a?(Integer)
846
+
847
+ buffer_from_string(value.to_s)
848
+ end
849
+
850
+ def decode_binary(value)
851
+ return nil if value.nil?
852
+ return buffer_from_string(value) if value.is_a?(String)
853
+
854
+ decode_text(value)
855
+ end
856
+
857
+ # Binary only when mysql2 tagged the bytes as such (charset 63, like
858
+ # Node); otherwise this is TEXT travelling under a BLOB type code.
859
+ def decode_blob_coded(value)
860
+ return nil if value.nil?
861
+ return buffer_from_string(value) if value.is_a?(String) && value.encoding == Encoding::BINARY
862
+
863
+ decode_text(value)
864
+ end
865
+
866
+ def decode_text(value)
867
+ return nil if value.nil?
868
+ if value.is_a?(String)
869
+ utf8 = value.encoding == Encoding::UTF_8 ? value : value.dup.force_encoding(Encoding::UTF_8)
870
+ return utf8 if utf8.valid_encoding?
871
+
872
+ return buffer_from_string(value)
873
+ end
874
+ return value.to_a.sort.join(',') if value.is_a?(Set)
875
+ return value.to_s('F') if defined?(BigDecimal) && value.is_a?(BigDecimal)
876
+
877
+ value
878
+ end
879
+
880
+ def buffer_from_int(value)
881
+ length = [1, (value.bit_length + 7) / 8].max
882
+ bytes = Array.new(length) { |index| (value >> ((length - 1 - index) * 8)) & 0xFF }
883
+ { 'type' => 'Buffer', 'data' => bytes }
884
+ end
885
+
886
+ def buffer_from_string(value)
887
+ { 'type' => 'Buffer', 'data' => value.b.bytes }
888
+ end
889
+
890
+ def foreign_key_names(results, filter_ids: true)
891
+ names = results[:rows].map { |row| row_value(row, 'COLUMN_NAME') }
892
+ names = names.reject { |key| key == 'id' || key == '_id_' } if filter_ids
893
+ names.uniq
894
+ end
895
+
896
+ def row_value(row, key)
897
+ return row[key] if row.key?(key)
898
+
899
+ symbol = key.to_sym
900
+ return row[symbol] if row.key?(symbol)
901
+
902
+ nil
903
+ end
904
+
905
+ def table_identity(table)
906
+ schema_name = table[:schemaName] || table['schemaName'] || table[:schema_name] || table['schema_name']
907
+ table_name = table[:tableName] || table['tableName'] || table[:table_name] || table['table_name']
908
+ [schema_name, table_name]
909
+ end
910
+
911
+ # Node's textProcessing.depluralize: one trailing "s", and "ies" -> "y".
912
+ def mysql_depluralize(text)
913
+ text = text.to_s
914
+ return "#{text[0..-4]}y" if text.end_with?('ies')
915
+ return text[0..-2].to_s if text.end_with?('s')
916
+
917
+ text
918
+ end
919
+
920
+ def mysql_capitalize(text)
921
+ text = text.to_s
922
+ return text if text.empty?
923
+
924
+ text[0].upcase + text[1..]
925
+ end
926
+
927
+ # decodeURIComponent, not form decoding: "+" stays "+".
928
+ def percent_decode(text)
929
+ return '' if text.nil? || text.empty?
930
+
931
+ text.gsub(/%([0-9A-Fa-f]{2})/) { [Regexp.last_match(1).hex].pack('C') }.force_encoding(Encoding::UTF_8)
932
+ end
933
+ end
934
+ end