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.
@@ -0,0 +1,1167 @@
1
+ require 'bigdecimal'
2
+ require 'date'
3
+ require 'json'
4
+ require_relative 'civil_time'
5
+ require 'net/http'
6
+ require 'securerandom'
7
+ require 'stringio'
8
+ require 'uri'
9
+ require 'zlib'
10
+
11
+ # Snowflake driver, mirroring node-sdk/src/db/Snowflake.ts and the Python
12
+ # port in quillsql/db/snowflake.py.
13
+ #
14
+ # Query rows are the shapes `JSON.stringify` produces for snowflake-sdk:
15
+ # integral numbers render as integers (`20`, including `0`), DATE is
16
+ # `YYYY-MM-DD`, TIMESTAMP_NTZ / naive TIMESTAMP is `YYYY-MM-DD HH:MM:SS.mmm`,
17
+ # TIMESTAMP_LTZ / TIMESTAMP_TZ add ` ±HHMM`, TIME is `HH:MM:SS`, null TIME is
18
+ # the string `"NULL"`, BINARY is `{ "type": "Buffer", "data": [...] }`, and
19
+ # VARIANT / OBJECT / ARRAY / GEOGRAPHY / GEOMETRY / VECTOR are parsed JSON.
20
+ #
21
+ # Query-result `dataTypeID` follows snowflake-sdk `col.getType()`: numeric
22
+ # columns are FIXED (1700), floats are REAL (700), and GEOGRAPHY / GEOMETRY
23
+ # are `object` (3802). The map's GEOGRAPHY: 25 entry is only used for
24
+ # INFORMATION_SCHEMA lookups.
25
+ #
26
+ # Live connections use Snowflake's session HTTP API with the username and
27
+ # password from `snowflake://user:password@account/database/warehouse`. No
28
+ # extra gem is required, so the Spree Ruby server can load this driver from
29
+ # the SDK gemspec alone. Tests stub `snowflake_connector` or pass a fake
30
+ # client and never open a socket.
31
+ module SnowflakeHelper
32
+ # A login or statement Snowflake rejected, with the code and SQLSTATE it sent.
33
+ class QueryError < RuntimeError
34
+ attr_reader :code, :sql_state
35
+
36
+ def initialize(message, body)
37
+ super(message)
38
+ @code = body['code']
39
+ @sql_state = body.dig('data', 'sqlState')
40
+ end
41
+ end
42
+
43
+ # JS Number.MAX_SAFE_INTEGER. Whole floats inside this range stringify as
44
+ # integers (`20`, not `20.0`).
45
+ MAX_SAFE_INTEGER = 2**53
46
+
47
+ # Node's POSTGRES_SNOWFLAKE_MAP, upper-case keys.
48
+ POSTGRES_SNOWFLAKE_MAP = {
49
+ 'NUMBER' => 1700,
50
+ 'DECIMAL' => 1700,
51
+ 'NUMERIC' => 1700,
52
+ 'FIXED' => 1700,
53
+ 'INT' => 23,
54
+ 'INTEGER' => 23,
55
+ 'BIGINT' => 20,
56
+ 'SMALLINT' => 21,
57
+ 'TINYINT' => 21,
58
+ 'BYTEINT' => 21,
59
+ 'FLOAT' => 701,
60
+ 'FLOAT4' => 700,
61
+ 'FLOAT8' => 701,
62
+ 'DOUBLE' => 701,
63
+ 'REAL' => 700,
64
+ 'BOOLEAN' => 16,
65
+ 'VARCHAR' => 1043,
66
+ 'CHAR' => 1042,
67
+ 'CHARACTER' => 1042,
68
+ 'STRING' => 25,
69
+ 'TEXT' => 25,
70
+ 'BINARY' => 17,
71
+ 'VARBINARY' => 17,
72
+ 'DATE' => 1082,
73
+ 'DATETIME' => 1184,
74
+ 'TIME' => 1083,
75
+ 'TIMESTAMP' => 1184,
76
+ 'TIMESTAMP_LTZ' => 1184,
77
+ 'TIMESTAMP_NTZ' => 1114,
78
+ 'TIMESTAMP_TZ' => 1184,
79
+ 'VARIANT' => 3802,
80
+ 'OBJECT' => 3802,
81
+ 'ARRAY' => 2277,
82
+ 'GEOGRAPHY' => 25,
83
+ 'GEOMETRY' => 25,
84
+ 'VECTOR' => 3802
85
+ }.freeze
86
+
87
+ # snowflake-connector FIELD_ID -> the name snowflake-sdk getType() reports.
88
+ FIELD_ID_TO_NAME = {
89
+ 0 => 'FIXED',
90
+ 1 => 'REAL',
91
+ 2 => 'TEXT',
92
+ 3 => 'DATE',
93
+ 4 => 'TIMESTAMP',
94
+ 5 => 'VARIANT',
95
+ 6 => 'TIMESTAMP_LTZ',
96
+ 7 => 'TIMESTAMP_TZ',
97
+ 8 => 'TIMESTAMP_NTZ',
98
+ 9 => 'OBJECT',
99
+ 10 => 'ARRAY',
100
+ 11 => 'BINARY',
101
+ 12 => 'TIME',
102
+ 13 => 'BOOLEAN',
103
+ 14 => 'GEOGRAPHY',
104
+ 15 => 'GEOMETRY',
105
+ 16 => 'VECTOR'
106
+ }.freeze
107
+
108
+ FIXED = 0
109
+ REAL = 1
110
+ TEXT = 2
111
+ DATE = 3
112
+ TIMESTAMP = 4
113
+ VARIANT = 5
114
+ TIMESTAMP_LTZ = 6
115
+ TIMESTAMP_TZ = 7
116
+ TIMESTAMP_NTZ = 8
117
+ OBJECT = 9
118
+ ARRAY = 10
119
+ BINARY = 11
120
+ TIME = 12
121
+ BOOLEAN = 13
122
+ GEOGRAPHY = 14
123
+ GEOMETRY = 15
124
+ VECTOR = 16
125
+
126
+ JSON_TYPES = %w[VARIANT OBJECT ARRAY GEOGRAPHY GEOMETRY VECTOR].freeze
127
+ JSON_TYPE_SET = JSON_TYPES.to_h { |name| [name, true] }.freeze
128
+ LOWERCASE_LETTER = /[a-z]/
129
+ ISO_YEAR = CivilTime::ISO_YEAR
130
+ ISO_2 = CivilTime::ISO_2
131
+ ISO_3 = CivilTime::ISO_3
132
+ # `strftime('%z')` for whole-minute offsets in -14:00..+14:00. The hot
133
+ # path looks these up instead of formatting each timestamp's zone.
134
+ OFFSET_HHMM = begin
135
+ labels = {}
136
+ (-14 * 60..14 * 60).each do |minutes_total|
137
+ seconds = minutes_total * 60
138
+ sign = seconds.negative? ? '-' : '+'
139
+ hours, minutes = seconds.abs.divmod(3600)
140
+ labels[seconds] = "#{sign}#{ISO_2[hours]}#{ISO_2[minutes]}"
141
+ end
142
+ labels.freeze
143
+ end
144
+ # snowflake-sdk has no geography/geometry SqlType; query results report object.
145
+ QUERY_OBJECT_TYPES = %w[GEOGRAPHY GEOMETRY].freeze
146
+ NAIVE_TIMESTAMP_TYPES = %w[TIMESTAMP TIMESTAMP_NTZ].freeze
147
+
148
+ # Lazy handle. `connect` on the Ruby gem runs on the first query, matching
149
+ # Node returning the connection before its background connect finishes.
150
+ class SnowflakeClient
151
+ def initialize(config = nil)
152
+ @config = config.nil? ? {} : config.dup
153
+ @connection = nil
154
+ @closed = false
155
+ @lock = Mutex.new
156
+ end
157
+
158
+ def closed?
159
+ @lock.synchronize { @closed }
160
+ end
161
+
162
+ def connection
163
+ # Login holds the lock, so close waits and then closes the session this
164
+ # call stored. A later caller does not open another keep-alive session.
165
+ @lock.synchronize do
166
+ raise 'Snowflake connection is closed' if @closed
167
+ return @connection if @connection
168
+
169
+ @connection = open_connection
170
+ end
171
+ end
172
+
173
+ def cursor
174
+ connector = SnowflakeHelper.snowflake_connector
175
+ cursor_class = connector.respond_to?(:dict_cursor) ? connector.dict_cursor : nil
176
+ connection.cursor(cursor_class)
177
+ end
178
+
179
+ def close
180
+ connection = @lock.synchronize do
181
+ @closed = true
182
+ conn = @connection
183
+ @connection = nil
184
+ conn
185
+ end
186
+ return if connection.nil?
187
+
188
+ connection.close if connection.respond_to?(:close)
189
+ rescue StandardError
190
+ nil
191
+ end
192
+
193
+ private
194
+
195
+ def open_connection
196
+ SnowflakeHelper.snowflake_connector.connect(**connect_kwargs)
197
+ end
198
+
199
+ # Same fields Python passes to snowflake.connector.connect. Empty strings
200
+ # are omitted for extra keys; `false` and `0` are kept (they are truthy
201
+ # in Ruby and falsy-but-present in the Python `not in (None, "")` check).
202
+ def connect_kwargs
203
+ config = {}
204
+ @config.each { |key, value| config[key.to_s] = value }
205
+
206
+ username = config.delete('username')
207
+ account = blank_to_empty(config.delete('account'))
208
+ password = blank_to_empty(config.delete('password'))
209
+ user = if python_blank?(username)
210
+ blank_to_empty(config.delete('user'))
211
+ else
212
+ username
213
+ end
214
+
215
+ kwargs = {
216
+ account: account,
217
+ user: user,
218
+ password: password,
219
+ client_session_keep_alive: true
220
+ }
221
+ config.each do |key, value|
222
+ next if value.nil? || value == ''
223
+
224
+ kwargs[key.to_sym] = value
225
+ end
226
+ kwargs
227
+ end
228
+
229
+ def python_blank?(value)
230
+ value.nil? || value == false || value == 0 || value == ''
231
+ end
232
+
233
+ def blank_to_empty(value)
234
+ python_blank?(value) ? '' : value
235
+ end
236
+ end
237
+
238
+ # Snowflake session API (the same login and query-request calls snowflake-sdk
239
+ # makes). Password auth matches Node's createConnection. Row cells are
240
+ # decoded from the JSON rowset into the Ruby values `snowflake_value` already
241
+ # formats.
242
+ module SnowflakeSession
243
+ IN_PROGRESS = %w[333334 333001].freeze
244
+ TimeOfDay = Struct.new(:hour, :min, :sec)
245
+
246
+ module_function
247
+
248
+ def dict_cursor
249
+ :dict
250
+ end
251
+
252
+ def connect(**kwargs)
253
+ password = kwargs[:password]
254
+ if password.nil? || password == ''
255
+ raise ArgumentError, 'Snowflake password is required'
256
+ end
257
+
258
+ host, account_name = account_endpoint(kwargs[:account])
259
+ Session.new(
260
+ host: host,
261
+ account_name: account_name,
262
+ user: kwargs[:user].to_s,
263
+ password: password,
264
+ database: kwargs[:database],
265
+ warehouse: kwargs[:warehouse],
266
+ schema: kwargs[:schema],
267
+ role: kwargs[:role],
268
+ keep_alive: kwargs.fetch(:client_session_keep_alive, true)
269
+ ).login
270
+ end
271
+
272
+ # Node splits `account` on the first dot: the locator is ACCOUNT_NAME, and
273
+ # the rest is the region used to build `<locator>.<region>.snowflakecomputing.com`.
274
+ def account_endpoint(account)
275
+ account = account.to_s.strip.sub(%r{\Ahttps?://}i, '').sub(%r{/.*\z}, '')
276
+ if account.include?('snowflakecomputing.')
277
+ return [account, account.split('.').first]
278
+ end
279
+
280
+ locator, region = account.split('.', 2)
281
+ host = if region.nil? || region.empty? || region.casecmp('us-west-2').zero?
282
+ "#{locator}.snowflakecomputing.com"
283
+ elsif region.downcase.start_with?('cn-')
284
+ "#{locator}.#{region}.snowflakecomputing.cn"
285
+ else
286
+ "#{locator}.#{region}.snowflakecomputing.com"
287
+ end
288
+ [host, locator]
289
+ end
290
+
291
+ class Session
292
+ def initialize(host:, account_name:, user:, password:, database:, warehouse:, schema:, role:, keep_alive:)
293
+ @host = host
294
+ @account_name = account_name
295
+ @user = user
296
+ @password = password
297
+ @database = database
298
+ @warehouse = warehouse
299
+ @schema = schema
300
+ @role = role
301
+ @keep_alive = keep_alive
302
+ @token = nil
303
+ @timezone = 'UTC'
304
+ @sequence = 0
305
+ end
306
+
307
+ def login
308
+ params = { requestId: SecureRandom.uuid }
309
+ params[:warehouse] = @warehouse if present?(@warehouse)
310
+ params[:databaseName] = @database if present?(@database)
311
+ params[:schemaName] = @schema if present?(@schema)
312
+ params[:roleName] = @role if present?(@role)
313
+ body = request(
314
+ :post,
315
+ "/session/v1/login-request?#{URI.encode_www_form(params)}",
316
+ {
317
+ data: {
318
+ ACCOUNT_NAME: @account_name,
319
+ LOGIN_NAME: @user,
320
+ PASSWORD: @password,
321
+ CLIENT_APP_ID: 'RubyQuill',
322
+ CLIENT_APP_VERSION: '0.2.0',
323
+ CLIENT_ENVIRONMENT: { APPLICATION: 'Quill' },
324
+ SESSION_PARAMETERS: { CLIENT_SESSION_KEEP_ALIVE: @keep_alive == true }
325
+ }
326
+ }
327
+ )
328
+ unless body['success']
329
+ raise QueryError.new("Snowflake login failed: #{error_text(body)}", body)
330
+ end
331
+
332
+ @token = body.dig('data', 'token')
333
+ raise RuntimeError, 'Snowflake login failed: no session token' if @token.nil? || @token == ''
334
+
335
+ @timezone = session_timezone(body.dig('data', 'parameters'))
336
+ self
337
+ end
338
+
339
+ def cursor(_cursor_class = nil)
340
+ Cursor.new(self)
341
+ end
342
+
343
+ def close
344
+ return if @token.nil?
345
+
346
+ request(:post, "/session/logout-request?#{URI.encode_www_form(delete: true, requestId: SecureRandom.uuid)}", {}, auth: true)
347
+ rescue StandardError
348
+ nil
349
+ ensure
350
+ @token = nil
351
+ end
352
+
353
+ def query(sql)
354
+ request_id = SecureRandom.uuid
355
+ 60.times do
356
+ @sequence += 1
357
+ body = request(
358
+ :post,
359
+ "/queries/v1/query-request?#{URI.encode_www_form(requestId: request_id)}",
360
+ {
361
+ sqlText: sql.to_s,
362
+ asyncExec: false,
363
+ sequenceId: @sequence,
364
+ querySubmissionTime: (Time.now.to_f * 1000).to_i
365
+ },
366
+ auth: true
367
+ )
368
+ return body if body['success']
369
+
370
+ code = body['code'].to_s
371
+ raise QueryError.new(error_text(body), body) unless IN_PROGRESS.include?(code)
372
+
373
+ sleep 0.5
374
+ end
375
+ raise RuntimeError, 'Snowflake Query Error: query still running'
376
+ end
377
+
378
+ def download(url, headers)
379
+ uri = url.to_s.start_with?('http') ? URI(url) : URI("https://#{@host}#{url}")
380
+ response = http_request(:get, uri, nil, stringify_headers(headers))
381
+ unless response.is_a?(Net::HTTPSuccess)
382
+ raise RuntimeError, "Snowflake Query Error: result download failed (#{response.code})"
383
+ end
384
+
385
+ parse_rowset(decode_body(response))
386
+ end
387
+
388
+ def timezone
389
+ @timezone
390
+ end
391
+
392
+ private
393
+
394
+ def request(method, path, payload, auth: false)
395
+ headers = {
396
+ 'Accept' => 'application/json',
397
+ 'Content-Type' => 'application/json',
398
+ 'User-Agent' => 'QuillRuby/0.2.0'
399
+ }
400
+ headers['Authorization'] = %(Snowflake Token="#{@token}") if auth
401
+ response = http_request(method, URI("https://#{@host}#{path}"), JSON.generate(payload), headers)
402
+ parsed = JSON.parse(response.body)
403
+ return parsed if response.is_a?(Net::HTTPSuccess) || parsed.is_a?(Hash)
404
+
405
+ raise RuntimeError, "Snowflake request failed: #{response.code}"
406
+ rescue JSON::ParserError
407
+ raise RuntimeError, "Snowflake request failed: #{response.code}"
408
+ end
409
+
410
+ def http_request(method, uri, body, headers, limit = 3)
411
+ raise RuntimeError, 'Snowflake request failed: too many redirects' if limit <= 0
412
+
413
+ http = Net::HTTP.new(uri.host, uri.port)
414
+ http.use_ssl = uri.scheme == 'https'
415
+ http.open_timeout = 30
416
+ http.read_timeout = 180
417
+ klass = method == :get ? Net::HTTP::Get : Net::HTTP::Post
418
+ req = klass.new(uri)
419
+ headers.each { |key, value| req[key] = value }
420
+ req.body = body if body && method != :get
421
+ response = http.request(req)
422
+ if response.is_a?(Net::HTTPRedirection) && response['location']
423
+ location = URI(response['location'])
424
+ location = URI.join(uri, response['location']) if location.host.nil?
425
+ # A chunk redirect to S3 or GCS is only for this download. Storing
426
+ # that host would send the next query and logout there.
427
+ return http_request(method, location, body, headers, limit - 1)
428
+ end
429
+
430
+ response
431
+ end
432
+
433
+ def present?(value)
434
+ !value.nil? && value != ''
435
+ end
436
+
437
+ def session_timezone(parameters)
438
+ Array(parameters).each do |parameter|
439
+ name = parameter['name'] || parameter[:name]
440
+ return (parameter['value'] || parameter[:value]).to_s if name.to_s.casecmp('TIMEZONE').zero?
441
+ end
442
+ 'UTC'
443
+ end
444
+
445
+ def error_text(body)
446
+ body['message'] || body.dig('data', 'errorMessage') || body['code'] || 'unknown error'
447
+ end
448
+
449
+ def stringify_headers(headers)
450
+ return {} unless headers.is_a?(Hash)
451
+
452
+ headers.each_with_object({}) { |(key, value), built| built[key.to_s] = value.to_s }
453
+ end
454
+
455
+ def decode_body(response)
456
+ raw = response.body.to_s
457
+ encoding = response['content-encoding'].to_s.downcase
458
+ return gunzip(raw) if encoding.include?('gzip')
459
+
460
+ raw
461
+ end
462
+
463
+ def gunzip(raw)
464
+ gz = Zlib::GzipReader.new(StringIO.new(raw))
465
+ gz.read
466
+ ensure
467
+ gz&.close
468
+ end
469
+
470
+ def parse_rowset(text)
471
+ text = text.to_s
472
+ text = gunzip(text) if text.b.start_with?("\x1F\x8B".b)
473
+ parsed = JSON.parse(text)
474
+ return parsed if parsed.is_a?(Array)
475
+ return parsed['rowset'] if parsed.is_a?(Hash) && parsed['rowset'].is_a?(Array)
476
+ return JSON.parse(parsed) if parsed.is_a?(String)
477
+
478
+ parsed
479
+ rescue JSON::ParserError
480
+ JSON.parse("[#{text}]")
481
+ end
482
+ end
483
+
484
+ class Cursor
485
+ attr_reader :description
486
+
487
+ def initialize(session)
488
+ @session = session
489
+ @description = nil
490
+ @rows = []
491
+ end
492
+
493
+ def execute(sql)
494
+ body = @session.query(sql)
495
+ data = body['data'] || {}
496
+ columns = data['rowtype'] || data['rowType'] || []
497
+ if columns.empty?
498
+ @description = nil
499
+ @rows = []
500
+ return
501
+ end
502
+
503
+ @description = columns.map { |column| [column['name'].to_s, column['type'].to_s] }
504
+ rowset = Array(data['rowset'])
505
+ Array(data['chunks']).each do |chunk|
506
+ rowset.concat(Array(@session.download(chunk['url'], data['chunkHeaders'])))
507
+ end
508
+ @rows = rowset.map { |row| decode_row(row, columns) }
509
+ end
510
+
511
+ def fetchall
512
+ @rows
513
+ end
514
+
515
+ def close; end
516
+
517
+ private
518
+
519
+ def decode_row(row, columns)
520
+ values = row.is_a?(Hash) ? nil : Array(row)
521
+ columns.each_with_index.each_with_object({}) do |(column, index), built|
522
+ name = column['name'].to_s
523
+ raw = values.nil? ? (row[name] || row[name.to_sym]) : values[index]
524
+ built[name] = decode_cell(raw, column)
525
+ end
526
+ end
527
+
528
+ # JSON rowset cells are strings in Snowflake's wire form. Turn them into
529
+ # the Ruby values snowflake_value already renders like snowflake-sdk.
530
+ def decode_cell(raw, column)
531
+ return nil if raw.nil?
532
+
533
+ type_name = column['type']
534
+ type_name = type_name.to_s unless type_name.is_a?(String)
535
+ type_name = type_name.upcase if LOWERCASE_LETTER.match?(type_name)
536
+ case type_name
537
+ when 'FIXED', 'NUMBER', 'DECIMAL', 'NUMERIC', 'INT', 'INTEGER', 'BIGINT', 'SMALLINT', 'TINYINT', 'BYTEINT'
538
+ fixed_number(raw)
539
+ when 'REAL', 'FLOAT', 'FLOAT4', 'FLOAT8', 'DOUBLE'
540
+ SnowflakeHelper.send(:js_number, raw.is_a?(Float) ? raw : raw.to_f)
541
+ when 'BOOLEAN'
542
+ truthy?(raw)
543
+ when 'DATE'
544
+ format_unix_date(raw.to_i)
545
+ when 'TIME'
546
+ seconds, = epoch_parts(raw, column['scale'])
547
+ format_hms(seconds)
548
+ when 'TIMESTAMP_NTZ', 'TIMESTAMP'
549
+ seconds, nanos = epoch_parts(raw, column['scale'])
550
+ format_epoch_stamp(seconds, nanos, 0)
551
+ when 'TIMESTAMP_LTZ', 'TIMESTAMP_TZ', 'DATETIME'
552
+ zoned_timestamp(raw, column, type_name)
553
+ when 'BINARY', 'VARBINARY'
554
+ [raw.to_s].pack('H*').force_encoding(Encoding::ASCII_8BIT)
555
+ else
556
+ raw
557
+ end
558
+ end
559
+
560
+ def truthy?(raw)
561
+ return raw if raw == true || raw == false
562
+
563
+ text = raw.to_s
564
+ text == '1' || text.casecmp('TRUE').zero?
565
+ end
566
+
567
+ def zoned_timestamp(raw, column, type_name)
568
+ scale = column['scale']
569
+ if type_name == 'TIMESTAMP_TZ'
570
+ seconds, nanos, offset_minutes = timestamp_tz_parts(raw, scale)
571
+ offset_seconds = offset_minutes * 60
572
+ else
573
+ seconds, nanos = epoch_parts(raw, scale)
574
+ offset_seconds = timezone_offset(seconds)
575
+ end
576
+ "#{format_epoch_stamp(seconds, nanos, offset_seconds)} #{offset_label(offset_seconds)}"
577
+ end
578
+
579
+ # Result version > 0 packs TIMESTAMP_TZ as "<scaled seconds> <timezone index>".
580
+ # The index is minutes plus 1440.
581
+ def timestamp_tz_parts(raw, scale)
582
+ text = raw.to_s
583
+ if text.include?(' ')
584
+ seconds_text, index_text = text.split(' ', 2)
585
+ seconds, nanos = epoch_parts(seconds_text, scale)
586
+ [seconds, nanos, index_text.to_i - 1440]
587
+ else
588
+ seconds, nanos = epoch_parts(text, scale)
589
+ [seconds, nanos, 0]
590
+ end
591
+ end
592
+
593
+ def civil_from_epoch(seconds, nanos, offset_seconds)
594
+ local = Time.at(seconds, nanos.to_i / 1000, :usec).utc.getlocal(offset_seconds)
595
+ fraction = Rational(local.usec, 1_000_000)
596
+ DateTime.new(
597
+ local.year, local.month, local.day,
598
+ local.hour, local.min, local.sec + fraction,
599
+ Rational(offset_seconds, 86_400)
600
+ )
601
+ end
602
+
603
+ def timezone_offset(seconds)
604
+ name = @session.timezone.to_s
605
+ return 0 if name.empty? || name.casecmp('UTC').zero? || name.casecmp('Etc/UTC').zero?
606
+
607
+ require 'tzinfo'
608
+ TZInfo::Timezone.get(name).period_for_utc(Time.at(seconds).utc).observed_utc_offset
609
+ rescue LoadError, StandardError
610
+ 0
611
+ end
612
+
613
+ # Integer wire values are already whole seconds: multiplying and
614
+ # dividing by 10^scale cancels, and the fractional nanos are 0.
615
+ def epoch_parts(raw, scale)
616
+ text = raw.is_a?(String) ? raw : raw.to_s
617
+ number = parse_integer(text)
618
+ return [number, 0] unless number.nil?
619
+
620
+ scale = scale.to_i
621
+ value = BigDecimal(text)
622
+ factor = BigDecimal(10)**scale
623
+ scaled = value * factor
624
+ seconds = (scaled / factor).floor.to_i
625
+ remainder = scaled - (BigDecimal(seconds) * factor)
626
+ nanos = (remainder * (BigDecimal(10)**(9 - scale))).round.to_i
627
+ [seconds, nanos]
628
+ end
629
+
630
+ def fixed_number(raw)
631
+ text = raw.is_a?(String) ? raw : raw.to_s
632
+ number = parse_integer(text)
633
+ unless number.nil?
634
+ return number if number.abs < SnowflakeHelper::MAX_SAFE_INTEGER
635
+
636
+ return number.to_f
637
+ end
638
+
639
+ SnowflakeHelper.send(:js_number, BigDecimal(text))
640
+ end
641
+
642
+ INTEGER_TEXT = /\A[+-]?\d+\z/
643
+
644
+ def parse_integer(text)
645
+ return nil unless INTEGER_TEXT.match?(text)
646
+
647
+ text.to_i
648
+ end
649
+
650
+ def format_unix_date(days)
651
+ year, month, day = CivilTime.civil_from_days(days)
652
+ return format('%04d-%02d-%02d', year, month, day) unless year.between?(0, 9999)
653
+
654
+ CivilTime.iso_date(year, month, day)
655
+ end
656
+
657
+ def format_hms(seconds)
658
+ hour, remainder = seconds.divmod(3600)
659
+ minute, second = remainder.divmod(60)
660
+ if hour.negative? || hour > 59
661
+ return format('%02d:%02d:%02d', hour, minute, second)
662
+ end
663
+
664
+ "#{CivilTime::ISO_2[hour]}:#{CivilTime::ISO_2[minute]}:#{CivilTime::ISO_2[second]}"
665
+ end
666
+
667
+ def format_epoch_stamp(seconds, nanos, offset_seconds)
668
+ milli = nanos / 1_000_000
669
+ local = seconds + offset_seconds
670
+ if milli >= 1000 || milli.negative?
671
+ carry, milli = milli.divmod(1000)
672
+ local += carry
673
+ end
674
+ year, month, day, hour, minute, second = CivilTime.epoch_parts(local)
675
+ if year.between?(0, 9999)
676
+ return "#{CivilTime.iso_date(year, month, day)} #{CivilTime::ISO_2[hour]}:#{CivilTime::ISO_2[minute]}:#{CivilTime::ISO_2[second]}.#{CivilTime::ISO_3[milli]}"
677
+ end
678
+
679
+ format('%04d-%02d-%02d %02d:%02d:%02d.%03d', year, month, day, hour, minute, second, milli)
680
+ end
681
+
682
+ def offset_label(offset_seconds)
683
+ sign = offset_seconds.negative? ? '-' : '+'
684
+ total = offset_seconds.abs
685
+ hours, remainder = total.divmod(3600)
686
+ minutes, seconds = remainder.divmod(60)
687
+ text = format('%s%02d%02d', sign, hours, minutes)
688
+ seconds.nonzero? ? "#{text}#{format('%02d', seconds)}" : text
689
+ end
690
+ end
691
+ end
692
+
693
+ class << self
694
+ def snowflake_data_type_to_postgres_oid(type_name)
695
+ normalized = normalize_type_name(type_name)
696
+ return nil if normalized.nil?
697
+
698
+ POSTGRES_SNOWFLAKE_MAP[normalized]
699
+ end
700
+
701
+ # OID as Node computes it from col.getType() on a query result.
702
+ def query_result_type_to_postgres_oid(type_name)
703
+ normalized = normalize_type_name(type_name)
704
+ normalized = 'OBJECT' if QUERY_OBJECT_TYPES.include?(normalized)
705
+ return nil if normalized.nil?
706
+
707
+ POSTGRES_SNOWFLAKE_MAP[normalized]
708
+ end
709
+
710
+ def snowflake_connector
711
+ SnowflakeSession
712
+ end
713
+
714
+ def format_snowflake_config(connection_string)
715
+ parsed = parse_snowflake_url(connection_string)
716
+ parts = parsed.path.to_s.split('/')
717
+ {
718
+ account: parsed.host,
719
+ username: percent_decode(parsed.user),
720
+ password: percent_decode(parsed.password),
721
+ database: parts.length > 1 ? parts[1].to_s : '',
722
+ warehouse: parts.length > 2 ? parts[2].to_s : ''
723
+ }
724
+ end
725
+
726
+ def connect_to_snowflake(config)
727
+ SnowflakeClient.new(config)
728
+ end
729
+
730
+ def disconnect_from_snowflake(client)
731
+ return if client.nil?
732
+
733
+ client.close if client.respond_to?(:close)
734
+ end
735
+
736
+ # Exact classes the connector returns. `type(value) is datetime` in the
737
+ # Python port; `is_a?` walks ancestors and dominated the 100k-row pass.
738
+ EXACT_KIND = {
739
+ Integer => :passthrough,
740
+ TrueClass => :passthrough,
741
+ FalseClass => :passthrough,
742
+ String => :string,
743
+ Float => :float,
744
+ BigDecimal => :decimal,
745
+ DateTime => :datetime,
746
+ Date => :date,
747
+ Time => :time,
748
+ SnowflakeSession::TimeOfDay => :tod
749
+ }.freeze
750
+
751
+ def snowflake_value(value, type_name = nil)
752
+ if value.nil?
753
+ # TIME has no JS type; snowflake-sdk getNullValue() is the string "NULL".
754
+ return 'NULL' if fast_name(type_name) == 'TIME'
755
+
756
+ return nil
757
+ end
758
+
759
+ case EXACT_KIND[value.class]
760
+ when :passthrough
761
+ value
762
+ when :string
763
+ snowflake_string(value, type_name)
764
+ when :float, :decimal
765
+ js_number(value)
766
+ when :datetime, :date
767
+ value.class.equal?(Date) ? format_date(value) : format_timestamp(value)
768
+ when :time
769
+ fast_name(type_name) == 'TIME' ? format_time(value) : format_timestamp(value)
770
+ when :tod
771
+ format_time(value)
772
+ else
773
+ snowflake_other(value, type_name)
774
+ end
775
+ end
776
+
777
+ def run_query_snowflake(sql, client)
778
+ cursor = client.cursor
779
+ begin
780
+ cursor.execute(sql)
781
+ description = cursor.description
782
+ if description.nil? || description.empty?
783
+ description = []
784
+ rows = []
785
+ else
786
+ rows = cursor.fetchall || []
787
+ end
788
+ ensure
789
+ begin
790
+ cursor.close if cursor.respond_to?(:close)
791
+ rescue StandardError
792
+ nil
793
+ end
794
+ end
795
+
796
+ shape_result(description, rows)
797
+ end
798
+
799
+ def get_schemas_snowflake(client)
800
+ sql = <<~SQL
801
+ SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA
802
+ WHERE SCHEMA_NAME != 'INFORMATION_SCHEMA'
803
+ SQL
804
+ results = run_query_snowflake(sql, client)
805
+ results[:rows].map { |row| row_value(row, 'SCHEMA_NAME') }
806
+ end
807
+
808
+ def get_tables_by_schema_snowflake(client, schema_names)
809
+ names = schema_names.is_a?(Array) ? schema_names : [schema_names]
810
+ names.flat_map do |schema|
811
+ query = <<~SQL
812
+ SELECT
813
+ TABLE_NAME as "tableName",
814
+ TABLE_SCHEMA as "schemaName"
815
+ FROM INFORMATION_SCHEMA.TABLES
816
+ WHERE TABLE_SCHEMA = '#{schema}';
817
+ SQL
818
+ results = run_query_snowflake(query, client)
819
+ results[:rows].map do |row|
820
+ {
821
+ tableName: row_value(row, 'tableName'),
822
+ schemaName: row_value(row, 'schemaName')
823
+ }
824
+ end
825
+ end
826
+ end
827
+
828
+ def get_columns_by_table_snowflake(client, schema_name, table_name)
829
+ sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '#{schema_name}' AND TABLE_NAME = '#{table_name}'"
830
+ results = run_query_snowflake(sql, client)
831
+ results[:rows].map { |row| row_value(row, 'COLUMN_NAME') }
832
+ end
833
+
834
+ # Node's unused name-based heuristic, including TABLE_NAME = schemaName.
835
+ def get_foreign_keys_snowflake(client, schema_name, table_name, primary_key)
836
+ depluralized = snowflake_depluralize(table_name)
837
+ capitalized = snowflake_capitalize(primary_key)
838
+ sql = <<~SQL
839
+ SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
840
+ WHERE TABLE_SCHEMA = '#{schema_name}'
841
+ AND TABLE_NAME = '#{schema_name}'
842
+ and TABLE_NAME != '#{table_name}'
843
+ and (COLUMN_NAME = '#{primary_key}'
844
+ or COLUMN_NAME = '#{depluralized}_#{primary_key}'
845
+ or COLUMN_NAME = '#{depluralized}#{capitalized}')
846
+ SQL
847
+ foreign_keys = column_names(run_query_snowflake(sql, client))
848
+ foreign_keys = foreign_keys.reject { |key| key == 'id' || key == '_id_' }.uniq
849
+ if foreign_keys.empty?
850
+ sql = <<~SQL
851
+ SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
852
+ WHERE TABLE_SCHEMA = '#{schema_name}'
853
+ AND TABLE_NAME = '#{schema_name}'
854
+ and TABLE_NAME != '#{table_name}'
855
+ and (COLUMN_NAME like '#{depluralized}%'
856
+ or column_name like '%\\_id'
857
+ or column_name like '%Id'
858
+ or COLUMN_NAME like '%\\_#{primary_key}'
859
+ or COLUMN_NAME like '%#{capitalized}')
860
+ SQL
861
+ foreign_keys = column_names(run_query_snowflake(sql, client)).uniq
862
+ end
863
+ foreign_keys
864
+ end
865
+
866
+ def get_schema_column_info_snowflake(client, _schema_name, table_names)
867
+ table_names.map do |table|
868
+ table_schema, table_name = table_identity(table)
869
+ query = <<~SQL
870
+ SELECT
871
+ COLUMN_NAME as "columnName", DATA_TYPE as "dataType"
872
+ FROM INFORMATION_SCHEMA.COLUMNS
873
+ WHERE TABLE_SCHEMA = '#{table_schema}' AND TABLE_NAME = '#{table_name}';
874
+ SQL
875
+ results = run_query_snowflake(query, client)
876
+ {
877
+ tableName: "#{table_schema}.#{table_name}",
878
+ displayName: "#{table_schema}.#{table_name}",
879
+ columns: results[:rows].map do |row|
880
+ data_type = row_value(row, 'dataType')
881
+ column_name = row_value(row, 'columnName')
882
+ {
883
+ columnName: column_name,
884
+ displayName: column_name,
885
+ # Node looks up row.dataType without toUpperCase().
886
+ dataTypeID: POSTGRES_SNOWFLAKE_MAP[data_type],
887
+ fieldType: data_type
888
+ }
889
+ end
890
+ }
891
+ end
892
+ end
893
+
894
+ def row_value(row, key)
895
+ return nil unless row.is_a?(Hash)
896
+ return row[key] if row.key?(key)
897
+
898
+ symbol = key.to_sym
899
+ return row[symbol] if row.key?(symbol)
900
+
901
+ string = key.to_s
902
+ return row[string] if row.key?(string)
903
+
904
+ nil
905
+ end
906
+
907
+ private
908
+
909
+ def shape_result(description, rows)
910
+ fields = []
911
+ names = []
912
+ type_names = []
913
+ description.each do |column|
914
+ name = column[0]
915
+ type_name = column.length > 1 ? column[1] : nil
916
+ reported = FIELD_ID_TO_NAME.fetch(type_name, type_name)
917
+ names << name
918
+ type_names << reported
919
+ fields << {
920
+ name: name,
921
+ dataTypeID: query_result_type_to_postgres_oid(reported)
922
+ }
923
+ end
924
+
925
+ processed = Array(rows).map do |row|
926
+ names.each_with_index.each_with_object({}) do |(name, index), built|
927
+ raw = row.is_a?(Hash) ? row_value(row, name) : row[index]
928
+ built[name.to_s] = snowflake_value(raw, type_names[index])
929
+ end
930
+ end
931
+
932
+ { fields: fields, rows: processed }
933
+ end
934
+
935
+ def column_names(results)
936
+ results[:rows].map { |row| row_value(row, 'COLUMN_NAME') }
937
+ end
938
+
939
+ def table_identity(table)
940
+ schema_name = table[:schemaName] || table['schemaName'] || table[:schema_name] || table['schema_name']
941
+ table_name = table[:tableName] || table['tableName'] || table[:table_name] || table['table_name']
942
+ [schema_name, table_name]
943
+ end
944
+
945
+ def normalize_type_name(type_name)
946
+ fast_name(type_name)
947
+ end
948
+
949
+ # Already-uppercase type names are the common case. String#upcase allocates
950
+ # even when every character is already upper.
951
+ def fast_name(type_name)
952
+ return nil if type_name.nil?
953
+ return FIELD_ID_TO_NAME[type_name] if type_name.is_a?(Integer)
954
+
955
+ name = type_name.is_a?(String) ? type_name : type_name.to_s
956
+ return nil if name.empty?
957
+
958
+ LOWERCASE_LETTER.match?(name) ? name.upcase : name
959
+ end
960
+
961
+ def parse_jsonish(value)
962
+ return value if value.is_a?(Hash) || value.is_a?(Array)
963
+ return value unless value.is_a?(String)
964
+
965
+ JSON.parse(value)
966
+ rescue JSON::ParserError, TypeError
967
+ value
968
+ end
969
+
970
+ def snowflake_string(value, type_name)
971
+ if value.encoding != Encoding::ASCII_8BIT
972
+ name = type_name.is_a?(String) ? type_name : type_name.to_s
973
+ return value if !LOWERCASE_LETTER.match?(name) && !JSON_TYPE_SET[name]
974
+ end
975
+
976
+ normalized = fast_name(type_name)
977
+ return parse_jsonish(value) if JSON_TYPE_SET[normalized]
978
+ return buffer(value) if value.encoding == Encoding::ASCII_8BIT && (normalized == 'BINARY' || normalized == 'VARBINARY')
979
+
980
+ value
981
+ end
982
+
983
+ # Subclasses and duck-typed times (tests pass their own Struct).
984
+ def snowflake_other(value, type_name)
985
+ normalized = normalize_type_name(type_name)
986
+ return parse_jsonish(value) if JSON_TYPE_SET[normalized]
987
+ return buffer(value) if binary_string?(value) && (normalized == 'BINARY' || normalized == 'VARBINARY')
988
+ return format_time(value) if normalized == 'TIME' && (value.is_a?(Time) || time_only?(value))
989
+ return value if value == true || value == false
990
+ return value if value.is_a?(Integer)
991
+ return value if value.is_a?(String)
992
+ return js_number(value) if value.is_a?(BigDecimal) || value.is_a?(Float)
993
+ return format_timestamp(value) if value.is_a?(Time) || value.is_a?(DateTime)
994
+ return format_date(value) if value.is_a?(Date)
995
+ return format_time(value) if time_only?(value)
996
+ return buffer(value) if binary_string?(value)
997
+
998
+ value
999
+ end
1000
+
1001
+ def js_number(value)
1002
+ klass = value.class
1003
+ return value if klass.equal?(Integer) || klass.equal?(TrueClass) || klass.equal?(FalseClass)
1004
+
1005
+ if klass.equal?(BigDecimal)
1006
+ whole = value.to_i
1007
+ return whole if whole.abs < MAX_SAFE_INTEGER && value == whole
1008
+
1009
+ value = value.to_f
1010
+ elsif !klass.equal?(Float)
1011
+ value = value.is_a?(String) ? Float(value) : value.to_f
1012
+ end
1013
+ return value unless value.finite?
1014
+
1015
+ whole = value.to_i
1016
+ return whole if whole.abs < MAX_SAFE_INTEGER && value == whole
1017
+
1018
+ value
1019
+ end
1020
+
1021
+ # DateTime with offset 0 stands in for Python's naive datetime (no
1022
+ # suffix). Ruby Time always has an offset, so it always prints one.
1023
+ def format_timestamp(value)
1024
+ if value.class.equal?(DateTime)
1025
+ frac = value.sec_fraction
1026
+ milli = frac.zero? ? 0 : (frac * 1000).to_i
1027
+ rendered = stamp_text(value.year, value.month, value.day, value.hour, value.min, value.sec, milli)
1028
+ return rendered if value.offset.zero?
1029
+
1030
+ label = OFFSET_HHMM[(value.offset * 86_400).to_i] || tz_offset(value)
1031
+ return "#{rendered} #{label}"
1032
+ end
1033
+ if value.class.equal?(Time)
1034
+ rendered = stamp_text(value.year, value.month, value.day, value.hour, value.min, value.sec, value.usec / 1000)
1035
+ label = OFFSET_HHMM[value.utc_offset] || tz_offset(value)
1036
+ return "#{rendered} #{label}"
1037
+ end
1038
+
1039
+ year, month, day, hour, minute, second, usec = timestamp_parts(value)
1040
+ rendered = stamp_text(year, month, day, hour, minute, second, usec / 1000)
1041
+ return rendered unless timezone_aware?(value)
1042
+
1043
+ "#{rendered} #{tz_offset(value)}"
1044
+ end
1045
+
1046
+ def stamp_text(year, month, day, hour, minute, second, milli)
1047
+ if year.negative? || year > 9999 || month > 12 || day > 31 || hour > 23 || minute > 59 || second > 59 || milli.negative? || milli > 999
1048
+ return format('%04d-%02d-%02d %02d:%02d:%02d.%03d', year, month, day, hour, minute, second, milli)
1049
+ end
1050
+
1051
+ "#{ISO_YEAR[year]}-#{ISO_2[month]}-#{ISO_2[day]} #{ISO_2[hour]}:#{ISO_2[minute]}:#{ISO_2[second]}.#{ISO_3[milli]}"
1052
+ end
1053
+
1054
+ def format_date(value)
1055
+ year = value.year
1056
+ month = value.month
1057
+ day = value.day
1058
+ return format('%04d-%02d-%02d', year, month, day) if year.negative? || year > 9999
1059
+
1060
+ "#{ISO_YEAR[year]}-#{ISO_2[month]}-#{ISO_2[day]}"
1061
+ end
1062
+
1063
+ def format_time(value)
1064
+ minute = value.respond_to?(:min) ? value.min : value.minute
1065
+ second = value.respond_to?(:sec) ? value.sec : value.second
1066
+ hour = value.hour
1067
+ return format('%02d:%02d:%02d', hour, minute, second) if hour > 23 || minute > 59 || second > 59
1068
+
1069
+ "#{ISO_2[hour]}:#{ISO_2[minute]}:#{ISO_2[second]}"
1070
+ end
1071
+
1072
+ def timestamp_parts(value)
1073
+ minute = value.respond_to?(:min) ? value.min : value.minute
1074
+ second = value.respond_to?(:sec) ? value.sec : value.second
1075
+ usec = if value.respond_to?(:usec)
1076
+ value.usec
1077
+ elsif value.respond_to?(:sec_fraction)
1078
+ (value.sec_fraction * 1_000_000).to_i
1079
+ else
1080
+ 0
1081
+ end
1082
+ [value.year, value.month, value.day, value.hour, minute, second, usec.to_i]
1083
+ end
1084
+
1085
+ def timezone_aware?(value)
1086
+ return !value.offset.zero? if value.is_a?(DateTime)
1087
+ return true if value.is_a?(Time)
1088
+
1089
+ value.respond_to?(:tzinfo) && !value.tzinfo.nil?
1090
+ end
1091
+
1092
+ # Python `strftime('%z')`: `+0000`, `-0500`, and rare `+000030` / micros.
1093
+ def tz_offset(value)
1094
+ total = offset_microseconds(value)
1095
+ sign = total.negative? ? '-' : '+'
1096
+ total = total.abs
1097
+ seconds_total, frac = total.divmod(1_000_000)
1098
+ hours, remainder = seconds_total.divmod(3600)
1099
+ minutes, seconds = remainder.divmod(60)
1100
+ text = format('%s%02d%02d', sign, hours, minutes)
1101
+ if frac.nonzero?
1102
+ format('%s%02d.%06d', text, seconds, frac)
1103
+ elsif seconds.nonzero?
1104
+ format('%s%02d', text, seconds)
1105
+ else
1106
+ text
1107
+ end
1108
+ end
1109
+
1110
+ def offset_microseconds(value)
1111
+ if value.is_a?(DateTime)
1112
+ (value.offset * 86_400 * 1_000_000).round.to_i
1113
+ elsif value.respond_to?(:utc_offset)
1114
+ value.utc_offset.to_i * 1_000_000
1115
+ else
1116
+ 0
1117
+ end
1118
+ end
1119
+
1120
+ def time_only?(value)
1121
+ return false if value.is_a?(Time) || value.is_a?(Date) || value.is_a?(String) || value.is_a?(Numeric)
1122
+
1123
+ value.respond_to?(:hour) && (value.respond_to?(:min) || value.respond_to?(:minute)) && !value.respond_to?(:year)
1124
+ end
1125
+
1126
+ def binary_string?(value)
1127
+ value.is_a?(String) && value.encoding == Encoding::ASCII_8BIT
1128
+ end
1129
+
1130
+ def buffer(value)
1131
+ { 'type' => 'Buffer', 'data' => value.b.bytes }
1132
+ end
1133
+
1134
+ def parse_snowflake_url(connection_string)
1135
+ parsed = URI.parse(connection_string.to_s)
1136
+ if parsed.scheme.nil? || parsed.scheme.empty? || parsed.host.nil? || parsed.host.empty?
1137
+ raise ArgumentError, "Invalid URL: #{connection_string}"
1138
+ end
1139
+ parsed
1140
+ rescue URI::InvalidURIError
1141
+ raise ArgumentError, "Invalid URL: #{connection_string}"
1142
+ end
1143
+
1144
+ # decodeURIComponent, not form decoding: "+" stays "+".
1145
+ def percent_decode(text)
1146
+ return '' if text.nil? || text.empty?
1147
+
1148
+ text.gsub(/%([0-9A-Fa-f]{2})/) { [Regexp.last_match(1).hex].pack('C') }.force_encoding(Encoding::UTF_8)
1149
+ end
1150
+
1151
+ # Node's textProcessing.depluralize: one trailing "s", and "ies" -> "y".
1152
+ def snowflake_depluralize(text)
1153
+ text = text.to_s
1154
+ return "#{text[0...-3]}y" if text.end_with?('ies')
1155
+ return text[0...-1].to_s if text.end_with?('s')
1156
+
1157
+ text
1158
+ end
1159
+
1160
+ def snowflake_capitalize(text)
1161
+ text = text.to_s
1162
+ return text if text.empty?
1163
+
1164
+ text[0].upcase + text[1..]
1165
+ end
1166
+ end
1167
+ end