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/mssql.rb ADDED
@@ -0,0 +1,917 @@
1
+ require 'bigdecimal'
2
+ require 'date'
3
+ require 'json'
4
+ require 'uri'
5
+ require_relative 'civil_time'
6
+
7
+ # SQL Server driver, mirroring node-sdk/src/db/Mssql.ts.
8
+ #
9
+ # Node returns tedious values as JSON.stringify would render them. Cells here
10
+ # follow that: bigint is text, smaller integers are numbers, bit is a boolean,
11
+ # decimals and money are JS numbers (20, not 20.0), dates and times are UTC
12
+ # ISO strings, GUIDs are upper case, and binary / CLR payloads are
13
+ # { "type": "Buffer", "data": [...] }. Duplicate column names keep the first
14
+ # position and the last column's type, and the row value becomes a list.
15
+ #
16
+ # Field dataTypeIDs use Node's type-name switch. ODBC reports money as
17
+ # decimal(19, 4) and smallmoney as decimal(10, 4), so those precisions land
18
+ # on money (790); a real decimal(19, 4) does too. CLR user-defined types
19
+ # share one code and are reported as geography (bytea), which is what Node
20
+ # does for geography and geometry.
21
+ #
22
+ # tiny_tds is required only when a connection is opened. It does not expose
23
+ # TDS type codes, so a live query asks SQL Server to describe the result and
24
+ # maps those type names onto the same codes.
25
+ module MssqlHelper
26
+ MSSQL_DEFAULT_PORT = 1433
27
+ MSSQL_CONNECTION_TIMEOUT_MS = 15_000
28
+ MSSQL_REQUEST_TIMEOUT_MS = 15_000
29
+ DEFAULT_OID = 1043
30
+ # JS Number.MAX_SAFE_INTEGER. Whole floats inside this range stringify as
31
+ # integers (`20`, not `20.0`).
32
+ MAX_SAFE_INTEGER = 2**53
33
+
34
+ SQL_CHAR = 1
35
+ SQL_NUMERIC = 2
36
+ SQL_DECIMAL = 3
37
+ SQL_INTEGER = 4
38
+ SQL_SMALLINT = 5
39
+ SQL_FLOAT = 6
40
+ SQL_REAL = 7
41
+ SQL_DOUBLE = 8
42
+ SQL_DATE = 9
43
+ SQL_TIME = 10
44
+ SQL_TIMESTAMP = 11
45
+ SQL_VARCHAR = 12
46
+ SQL_TYPE_DATE = 91
47
+ SQL_TYPE_TIME = 92
48
+ SQL_TYPE_TIMESTAMP = 93
49
+ SQL_LONGVARCHAR = -1
50
+ SQL_BINARY = -2
51
+ SQL_VARBINARY = -3
52
+ SQL_LONGVARBINARY = -4
53
+ SQL_BIGINT = -5
54
+ SQL_TINYINT = -6
55
+ SQL_BIT = -7
56
+ SQL_WCHAR = -8
57
+ SQL_WVARCHAR = -9
58
+ SQL_WLONGVARCHAR = -10
59
+ SQL_GUID = -11
60
+ SQL_SS_VARIANT = -150
61
+ SQL_SS_UDT = -151
62
+ SQL_SS_XML = -152
63
+ SQL_SS_TIME2 = -154
64
+ SQL_SS_TIMESTAMPOFFSET = -155
65
+
66
+ ODBC_TYPE_NAMES = {
67
+ SQL_CHAR => 'Char',
68
+ SQL_VARCHAR => 'VarChar',
69
+ SQL_LONGVARCHAR => 'Text',
70
+ SQL_WCHAR => 'NChar',
71
+ SQL_WVARCHAR => 'NVarChar',
72
+ SQL_WLONGVARCHAR => 'NText',
73
+ SQL_INTEGER => 'Int',
74
+ SQL_SMALLINT => 'SmallInt',
75
+ SQL_TINYINT => 'TinyInt',
76
+ SQL_BIGINT => 'BigInt',
77
+ SQL_BIT => 'Bit',
78
+ SQL_FLOAT => 'Float',
79
+ SQL_DOUBLE => 'Float',
80
+ SQL_REAL => 'Real',
81
+ SQL_DECIMAL => 'Decimal',
82
+ SQL_NUMERIC => 'Numeric',
83
+ SQL_BINARY => 'Binary',
84
+ SQL_VARBINARY => 'VarBinary',
85
+ SQL_LONGVARBINARY => 'Image',
86
+ SQL_DATE => 'Date',
87
+ SQL_TYPE_DATE => 'Date',
88
+ SQL_TIME => 'Time',
89
+ SQL_TYPE_TIME => 'Time',
90
+ SQL_SS_TIME2 => 'Time',
91
+ SQL_TIMESTAMP => 'DateTime',
92
+ SQL_TYPE_TIMESTAMP => 'DateTime',
93
+ SQL_SS_TIMESTAMPOFFSET => 'DateTimeOffset',
94
+ SQL_GUID => 'UniqueIdentifier',
95
+ SQL_SS_XML => 'Xml',
96
+ SQL_SS_UDT => 'Geography',
97
+ SQL_SS_VARIANT => 'Variant'
98
+ }.freeze
99
+
100
+ # Node's mssqlDataTypeToPostgresOID, lower-cased.
101
+ MSSQL_DATATYPE_MAP = {
102
+ 'bigint' => 20,
103
+ 'int' => 23,
104
+ 'smallint' => 21,
105
+ 'tinyint' => 21,
106
+ 'decimal' => 1700,
107
+ 'numeric' => 1700,
108
+ 'money' => 790,
109
+ 'smallmoney' => 790,
110
+ 'float' => 701,
111
+ 'real' => 700,
112
+ 'bit' => 16,
113
+ 'char' => 1042,
114
+ 'varchar' => 1043,
115
+ 'text' => 25,
116
+ 'nchar' => 1042,
117
+ 'nvarchar' => 1043,
118
+ 'ntext' => 25,
119
+ 'binary' => 17,
120
+ 'varbinary' => 17,
121
+ 'image' => 17,
122
+ 'date' => 1082,
123
+ 'datetime' => 1114,
124
+ 'datetime2' => 1114,
125
+ 'smalldatetime' => 1114,
126
+ 'time' => 1083,
127
+ 'datetimeoffset' => 1184,
128
+ 'uniqueidentifier' => 2950,
129
+ 'xml' => 142,
130
+ 'json' => 114,
131
+ 'sql_variant' => 1043,
132
+ 'geometry' => 17,
133
+ 'geography' => 17
134
+ }.freeze
135
+
136
+ SYSTEM_TYPE_CODES = {
137
+ 'bigint' => SQL_BIGINT,
138
+ 'int' => SQL_INTEGER,
139
+ 'smallint' => SQL_SMALLINT,
140
+ 'tinyint' => SQL_TINYINT,
141
+ 'bit' => SQL_BIT,
142
+ 'decimal' => SQL_DECIMAL,
143
+ 'numeric' => SQL_NUMERIC,
144
+ 'money' => SQL_DECIMAL,
145
+ 'smallmoney' => SQL_DECIMAL,
146
+ 'float' => SQL_FLOAT,
147
+ 'real' => SQL_REAL,
148
+ 'char' => SQL_CHAR,
149
+ 'varchar' => SQL_VARCHAR,
150
+ 'text' => SQL_LONGVARCHAR,
151
+ 'nchar' => SQL_WCHAR,
152
+ 'nvarchar' => SQL_WVARCHAR,
153
+ 'ntext' => SQL_WLONGVARCHAR,
154
+ 'binary' => SQL_BINARY,
155
+ 'varbinary' => SQL_VARBINARY,
156
+ 'image' => SQL_LONGVARBINARY,
157
+ 'date' => SQL_TYPE_DATE,
158
+ 'time' => SQL_SS_TIME2,
159
+ 'datetime' => SQL_TYPE_TIMESTAMP,
160
+ 'datetime2' => SQL_TYPE_TIMESTAMP,
161
+ 'smalldatetime' => SQL_TYPE_TIMESTAMP,
162
+ 'datetimeoffset' => SQL_SS_TIMESTAMPOFFSET,
163
+ 'uniqueidentifier' => SQL_GUID,
164
+ 'xml' => SQL_SS_XML,
165
+ 'geography' => SQL_SS_UDT,
166
+ 'geometry' => SQL_SS_UDT,
167
+ 'hierarchyid' => SQL_SS_UDT,
168
+ 'sql_variant' => SQL_SS_VARIANT
169
+ }.freeze
170
+
171
+ INTEGER_CODES = [SQL_INTEGER, SQL_SMALLINT, SQL_TINYINT].freeze
172
+ FLOAT_CODES = [SQL_FLOAT, SQL_DOUBLE, SQL_REAL].freeze
173
+ DECIMAL_CODES = [SQL_DECIMAL, SQL_NUMERIC].freeze
174
+ DATE_CODES = [SQL_DATE, SQL_TYPE_DATE].freeze
175
+ TIME_CODES = [SQL_TIME, SQL_TYPE_TIME, SQL_SS_TIME2].freeze
176
+ DATETIME_CODES = [SQL_TIMESTAMP, SQL_TYPE_TIMESTAMP, SQL_SS_TIMESTAMPOFFSET].freeze
177
+ BINARY_CODES = [SQL_BINARY, SQL_VARBINARY, SQL_LONGVARBINARY, SQL_SS_UDT].freeze
178
+ # FreeTDS bytes (including the sign byte) for a numeric of this precision.
179
+ NUMERIC_BYTES_PER_PREC = [
180
+ 1,
181
+ 2, 2, 3, 3, 4, 4, 4, 5, 5,
182
+ 6, 6, 6, 7, 7, 8, 8, 9, 9, 9,
183
+ 10, 10, 11, 11, 11, 12, 12, 13, 13, 14,
184
+ 14, 14, 15, 15, 16, 16, 16, 17, 17
185
+ ].freeze
186
+ POW10 = (0..38).map { |scale| 10**scale }.freeze
187
+ DECODER_CACHE = {}
188
+ # Days from 1900-01-01 to 1970-01-01. Variant dates count from 1900.
189
+ DAYS_1900_TO_UNIX = 25_567
190
+ TEXT_CODES = [SQL_CHAR, SQL_VARCHAR, SQL_LONGVARCHAR, SQL_WCHAR, SQL_WVARCHAR, SQL_WLONGVARCHAR].freeze
191
+
192
+ # Lazy pool. `connect` validates and returns the socket; each query opens
193
+ # another. `close` marks it closed so the next use builds a fresh pool.
194
+ class MssqlConnectionPool
195
+ attr_accessor :connected
196
+
197
+ def initialize(config = nil)
198
+ @config = config || {}
199
+ @connected = false
200
+ @closed = false
201
+ end
202
+
203
+ def closed?
204
+ @closed
205
+ end
206
+
207
+ def connect
208
+ MssqlHelper.close_quietly(open_connection)
209
+ @connected = true
210
+ @closed = false
211
+ self
212
+ end
213
+
214
+ def acquire
215
+ open_connection
216
+ end
217
+
218
+ def close
219
+ @connected = false
220
+ @closed = true
221
+ end
222
+
223
+ def open_connection
224
+ connection = MssqlHelper.connect_client(@config)
225
+ seconds = MssqlHelper.request_timeout_seconds(@config)
226
+ connection.timeout = seconds if seconds.positive? && connection.respond_to?(:timeout=)
227
+ connection
228
+ end
229
+ end
230
+
231
+ # Wraps TinyTds::Client with the cursor shape run_query_mssql expects.
232
+ class TinyTdsConnection
233
+ attr_accessor :timeout
234
+
235
+ def initialize(client)
236
+ @client = client
237
+ end
238
+
239
+ def cursor
240
+ TinyTdsCursor.new(@client)
241
+ end
242
+
243
+ def close
244
+ @client.close if @client.respond_to?(:close)
245
+ end
246
+ end
247
+
248
+ class TinyTdsCursor
249
+ attr_reader :description, :column_sql_types
250
+
251
+ def initialize(client)
252
+ @client = client
253
+ @description = nil
254
+ @column_sql_types = nil
255
+ @rows = []
256
+ end
257
+
258
+ def execute(sql)
259
+ meta = describe_metadata(sql)
260
+ with_query_option(:as, :array) do
261
+ result = @client.execute(sql)
262
+ names = result.respond_to?(:fields) ? Array(result.fields) : []
263
+ @rows = []
264
+ result.each { |row| @rows << row } if result.respond_to?(:each)
265
+ if names.empty?
266
+ @description = nil
267
+ @column_sql_types = nil
268
+ else
269
+ @column_sql_types = []
270
+ @description = names.each_with_index.map do |name, index|
271
+ code, precision, scale = column_meta(meta, index)
272
+ @column_sql_types << code
273
+ [name, nil, nil, precision, precision, scale, true]
274
+ end
275
+ end
276
+ end
277
+ end
278
+
279
+ def fetchall
280
+ @rows
281
+ end
282
+
283
+ def close; end
284
+
285
+ private
286
+
287
+ def describe_metadata(sql)
288
+ rows = []
289
+ with_query_option(:as, :hash) do
290
+ result = @client.execute(MssqlHelper.describe_sql(sql))
291
+ result.each { |row| rows << row } if result.respond_to?(:each)
292
+ end
293
+ rows
294
+ rescue StandardError
295
+ nil
296
+ end
297
+
298
+ def column_meta(meta, index)
299
+ return [nil, nil, nil] if meta.nil? || meta[index].nil?
300
+
301
+ row = meta[index]
302
+ MssqlHelper.system_type_column(
303
+ MssqlHelper.row_value(row, 'system_type_name'),
304
+ MssqlHelper.row_value(row, 'precision'),
305
+ MssqlHelper.row_value(row, 'scale')
306
+ )
307
+ end
308
+
309
+ def with_query_option(key, value)
310
+ return yield unless @client.respond_to?(:query_options)
311
+
312
+ options = @client.query_options
313
+ previous = options[key]
314
+ options[key] = value
315
+ yield
316
+ ensure
317
+ options[key] = previous if options
318
+ end
319
+ end
320
+
321
+ class << self
322
+ def mssql_data_type_to_postgres_oid(type_name)
323
+ MSSQL_DATATYPE_MAP[type_name.to_s.downcase] || DEFAULT_OID
324
+ end
325
+
326
+ def odbc_type_name(type_code, precision = nil, scale = nil)
327
+ if type_code == SQL_DECIMAL && scale == 4 && [19, 10].include?(precision)
328
+ return precision == 19 ? 'Money' : 'SmallMoney'
329
+ end
330
+
331
+ ODBC_TYPE_NAMES[type_code] || ''
332
+ end
333
+
334
+ # `decimal(18,2)` / `money` from sys.dm_exec_describe_first_result_set,
335
+ # as an ODBC code plus precision and scale.
336
+ def system_type_column(type_name, precision = nil, scale = nil)
337
+ base, parsed_precision, parsed_scale = split_type_name(type_name)
338
+ precision = parsed_precision if precision.nil? || precision.to_s.empty?
339
+ scale = parsed_scale if scale.nil? || scale.to_s.empty?
340
+ precision = integer_or_nil(precision)
341
+ scale = integer_or_nil(scale)
342
+ case base
343
+ when 'money'
344
+ [SQL_DECIMAL, 19, 4]
345
+ when 'smallmoney'
346
+ [SQL_DECIMAL, 10, 4]
347
+ else
348
+ [SYSTEM_TYPE_CODES[base], precision, scale]
349
+ end
350
+ end
351
+
352
+ def describe_sql(sql)
353
+ literal = sql.to_s.gsub("'", "''")
354
+ "SELECT name, system_type_name, precision, scale FROM sys.dm_exec_describe_first_result_set(N'#{literal}', NULL, 0)"
355
+ end
356
+
357
+ def format_mssql_config(connection_string)
358
+ parsed = URI.parse(connection_string)
359
+ path = parsed.path.to_s
360
+ database = path.start_with?('/') ? path[1..].to_s : path
361
+ {
362
+ server: parsed.host || '',
363
+ user: percent_decode(parsed.user),
364
+ password: percent_decode(parsed.password),
365
+ database: database,
366
+ port: parsed.port || MSSQL_DEFAULT_PORT,
367
+ options: {
368
+ encrypt: true,
369
+ trustServerCertificate: true
370
+ }
371
+ }
372
+ end
373
+
374
+ def connect_to_mssql(config)
375
+ MssqlConnectionPool.new(config)
376
+ end
377
+
378
+ def disconnect_from_mssql(pool)
379
+ return if pool.nil?
380
+
381
+ pool.close if pool.respond_to?(:close)
382
+ end
383
+
384
+ def tiny_tds_client_class
385
+ require 'tiny_tds'
386
+ TinyTds::Client
387
+ end
388
+
389
+ def client_options(config)
390
+ options = config_value(config, :options) || {}
391
+ encrypt = config_value(options, :encrypt)
392
+ trust = config_value(options, :trustServerCertificate)
393
+ server = config_value(config, :server)
394
+ server = 'localhost' if server.nil? || server.to_s.empty?
395
+ port = (config_value(config, :port) || MSSQL_DEFAULT_PORT).to_i
396
+ opts = {
397
+ host: server,
398
+ port: port,
399
+ username: config_value(config, :user).to_s,
400
+ password: config_value(config, :password).to_s,
401
+ login_timeout: login_timeout_seconds(config),
402
+ timeout: request_timeout_seconds(config),
403
+ tds_version: '7.4',
404
+ encrypt: encrypt.nil? ? true : encrypt,
405
+ trustServerCertificate: trust.nil? ? true : trust
406
+ }
407
+ database = config_value(config, :database)
408
+ opts[:database] = database unless database.nil? || database.to_s.empty?
409
+ opts
410
+ end
411
+
412
+ def login_timeout_seconds(config)
413
+ timeout_seconds(config, :connectionTimeout, MSSQL_CONNECTION_TIMEOUT_MS)
414
+ end
415
+
416
+ def request_timeout_seconds(config)
417
+ timeout_seconds(config, :requestTimeout, MSSQL_REQUEST_TIMEOUT_MS)
418
+ end
419
+
420
+ def connect_client(config)
421
+ client = tiny_tds_client_class.new(client_options(config))
422
+ if client.respond_to?(:query_options)
423
+ client.query_options[:timezone] = :utc
424
+ client.query_options[:symbolize_keys] = false
425
+ client.query_options[:cache_rows] = true
426
+ client.query_options[:empty_sets] = true
427
+ end
428
+ TinyTdsConnection.new(client)
429
+ end
430
+
431
+ def mssql_value(value, type_code = nil)
432
+ decoder_for(type_code).call(value)
433
+ end
434
+
435
+ def run_query_mssql(sql, pool)
436
+ connection = nil
437
+ cursor = nil
438
+ begin
439
+ pool.connect unless pool.connected
440
+ connection = pool.acquire
441
+ cursor = connection.cursor
442
+ cursor.execute(sql)
443
+ description = cursor.description
444
+ type_codes = column_type_codes(cursor, description)
445
+ rows = description.nil? || description.empty? ? [] : cursor.fetchall
446
+ ensure
447
+ cursor.close if cursor.respond_to?(:close)
448
+ close_quietly(connection)
449
+ end
450
+ shape_result(description, type_codes, rows)
451
+ end
452
+
453
+ def get_schemas_mssql(pool)
454
+ sql = <<~SQL
455
+ SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA
456
+ WHERE SCHEMA_NAME != 'INFORMATION_SCHEMA'
457
+ SQL
458
+ results = run_query_mssql(sql, pool)
459
+ results[:rows].map { |row| row_value(row, 'SCHEMA_NAME') }
460
+ end
461
+
462
+ def get_tables_by_schema_mssql(pool, schema_names)
463
+ schema_names.flat_map do |schema|
464
+ sql = <<~SQL
465
+ SELECT TABLE_NAME, TABLE_SCHEMA
466
+ FROM INFORMATION_SCHEMA.TABLES
467
+ WHERE TABLE_SCHEMA = '#{schema}'
468
+ AND TABLE_TYPE = 'BASE TABLE'
469
+ SQL
470
+ results = run_query_mssql(sql, pool)
471
+ results[:rows].map do |row|
472
+ {
473
+ tableName: row_value(row, 'TABLE_NAME'),
474
+ schemaName: row_value(row, 'TABLE_SCHEMA')
475
+ }
476
+ end
477
+ end
478
+ end
479
+
480
+ def get_columns_by_table_mssql(pool, schema_name, table_name)
481
+ sql = <<~SQL
482
+ SELECT COLUMN_NAME
483
+ FROM INFORMATION_SCHEMA.COLUMNS
484
+ WHERE TABLE_SCHEMA = '#{schema_name}'
485
+ AND TABLE_NAME = '#{table_name}'
486
+ ORDER BY ORDINAL_POSITION
487
+ SQL
488
+ results = run_query_mssql(sql, pool)
489
+ results[:rows].map { |row| row_value(row, 'COLUMN_NAME') }
490
+ end
491
+
492
+ # Node's getForeignKeys for mssql is unused and returns nothing.
493
+ def get_foreign_keys_mssql(_pool, _schema_name, _table_name, _primary_key)
494
+ []
495
+ end
496
+
497
+ def get_schema_column_info_mssql(pool, _schema_name, table_names)
498
+ table_names.map do |table|
499
+ table_schema, table_name = table_identity(table)
500
+ sql = <<~SQL
501
+ SELECT
502
+ COLUMN_NAME as columnName,
503
+ DATA_TYPE as fieldType,
504
+ ORDINAL_POSITION as sortNumber
505
+ FROM INFORMATION_SCHEMA.COLUMNS
506
+ WHERE TABLE_SCHEMA = '#{table_schema}'
507
+ AND TABLE_NAME = '#{table_name}'
508
+ ORDER BY ORDINAL_POSITION
509
+ SQL
510
+ results = run_query_mssql(sql, pool)
511
+ {
512
+ tableName: "#{table_schema}.#{table_name}",
513
+ displayName: "#{table_schema}.#{table_name}",
514
+ columns: results[:rows].map do |row|
515
+ field_type = row_value(row, 'fieldType')
516
+ column_name = row_value(row, 'columnName')
517
+ {
518
+ columnName: column_name,
519
+ displayName: column_name,
520
+ dataTypeID: mssql_data_type_to_postgres_oid(field_type),
521
+ fieldType: field_type
522
+ }
523
+ end
524
+ }
525
+ end
526
+ end
527
+
528
+ def row_value(row, key)
529
+ return nil unless row.is_a?(Hash)
530
+ return row[key] if row.key?(key)
531
+
532
+ symbol = key.to_sym
533
+ return row[symbol] if row.key?(symbol)
534
+
535
+ nil
536
+ end
537
+
538
+ def close_quietly(connection)
539
+ connection.close if connection.respond_to?(:close)
540
+ rescue StandardError
541
+ nil
542
+ end
543
+
544
+ private
545
+
546
+ def shape_result(description, type_codes, rows)
547
+ description = [] if description.nil?
548
+ columns = {}
549
+ decoders = []
550
+ description.each_with_index do |column, index|
551
+ name = column[0]
552
+ precision = column.length > 4 ? column[4] : nil
553
+ scale = column.length > 5 ? column[5] : nil
554
+ type_code = type_codes[index]
555
+ type_name = odbc_type_name(type_code, precision, scale)
556
+ columns[name] = {
557
+ name: name,
558
+ dataTypeID: mssql_data_type_to_postgres_oid(type_name)
559
+ }
560
+ decoders << [name, decoder_for(type_code)]
561
+ end
562
+
563
+ processed = Array(rows).map do |row|
564
+ values = row_values(row, decoders.map(&:first))
565
+ built = {}
566
+ decoders.zip(values) do |(name, decode), value|
567
+ value = decode.call(value)
568
+ key = name.to_s
569
+ if built.key?(key)
570
+ existing = built[key]
571
+ if existing.is_a?(Array)
572
+ existing << value
573
+ else
574
+ built[key] = [existing, value]
575
+ end
576
+ else
577
+ built[key] = value
578
+ end
579
+ end
580
+ built
581
+ end
582
+
583
+ { fields: columns.values, rows: processed }
584
+ end
585
+
586
+ def column_type_codes(cursor, description)
587
+ return [] if description.nil?
588
+
589
+ codes = cursor.respond_to?(:column_sql_types) ? cursor.column_sql_types : nil
590
+ return Array.new(description.length) if codes.nil? || codes.length != description.length
591
+
592
+ codes
593
+ end
594
+
595
+ def row_values(row, names)
596
+ return names.map { |name| row_value(row, name.to_s) } if row.is_a?(Hash)
597
+
598
+ row
599
+ end
600
+
601
+ def decoder_for(type_code)
602
+ DECODER_CACHE[type_code] ||= resolve_decoder(type_code)
603
+ end
604
+
605
+ def resolve_decoder(type_code)
606
+ return method(:decode_bigint) if type_code == SQL_BIGINT
607
+ return method(:decode_bit) if type_code == SQL_BIT
608
+ return method(:decode_int) if INTEGER_CODES.include?(type_code)
609
+ return method(:decode_number) if FLOAT_CODES.include?(type_code) || DECIMAL_CODES.include?(type_code)
610
+ return method(:decode_datetime) if DATETIME_CODES.include?(type_code)
611
+ return method(:decode_date) if DATE_CODES.include?(type_code)
612
+ return method(:decode_time) if TIME_CODES.include?(type_code)
613
+ return method(:decode_guid) if type_code == SQL_GUID
614
+ return method(:decode_binary) if BINARY_CODES.include?(type_code)
615
+ return method(:decode_text) if TEXT_CODES.include?(type_code)
616
+ return method(:decode_variant) if type_code == SQL_SS_VARIANT
617
+
618
+ method(:decode_generic_value)
619
+ end
620
+
621
+ def decode_bigint(value)
622
+ return value if value.nil? || value.is_a?(String)
623
+
624
+ Integer(value).to_s
625
+ end
626
+
627
+ def decode_bit(value)
628
+ return nil if value.nil?
629
+ return false if value == false || value == 0
630
+ return true if value == true
631
+ return !value.zero? if value.is_a?(Numeric)
632
+
633
+ !value.nil?
634
+ end
635
+
636
+ def decode_int(value)
637
+ return nil if value.nil?
638
+ return value if value.is_a?(Integer)
639
+
640
+ Integer(value)
641
+ end
642
+
643
+ def decode_number(value)
644
+ return nil if value.nil?
645
+ return value if value == true || value == false
646
+ return value if value.is_a?(Integer)
647
+
648
+ js_number(value)
649
+ end
650
+
651
+ def decode_datetime(value)
652
+ return nil if value.nil?
653
+ return datetime_iso(value) if value.is_a?(Time) || value.is_a?(DateTime)
654
+
655
+ decode_generic_value(value)
656
+ end
657
+
658
+ def decode_date(value)
659
+ return nil if value.nil?
660
+ return date_iso(value) if value.is_a?(Date)
661
+
662
+ decode_generic_value(value)
663
+ end
664
+
665
+ def decode_time(value)
666
+ return nil if value.nil?
667
+ return time_iso(value) if value.is_a?(Time) || time_only?(value)
668
+
669
+ decode_generic_value(value)
670
+ end
671
+
672
+ def decode_guid(value)
673
+ return nil if value.nil?
674
+
675
+ value.to_s.upcase
676
+ end
677
+
678
+ def decode_binary(value)
679
+ return nil if value.nil?
680
+ return buffer(value) if value.is_a?(String)
681
+
682
+ decode_generic_value(value)
683
+ end
684
+
685
+ def decode_text(value)
686
+ return nil if value.nil?
687
+ return textual(value) if value.is_a?(String)
688
+
689
+ decode_generic_value(value)
690
+ end
691
+
692
+ # tiny_tds keeps an int variant as an Integer and a character variant as
693
+ # text. Datetime arrives as FreeTDS's 16-byte TDS_DATETIMEALL, decimal as
694
+ # the start of TDS_NUMERIC, and bit as a single 0 or 1 byte.
695
+ def decode_variant(value)
696
+ return nil if value.nil?
697
+ return value if value == true || value == false || value.is_a?(Integer)
698
+ return js_number(value) if value.is_a?(Float) || (defined?(BigDecimal) && value.is_a?(BigDecimal))
699
+ return textual(value) unless value.is_a?(String)
700
+
701
+ datetime = variant_datetime(value)
702
+ return datetime unless datetime.nil?
703
+
704
+ number = variant_numeric(value)
705
+ return number unless number.nil?
706
+
707
+ bit = variant_bit(value)
708
+ return bit unless bit.nil?
709
+
710
+ textual(value)
711
+ end
712
+
713
+ def decode_generic_value(value)
714
+ return nil if value.nil?
715
+ return value if value == true || value == false
716
+ return value if value.is_a?(Integer)
717
+ return textual(value) if value.is_a?(String)
718
+ return js_number(value) if value.is_a?(Float) || (defined?(BigDecimal) && value.is_a?(BigDecimal))
719
+ return datetime_iso(value) if value.is_a?(Time) || value.is_a?(DateTime)
720
+ return date_iso(value) if value.is_a?(Date)
721
+ return time_iso(value) if time_only?(value)
722
+ return value.to_s.upcase if uuid_like?(value)
723
+
724
+ value
725
+ end
726
+
727
+ def js_number(value)
728
+ return value if value == true || value == false
729
+ return value if value.is_a?(Integer)
730
+
731
+ number = value.is_a?(Float) ? value : value.to_f
732
+ return number.to_i if number.finite? && number.abs < MAX_SAFE_INTEGER && number == number.to_i
733
+
734
+ number
735
+ end
736
+
737
+ def datetime_iso(value)
738
+ if value.is_a?(Time)
739
+ wall = value.utc_offset.zero? ? value : value.getutc
740
+ return format_iso(wall.year, wall.month, wall.day, wall.hour, wall.min, wall.sec, wall.usec)
741
+ end
742
+
743
+ utc = value.offset.zero? ? value : value.new_offset(0)
744
+ format_iso(utc.year, utc.month, utc.day, utc.hour, utc.min, utc.sec, (utc.sec_fraction * 1_000_000).to_i)
745
+ end
746
+
747
+ def date_iso(value)
748
+ format('%04d-%02d-%02dT00:00:00.000Z', value.year, value.month, value.day)
749
+ end
750
+
751
+ def time_iso(value)
752
+ hour, minute, second, usec = time_parts(value)
753
+ format('1970-01-01T%02d:%02d:%02d.%03dZ', hour, minute, second, usec / 1000)
754
+ end
755
+
756
+ def format_iso(year, month, day, hour, minute, second, usec)
757
+ milli = usec / 1000
758
+ if year.between?(0, 9999) && month.between?(1, 12) && day.between?(1, 31) &&
759
+ hour.between?(0, 23) && minute.between?(0, 59) && second.between?(0, 59) && milli.between?(0, 999)
760
+ return CivilTime.iso_utc(year, month, day, hour, minute, second, milli)
761
+ end
762
+
763
+ format('%04d-%02d-%02dT%02d:%02d:%02d.%03dZ', year, month, day, hour, minute, second, milli)
764
+ end
765
+
766
+ def time_parts(value)
767
+ minute = value.respond_to?(:min) ? value.min : value.minute
768
+ second = value.respond_to?(:sec) ? value.sec : value.second
769
+ usec = if value.respond_to?(:usec)
770
+ value.usec
771
+ elsif value.respond_to?(:microsecond)
772
+ value.microsecond
773
+ else
774
+ 0
775
+ end
776
+ [value.hour, minute, second, usec.to_i]
777
+ end
778
+
779
+ def time_only?(value)
780
+ return false if value.is_a?(Time) || value.is_a?(Date) || value.is_a?(String) || value.is_a?(Numeric)
781
+
782
+ value.respond_to?(:hour) && (value.respond_to?(:min) || value.respond_to?(:minute)) && !value.respond_to?(:year)
783
+ end
784
+
785
+ def uuid_like?(value)
786
+ value.class.name.to_s.split('::').last == 'UUID'
787
+ end
788
+
789
+ def variant_datetime(value)
790
+ return nil unless value.bytesize == 16
791
+
792
+ flags = value.getbyte(14) | (value.getbyte(15) << 8)
793
+ has_time = (flags & 0x2000) != 0
794
+ has_date = (flags & 0x4000) != 0
795
+ return nil unless has_date || has_time
796
+
797
+ ticks = 0
798
+ 8.times { |index| ticks |= value.getbyte(index) << (8 * index) }
799
+ days = value.getbyte(8) | (value.getbyte(9) << 8) | (value.getbyte(10) << 16) | (value.getbyte(11) << 24)
800
+ days -= 2**32 if days >= 2**31
801
+ seconds, fraction = ticks.divmod(10_000_000)
802
+ extra_days, second_of_day = seconds.divmod(86_400)
803
+ hour, remainder = second_of_day.divmod(3600)
804
+ minute, second = remainder.divmod(60)
805
+ year, month, day = CivilTime.civil_from_days(days - DAYS_1900_TO_UNIX + extra_days)
806
+ format_iso(year, month, day, hour, minute, second, fraction / 10)
807
+ end
808
+
809
+ def variant_numeric(value)
810
+ return nil if value.bytesize < 3
811
+
812
+ precision = value.getbyte(0)
813
+ scale = value.getbyte(1)
814
+ return nil if precision < 1 || precision > 38 || scale > precision
815
+
816
+ width = NUMERIC_BYTES_PER_PREC[precision]
817
+ return nil if value.bytesize < 2 + width
818
+
819
+ sign = value.getbyte(2)
820
+ return nil unless sign == 0 || sign == 1
821
+
822
+ index = 2 + width
823
+ while index < value.bytesize
824
+ return nil if value.getbyte(index) != 0
825
+
826
+ index += 1
827
+ end
828
+
829
+ magnitude = 0
830
+ (width - 1).times { |offset| magnitude = (magnitude << 8) | value.getbyte(3 + offset) }
831
+ if scale.zero? || (magnitude % POW10[scale]).zero?
832
+ number = scale.zero? ? magnitude : magnitude / POW10[scale]
833
+ elsif magnitude <= MAX_SAFE_INTEGER
834
+ number = magnitude.to_f / POW10[scale]
835
+ else
836
+ number = BigDecimal(magnitude) / POW10[scale]
837
+ end
838
+ number = -number if sign == 1
839
+ if number.is_a?(Integer)
840
+ return number if number.abs < MAX_SAFE_INTEGER
841
+
842
+ return number.to_f
843
+ end
844
+
845
+ js_number(number)
846
+ end
847
+
848
+ def variant_bit(value)
849
+ return nil unless value.bytesize == 1
850
+
851
+ byte = value.getbyte(0)
852
+ return nil unless byte == 0 || byte == 1
853
+
854
+ byte == 1
855
+ end
856
+
857
+ # tiny_tds returns image/varbinary as binary, but geography, geometry, and
858
+ # hierarchyid as UTF-8-tagged strings of the raw CLR bytes. Those bytes are
859
+ # not valid UTF-8, and JSON.generate raises on them.
860
+ def textual(value)
861
+ return buffer(value) if binary_string?(value) || !value.valid_encoding?
862
+
863
+ value
864
+ end
865
+
866
+ def binary_string?(value)
867
+ value.is_a?(String) && value.encoding == Encoding::ASCII_8BIT
868
+ end
869
+
870
+ def buffer(value)
871
+ { 'type' => 'Buffer', 'data' => value.b.bytes }
872
+ end
873
+
874
+ def table_identity(table)
875
+ schema_name = table[:schemaName] || table['schemaName'] || table[:schema_name] || table['schema_name']
876
+ table_name = table[:tableName] || table['tableName'] || table[:table_name] || table['table_name']
877
+ [schema_name, table_name]
878
+ end
879
+
880
+ def split_type_name(type_name)
881
+ text = type_name.to_s.strip.downcase
882
+ base, rest = text.split('(', 2)
883
+ return [base, nil, nil] if rest.nil?
884
+
885
+ parts = rest.sub(/\)\z/, '').split(',').map(&:strip)
886
+ [base, integer_or_nil(parts[0]), integer_or_nil(parts[1])]
887
+ end
888
+
889
+ def integer_or_nil(value)
890
+ return nil if value.nil?
891
+ return value if value.is_a?(Integer)
892
+
893
+ text = value.to_s.strip
894
+ return nil if text.empty? || text !~ /\A-?\d+\z/
895
+
896
+ text.to_i
897
+ end
898
+
899
+ def timeout_seconds(config, key, default_ms)
900
+ ms = config_value(config, key)
901
+ ms = default_ms if ms.nil?
902
+ [0, ms.to_i / 1000].max
903
+ end
904
+
905
+ def config_value(config, key)
906
+ return nil if config.nil?
907
+
908
+ config[key].nil? ? config[key.to_s] : config[key]
909
+ end
910
+
911
+ def percent_decode(text)
912
+ return '' if text.nil? || text.empty?
913
+
914
+ text.gsub(/%([0-9A-Fa-f]{2})/) { [Regexp.last_match(1).hex].pack('C') }.force_encoding(Encoding::UTF_8)
915
+ end
916
+ end
917
+ end