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,1346 @@
1
+ require 'base64'
2
+ require 'bigdecimal'
3
+ require 'date'
4
+ require 'json'
5
+ require_relative 'civil_time'
6
+ require 'net/http'
7
+ require 'openssl'
8
+ require 'time'
9
+ require 'uri'
10
+
11
+ # BigQuery driver, mirroring node-sdk/src/db/BigQuery.ts and the Node-parity
12
+ # cell shapes in python-sdk/quillsql/db/bigquery.py.
13
+ #
14
+ # Query cells match JSON.stringify of the Node client: NUMERIC is a Big.js
15
+ # string, whole floats inside MAX_SAFE_INTEGER are integers, dates and times
16
+ # are `{value: ...}` objects, and BYTES is `{type: "Buffer", data: [...]}`.
17
+ # `dataTypeID` is inferred from the first non-null cell, same as Node.
18
+ # An empty row set returns no fields.
19
+ #
20
+ # Catalog reads use Node's INFORMATION_SCHEMA SQL (Python lists datasets and
21
+ # tables through the metadata API instead). Foreign keys follow Node's
22
+ # depluralize rules. Column OIDs use Python's map, which is the same table
23
+ # Node declares; Node then looks that OID up again and always falls through
24
+ # to varchar.
25
+ #
26
+ # The Google client is not required. `connect_to_bigquery` returns a REST
27
+ # client built from one config hash. Service-account auth runs only when a
28
+ # query or dataset list is issued.
29
+ module BigQueryHelper
30
+ # A request BigQuery rejected, with the code, reason and location it sent.
31
+ class RequestError < RuntimeError
32
+ attr_reader :code, :reason, :location
33
+
34
+ def initialize(message, sent)
35
+ super(message)
36
+ first = Array(sent['errors']).first || {}
37
+ @code = sent['code']
38
+ @reason = first['reason']
39
+ @location = first['location']
40
+ end
41
+ end
42
+
43
+ # JS Number.MAX_SAFE_INTEGER. Whole floats with abs <= this stay Integer
44
+ # so JSON is `20`, not `20.0`.
45
+ MAX_SAFE_INTEGER = 9_007_199_254_740_991
46
+ VARCHAR_OID = 1043
47
+
48
+ # Python's convert_bigquery_to_postgres. Standard SQL spellings from
49
+ # INFORMATION_SCHEMA (`INT64`, `FLOAT64`, `BOOLEAN`, `STRING`) alias onto
50
+ # the legacy names the map was written with.
51
+ TYPE_TO_OID = {
52
+ 'VARCHAR' => 1043,
53
+ 'STRING' => 1043,
54
+ 'INTEGER' => 23,
55
+ 'INT64' => 23,
56
+ 'FLOAT' => 700,
57
+ 'FLOAT64' => 700,
58
+ 'TIMESTAMP' => 1114,
59
+ 'DATE' => 1082,
60
+ 'BOOL' => 16,
61
+ 'BOOLEAN' => 16
62
+ }.freeze
63
+
64
+ DATE_RE = /\A\d{4}-\d{2}-\d{2}\z/
65
+ DATE_SLASH_RE = /\A\d{2}\/\d{2}\/\d{2,4}\z/
66
+ TIMESTAMP_RE = /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?\z/
67
+ TIMESTAMPTZ_RE = /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z\z/
68
+ TIME_RE = /\A\d{2}:\d{2}:\d{2}\z/
69
+
70
+ OAUTH_TOKEN_URL = 'https://oauth2.googleapis.com/token'
71
+ BIGQUERY_SCOPE = 'https://www.googleapis.com/auth/bigquery'
72
+ API_HOST = 'https://bigquery.googleapis.com'
73
+
74
+ # Wall-clock time with no date. REST TIME values and tests both use this.
75
+ Clock = Struct.new(:hour, :min, :sec, :usec)
76
+
77
+ QueryField = Struct.new(:name, :field_type, :mode, :fields, keyword_init: true)
78
+
79
+ class QueryResult
80
+ attr_reader :schema, :rows
81
+
82
+ def initialize(schema, rows)
83
+ @schema = schema
84
+ @rows = rows
85
+ end
86
+ end
87
+
88
+ # REST client. `query` returns native Ruby values; `run_query_bigquery`
89
+ # turns those into the Node JSON shapes. Tests pass any object that
90
+ # implements `query` and skip this class.
91
+ class Client
92
+ attr_reader :project, :dataset_name, :credentials, :using_connection_string
93
+
94
+ def initialize(project:, dataset_name:, credentials:, using_connection_string:)
95
+ @project = project
96
+ @dataset_name = dataset_name
97
+ @credentials = credentials
98
+ @using_connection_string = using_connection_string
99
+ @access_token = nil
100
+ @token_expiry = 0
101
+ end
102
+
103
+ def query(sql)
104
+ payload = fetch_query_payload(sql)
105
+ fields = normalize_schema(payload_value(payload, 'schema'))
106
+ QueryResult.new(fields, native_rows(fields, payload_value(payload, 'rows') || []))
107
+ end
108
+
109
+ def list_datasets
110
+ ids = []
111
+ page = nil
112
+ seen = {}
113
+ loop do
114
+ params = {}
115
+ params[:pageToken] = page if page && !page.empty?
116
+ data = api_json(:get, "/bigquery/v2/projects/#{path_escape(@project)}/datasets", params)
117
+ Array(data['datasets']).each do |dataset|
118
+ id = dataset.dig('datasetReference', 'datasetId')
119
+ ids << id unless id.nil?
120
+ end
121
+ page = data['nextPageToken']
122
+ break if page.nil? || page.empty? || seen[page]
123
+
124
+ seen[page] = true
125
+ end
126
+ ids
127
+ end
128
+
129
+ def fetch_query_payload(sql)
130
+ data = api_json(:post, "/bigquery/v2/projects/#{path_escape(@project)}/queries", {
131
+ query: sql,
132
+ useLegacySql: false,
133
+ timeoutMs: 60_000
134
+ })
135
+ job = data['jobReference'] || {}
136
+ polls = 0
137
+ while data['jobComplete'] == false
138
+ polls += 1
139
+ raise 'BigQuery query did not complete' if polls > 60
140
+
141
+ sleep 0.5
142
+ data = api_json(:get, query_results_path(job), compact_params(timeoutMs: 60_000, location: job['location']))
143
+ end
144
+ rows = Array(data['rows'])
145
+ schema = data['schema']
146
+ seen = {}
147
+ while (token = data['pageToken']) && !token.empty? && !seen[token]
148
+ seen[token] = true
149
+ data = api_json(:get, query_results_path(job), compact_params(pageToken: token, location: job['location']))
150
+ schema ||= data['schema']
151
+ rows.concat(Array(data['rows']))
152
+ end
153
+ { 'schema' => schema, 'rows' => rows }
154
+ end
155
+
156
+ private
157
+
158
+ def query_results_path(job)
159
+ project = job['projectId'] || @project
160
+ "/bigquery/v2/projects/#{path_escape(project)}/queries/#{path_escape(job['jobId'])}"
161
+ end
162
+
163
+ def compact_params(params)
164
+ params.reject { |_key, value| value.nil? || (value.respond_to?(:empty?) && value.empty?) }
165
+ end
166
+
167
+ def payload_value(payload, key)
168
+ return nil unless payload.is_a?(Hash)
169
+ return payload[key] if payload.key?(key)
170
+
171
+ symbol = key.to_sym
172
+ return payload[symbol] if payload.key?(symbol)
173
+
174
+ nil
175
+ end
176
+
177
+ def normalize_schema(schema)
178
+ list = if schema.is_a?(Hash)
179
+ schema['fields'] || schema[:fields] || []
180
+ else
181
+ Array(schema)
182
+ end
183
+ list.map { |field| normalize_field(field) }
184
+ end
185
+
186
+ def normalize_field(field)
187
+ if field.is_a?(QueryField)
188
+ return QueryField.new(
189
+ name: field.name.to_s,
190
+ field_type: field.field_type.to_s,
191
+ mode: field.mode,
192
+ fields: normalize_schema(field.fields)
193
+ )
194
+ end
195
+
196
+ QueryField.new(
197
+ name: attr_of(field, :name).to_s,
198
+ field_type: (attr_of(field, :field_type, :type) || '').to_s,
199
+ mode: attr_of(field, :mode),
200
+ fields: normalize_schema(attr_of(field, :fields) || [])
201
+ )
202
+ end
203
+
204
+ def attr_of(field, *keys)
205
+ BigQueryHelper.field_attr(field, *keys)
206
+ end
207
+
208
+ def native_rows(fields, rows)
209
+ type_names = {}
210
+ repeated_fields = {}
211
+ Array(rows).map { |row| native_row(fields, row, type_names, repeated_fields) }
212
+ end
213
+
214
+ def native_row(fields, row, type_names = {}, repeated_fields = {})
215
+ cells = if row.is_a?(Hash) && (row.key?('f') || row.key?(:f))
216
+ row['f'] || row[:f]
217
+ else
218
+ nil
219
+ end
220
+ return row if cells.nil? && row.is_a?(Hash)
221
+
222
+ fields.each_with_index.each_with_object({}) do |(field, index), built|
223
+ built[field.name] = rest_native(cell_value(cells[index]), field, type_names, repeated_fields)
224
+ end
225
+ end
226
+
227
+ def cached_type(field, type_names)
228
+ name = type_names[field.object_id]
229
+ return name unless name.nil?
230
+
231
+ type_names[field.object_id] = field.field_type.to_s.upcase
232
+ end
233
+
234
+ def cell_value(cell)
235
+ return nil unless cell.is_a?(Hash)
236
+ return cell['v'] if cell.key?('v')
237
+ return cell[:v] if cell.key?(:v)
238
+
239
+ nil
240
+ end
241
+
242
+ def rest_native(value, field, type_names = {}, repeated_fields = {})
243
+ return nil if value.nil?
244
+ return rest_repeated(value, field, type_names, repeated_fields) if field.mode == 'REPEATED'
245
+
246
+ rest_scalar(value, field, type_names, repeated_fields)
247
+ end
248
+
249
+ def rest_repeated(value, field, type_names = {}, repeated_fields = {})
250
+ return nil unless value.is_a?(Array)
251
+
252
+ scalar = repeated_fields[field.object_id] ||= QueryField.new(
253
+ name: field.name, field_type: field.field_type, mode: 'NULLABLE', fields: field.fields
254
+ )
255
+ value.map do |item|
256
+ raw = item.is_a?(Hash) && (item.key?('v') || item.key?(:v)) ? cell_value(item) : item
257
+ rest_scalar(raw, scalar, type_names, repeated_fields)
258
+ end
259
+ end
260
+
261
+ def rest_scalar(value, field, type_names = {}, repeated_fields = {})
262
+ return nil if value.nil?
263
+
264
+ case cached_type(field, type_names)
265
+ when 'RECORD', 'STRUCT'
266
+ rest_record(value, field, type_names, repeated_fields)
267
+ when 'INTEGER', 'INT64'
268
+ rest_integer(value)
269
+ when 'FLOAT', 'FLOAT64'
270
+ rest_float(value)
271
+ when 'NUMERIC', 'BIGNUMERIC'
272
+ value.is_a?(BigDecimal) || value.is_a?(String) ? value : BigDecimal(value.to_s)
273
+ when 'BOOLEAN', 'BOOL'
274
+ rest_bool(value)
275
+ when 'DATE'
276
+ rest_date(value)
277
+ when 'DATETIME'
278
+ rest_datetime(value)
279
+ when 'TIME'
280
+ rest_time(value)
281
+ when 'TIMESTAMP'
282
+ rest_timestamp(value)
283
+ when 'BYTES'
284
+ rest_bytes(value)
285
+ when 'JSON'
286
+ value.is_a?(String) ? value : value
287
+ else
288
+ value
289
+ end
290
+ end
291
+
292
+ def rest_record(value, field, type_names = {}, repeated_fields = {})
293
+ children = field.fields || []
294
+ cells = value.is_a?(Hash) && (value.key?('f') || value.key?(:f)) ? (value['f'] || value[:f]) : nil
295
+ if cells
296
+ return children.each_with_index.each_with_object({}) do |(child, index), built|
297
+ built[child.name] = rest_native(cell_value(cells[index]), child, type_names, repeated_fields)
298
+ end
299
+ end
300
+ return value unless value.is_a?(Hash)
301
+
302
+ children.each_with_object({}) do |child, built|
303
+ built[child.name] = rest_native(BigQueryHelper.row_get(value, child.name), child, type_names, repeated_fields)
304
+ end
305
+ end
306
+
307
+ def rest_integer(value)
308
+ return value if value.is_a?(Integer)
309
+ return BigQueryHelper.js_number(value) if value.is_a?(Float)
310
+
311
+ text = value.to_s
312
+ number = integer_text(text)
313
+ return number unless number.nil?
314
+
315
+ BigQueryHelper.js_number(text)
316
+ end
317
+
318
+ def rest_float(value)
319
+ return value if value.is_a?(Float)
320
+ return value.to_f if value.is_a?(Integer)
321
+
322
+ Float(value.to_s)
323
+ end
324
+
325
+ def rest_bool(value)
326
+ return value if value == true || value == false
327
+
328
+ value.to_s.casecmp('true').zero?
329
+ end
330
+
331
+ def rest_date(value)
332
+ return value if value.is_a?(Date) && !value.is_a?(DateTime)
333
+
334
+ text = value.to_s
335
+ return text.byteslice(0, 10) if text.bytesize >= 10 && date_prefix?(text)
336
+
337
+ Date.iso8601(text[0, 10])
338
+ end
339
+
340
+ def rest_datetime(value)
341
+ return value if value.is_a?(Time) || value.is_a?(DateTime)
342
+
343
+ text = value.to_s
344
+ parts = split_datetime(text)
345
+ return text unless parts
346
+
347
+ year, month, day, hour, minute, second, usec = parts
348
+ clock_text(year, month, day, hour, minute, second, usec)
349
+ end
350
+
351
+ def rest_time(value)
352
+ return value if value.is_a?(Clock)
353
+
354
+ text = value.to_s
355
+ parts = split_time(text)
356
+ return text unless parts
357
+
358
+ hour, minute, second, usec = parts
359
+ "#{CivilTime::ISO_2[hour]}:#{CivilTime::ISO_2[minute]}:#{CivilTime::ISO_2[second]}#{fraction_tail(usec)}"
360
+ end
361
+
362
+ def rest_timestamp(value)
363
+ return value if value.is_a?(Time) || value.is_a?(DateTime)
364
+
365
+ text = value.to_s
366
+ iso = epoch_text_to_iso(text)
367
+ return iso unless iso.nil?
368
+
369
+ # Anything that is not an epoch still goes through Time. Time.parse
370
+ # reads a scientific exponent as a day-of-year, so those are handled above.
371
+ Time.parse(text).utc
372
+ end
373
+
374
+ def epoch_text_to_iso(text)
375
+ scaled = scaled_decimal(text)
376
+ return nil if scaled.nil?
377
+
378
+ mantissa, scale = scaled
379
+ seconds, usec = mantissa_to_seconds(mantissa, scale)
380
+ year, month, day, hour, minute, second = CivilTime.epoch_parts(seconds)
381
+ return nil unless year.between?(0, 9999)
382
+
383
+ "#{CivilTime.iso_date(year, month, day)}T#{CivilTime::ISO_2[hour]}:#{CivilTime::ISO_2[minute]}:#{CivilTime::ISO_2[second]}#{timestamp_tail(usec)}"
384
+ end
385
+
386
+ def clock_text(year, month, day, hour, minute, second, usec)
387
+ "#{CivilTime.iso_date(year, month, day)}T#{CivilTime::ISO_2[hour]}:#{CivilTime::ISO_2[minute]}:#{CivilTime::ISO_2[second]}#{fraction_tail(usec)}"
388
+ end
389
+
390
+ def fraction_tail(usec)
391
+ usec = usec.to_i
392
+ return '' if usec.zero?
393
+
394
+ format('.%06d', usec).sub(/0+\z/, '')
395
+ end
396
+
397
+ def timestamp_tail(usec)
398
+ usec = usec.to_i
399
+ return format('.%06dZ', usec) if (usec % 1000) != 0
400
+
401
+ ".#{CivilTime::ISO_3[usec / 1000]}Z"
402
+ end
403
+
404
+ def date_prefix?(text)
405
+ return false unless text.getbyte(4) == 45 && text.getbyte(7) == 45
406
+
407
+ 10.times do |index|
408
+ next if index == 4 || index == 7
409
+
410
+ byte = text.getbyte(index)
411
+ return false if byte.nil? || byte < 48 || byte > 57
412
+ end
413
+ true
414
+ end
415
+
416
+ def split_datetime(text)
417
+ size = text.bytesize
418
+ return nil unless size >= 19 && date_prefix?(text)
419
+
420
+ separator = text.getbyte(10)
421
+ return nil unless separator == 32 || separator == 84
422
+ return nil unless text.getbyte(13) == 58 && text.getbyte(16) == 58
423
+
424
+ year = read_digits(text, 0, 4)
425
+ month = read_digits(text, 5, 2)
426
+ day = read_digits(text, 8, 2)
427
+ hour = read_digits(text, 11, 2)
428
+ minute = read_digits(text, 14, 2)
429
+ second = read_digits(text, 17, 2)
430
+ return nil if year.nil? || month.nil? || day.nil? || hour.nil? || minute.nil? || second.nil?
431
+ return nil unless month.between?(1, 12) && hour.between?(0, 23) && minute.between?(0, 59) && second.between?(0, 59)
432
+
433
+ index = 19
434
+ fraction = nil
435
+ if index < size && text.getbyte(index) == 46
436
+ start = index + 1
437
+ index = start
438
+ while index < size
439
+ byte = text.getbyte(index)
440
+ break if byte < 48 || byte > 57
441
+
442
+ index += 1
443
+ end
444
+ return nil if index == start
445
+
446
+ fraction = text.byteslice(start, index - start)
447
+ end
448
+ return nil if index != size
449
+
450
+ [year, month, day, hour, minute, second, fraction_usec(fraction)]
451
+ end
452
+
453
+ def split_time(text)
454
+ size = text.bytesize
455
+ return nil if size < 8
456
+ return nil unless text.getbyte(2) == 58 && text.getbyte(5) == 58
457
+
458
+ hour = read_digits(text, 0, 2)
459
+ minute = read_digits(text, 3, 2)
460
+ second = read_digits(text, 6, 2)
461
+ return nil if hour.nil? || minute.nil? || second.nil?
462
+ return nil unless hour.between?(0, 23) && minute.between?(0, 59) && second.between?(0, 59)
463
+
464
+ index = 8
465
+ fraction = nil
466
+ if index < size && text.getbyte(index) == 46
467
+ start = index + 1
468
+ index = start
469
+ while index < size
470
+ byte = text.getbyte(index)
471
+ break if byte < 48 || byte > 57
472
+
473
+ index += 1
474
+ end
475
+ return nil if index == start
476
+
477
+ fraction = text.byteslice(start, index - start)
478
+ end
479
+ return nil if index != size
480
+
481
+ [hour, minute, second, fraction_usec(fraction)]
482
+ end
483
+
484
+ def integer_text(text)
485
+ size = text.bytesize
486
+ return nil if size.zero?
487
+
488
+ index = 0
489
+ negative = false
490
+ if text.getbyte(0) == 45
491
+ negative = true
492
+ index = 1
493
+ end
494
+ return nil if index >= size
495
+
496
+ number = 0
497
+ while index < size
498
+ byte = text.getbyte(index)
499
+ return nil if byte < 48 || byte > 57
500
+
501
+ number = number * 10 + (byte - 48)
502
+ index += 1
503
+ end
504
+ negative ? -number : number
505
+ end
506
+
507
+ def read_digits(text, start, count)
508
+ return nil if start + count > text.bytesize
509
+
510
+ number = 0
511
+ count.times do |offset|
512
+ byte = text.getbyte(start + offset)
513
+ return nil if byte < 48 || byte > 57
514
+
515
+ number = number * 10 + (byte - 48)
516
+ end
517
+ number
518
+ end
519
+
520
+ # [mantissa, scale] so the value is mantissa * 10^scale. nil when text
521
+ # is not a plain or scientific decimal.
522
+ def scaled_decimal(text)
523
+ size = text.bytesize
524
+ return nil if size.zero?
525
+
526
+ index = 0
527
+ negative = false
528
+ byte = text.getbyte(0)
529
+ if byte == 45
530
+ negative = true
531
+ index = 1
532
+ elsif byte == 43
533
+ index = 1
534
+ end
535
+ return nil if index >= size
536
+
537
+ mantissa = 0
538
+ saw_digit = false
539
+ while index < size
540
+ byte = text.getbyte(index)
541
+ break unless byte >= 48 && byte <= 57
542
+
543
+ mantissa = mantissa * 10 + (byte - 48)
544
+ saw_digit = true
545
+ index += 1
546
+ end
547
+ frac_len = 0
548
+ if index < size && text.getbyte(index) == 46
549
+ index += 1
550
+ while index < size
551
+ byte = text.getbyte(index)
552
+ break unless byte >= 48 && byte <= 57
553
+
554
+ mantissa = mantissa * 10 + (byte - 48)
555
+ frac_len += 1
556
+ saw_digit = true
557
+ index += 1
558
+ end
559
+ end
560
+ exponent = 0
561
+ if index < size && (text.getbyte(index) == 69 || text.getbyte(index) == 101)
562
+ index += 1
563
+ exp_neg = false
564
+ if index < size && text.getbyte(index) == 45
565
+ exp_neg = true
566
+ index += 1
567
+ elsif index < size && text.getbyte(index) == 43
568
+ index += 1
569
+ end
570
+ saw_exp = false
571
+ while index < size
572
+ byte = text.getbyte(index)
573
+ return nil unless byte >= 48 && byte <= 57
574
+
575
+ exponent = exponent * 10 + (byte - 48)
576
+ saw_exp = true
577
+ index += 1
578
+ end
579
+ return nil unless saw_exp
580
+
581
+ exponent = -exponent if exp_neg
582
+ end
583
+ return nil if index != size || !saw_digit
584
+
585
+ mantissa = -mantissa if negative
586
+ [mantissa, exponent - frac_len]
587
+ end
588
+
589
+ def mantissa_to_seconds(mantissa, scale)
590
+ negative = mantissa.negative?
591
+ magnitude = mantissa.abs
592
+ micro_scale = scale + 6
593
+ if micro_scale >= 0
594
+ micros = magnitude * (10**micro_scale)
595
+ else
596
+ divisor = 10**(-micro_scale)
597
+ micros, remainder = magnitude.divmod(divisor)
598
+ micros += 1 if remainder * 2 >= divisor
599
+ end
600
+ micros = -micros if negative
601
+ seconds, usec = micros.divmod(1_000_000)
602
+ [seconds, usec]
603
+ end
604
+
605
+ def rest_bytes(value)
606
+ Base64.decode64(value.to_s)
607
+ end
608
+
609
+ def fraction_usec(fraction)
610
+ return 0 if fraction.nil? || fraction.empty?
611
+
612
+ "#{fraction}000000"[0, 6].to_i
613
+ end
614
+
615
+ def access_token
616
+ now = Time.now.to_i
617
+ return @access_token if @access_token && now < @token_expiry - 30
618
+
619
+ assertion = jwt_assertion(now)
620
+ uri = URI(OAUTH_TOKEN_URL)
621
+ http = Net::HTTP.new(uri.host, uri.port)
622
+ http.use_ssl = true
623
+ http.open_timeout = 60
624
+ http.read_timeout = 60
625
+ request = Net::HTTP::Post.new(uri)
626
+ request['Content-Type'] = 'application/x-www-form-urlencoded'
627
+ request.body = URI.encode_www_form(
628
+ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
629
+ assertion: assertion
630
+ )
631
+ response = http.request(request)
632
+ unless response.is_a?(Net::HTTPSuccess)
633
+ raise "BigQuery authentication failed: #{error_text(response)}"
634
+ end
635
+
636
+ parsed = JSON.parse(response.body)
637
+ @access_token = parsed['access_token']
638
+ @token_expiry = now + parsed.fetch('expires_in', 3600).to_i
639
+ @access_token
640
+ end
641
+
642
+ def jwt_assertion(now)
643
+ header = base64url(JSON.generate({ 'alg' => 'RS256', 'typ' => 'JWT' }))
644
+ claims = {
645
+ 'iss' => @credentials['client_email'] || @credentials[:client_email],
646
+ 'scope' => BIGQUERY_SCOPE,
647
+ 'aud' => OAUTH_TOKEN_URL,
648
+ 'iat' => now,
649
+ 'exp' => now + 3600
650
+ }
651
+ payload = base64url(JSON.generate(claims))
652
+ signing_input = "#{header}.#{payload}"
653
+ key = OpenSSL::PKey.read(private_key_pem)
654
+ signature = key.sign(OpenSSL::Digest::SHA256.new, signing_input)
655
+ "#{signing_input}.#{base64url(signature)}"
656
+ end
657
+
658
+ def private_key_pem
659
+ pem = (@credentials['private_key'] || @credentials[:private_key]).to_s
660
+ pem = pem.gsub('\\n', "\n") if pem.include?('\\n') && !pem.include?("\n")
661
+ pem
662
+ end
663
+
664
+ def base64url(data)
665
+ Base64.urlsafe_encode64(data, padding: false)
666
+ end
667
+
668
+ def api_json(method, path, params_or_body = nil)
669
+ uri = URI("#{API_HOST}#{path}")
670
+ if method == :get && params_or_body.is_a?(Hash)
671
+ query = URI.encode_www_form(params_or_body)
672
+ uri.query = query unless query.empty?
673
+ end
674
+ http = Net::HTTP.new(uri.host, uri.port)
675
+ http.use_ssl = true
676
+ http.open_timeout = 60
677
+ http.read_timeout = 120
678
+ request = method == :post ? Net::HTTP::Post.new(uri) : Net::HTTP::Get.new(uri)
679
+ request['Authorization'] = "Bearer #{access_token}"
680
+ request['Content-Type'] = 'application/json'
681
+ request.body = JSON.generate(params_or_body || {}) if method == :post
682
+ response = http.request(request)
683
+ unless response.is_a?(Net::HTTPSuccess)
684
+ sent = JSON.parse(response.body.to_s)['error'] rescue nil
685
+ raise RequestError.new(error_text(response), sent.is_a?(Hash) ? sent : {})
686
+ end
687
+
688
+ body = response.body.to_s
689
+ return {} if body.empty?
690
+
691
+ JSON.parse(body)
692
+ end
693
+
694
+ def error_text(response)
695
+ parsed = JSON.parse(response.body)
696
+ parsed.dig('error', 'message') || response.body
697
+ rescue JSON::ParserError, TypeError
698
+ response.body.to_s
699
+ end
700
+
701
+ def path_escape(value)
702
+ URI.encode_www_form_component(value.to_s).gsub('+', '%20')
703
+ end
704
+ end
705
+
706
+ class << self
707
+ def format_bigquery_config(connection_string)
708
+ text = connection_string.to_s
709
+ json_start = text.index('{')
710
+ raise 'Invalid input string. No JSON data found.' if json_start.nil?
711
+
712
+ dataset_name = text[0...json_start].strip
713
+ begin
714
+ service_account = JSON.parse(text[json_start..])
715
+ rescue JSON::ParserError => e
716
+ raise "Failed to parse JSON string: #{e.message}"
717
+ end
718
+ unless service_account.is_a?(Hash) &&
719
+ present_field?(service_account['project_id']) &&
720
+ present_field?(service_account['private_key'])
721
+ raise 'Invalid service account JSON. Required fields are missing.'
722
+ end
723
+
724
+ project_id = service_account['project_id']
725
+ {
726
+ datasetName: dataset_name,
727
+ projectId: project_id,
728
+ project: project_id,
729
+ credentials: service_account,
730
+ usingConnectionString: true
731
+ }
732
+ end
733
+
734
+ def connect_to_bigquery(config)
735
+ flag = resolve_using_connection_string(config)
736
+ credentials = resolve_credentials(config, flag)
737
+ Client.new(
738
+ project: resolve_project(config, credentials),
739
+ dataset_name: resolve_dataset(config),
740
+ credentials: credentials,
741
+ using_connection_string: flag
742
+ )
743
+ end
744
+
745
+ def disconnect_from_bigquery(_client)
746
+ nil
747
+ end
748
+
749
+ def run_query_bigquery(sql, connection)
750
+ queried = connection.query(sql)
751
+ result = queried.respond_to?(:result) ? queried.result : queried
752
+ raw_rows = result_rows(result)
753
+ return { fields: [], rows: [] } if raw_rows.empty?
754
+
755
+ decoders = decoders_for(result_schema(result))
756
+ rows = raw_rows.map do |row|
757
+ row = row.to_h if !row.is_a?(Hash) && row.respond_to?(:to_h)
758
+ decoders.each_with_object({}) do |(name, decode), built|
759
+ built[name] = decode.call(row_get(row, name))
760
+ end
761
+ end
762
+ fields = decoders.map do |name, _decode|
763
+ data_type_id = VARCHAR_OID
764
+ rows.each do |row|
765
+ value = row[name]
766
+ next if value.nil?
767
+
768
+ data_type_id = infer_type(value)
769
+ break
770
+ end
771
+ { name: name, dataTypeID: data_type_id }
772
+ end
773
+ { fields: fields, rows: rows }
774
+ end
775
+
776
+ def get_schemas_bigquery(client)
777
+ Array(client.list_datasets).filter_map { |dataset| dataset_identifier(dataset) }
778
+ end
779
+
780
+ def get_tables_by_schema_bigquery(client, schema_names)
781
+ Array(schema_names).flat_map do |schema|
782
+ sql = "SELECT table_name FROM #{schema}.INFORMATION_SCHEMA.TABLES WHERE table_type = 'BASE TABLE' OR table_type = 'VIEW' OR table_type = 'MATERIALIZED VIEW'"
783
+ results = run_query_bigquery(sql, client)
784
+ results[:rows].map do |row|
785
+ {
786
+ tableName: row_get(row, 'table_name'),
787
+ schemaName: schema
788
+ }
789
+ end
790
+ end
791
+ end
792
+
793
+ def get_columns_by_table_bigquery(client, schema_name, table_name)
794
+ sql = "SELECT column_name FROM #{schema_name}.INFORMATION_SCHEMA.COLUMNS WHERE table_name = '#{table_name}'"
795
+ results = run_query_bigquery(sql, client)
796
+ results[:rows].map { |row| row_get(row, 'column_name') }
797
+ end
798
+
799
+ # Node's getForeignKeys. The first probe drops `id` and `_id_`. A miss
800
+ # falls through to the broader LIKE probe, which keeps those names.
801
+ def get_foreign_keys_bigquery(client, schema_name, table_name, primary_key)
802
+ singular = depluralize(table_name.to_s)
803
+ capitalized = capitalize_word(primary_key.to_s)
804
+ sql = <<~SQL
805
+ SELECT column_name FROM #{schema_name}.INFORMATION_SCHEMA.COLUMNS
806
+ WHERE table_name != '#{table_name}'
807
+ and (column_name = '#{primary_key}'
808
+ or column_name = '#{singular}_#{primary_key}'
809
+ or column_name = '#{singular}#{capitalized}')
810
+ SQL
811
+ keys = column_names(run_query_bigquery(sql, client))
812
+ keys = keys.reject { |key| key == 'id' || key == '_id_' }.uniq
813
+ return keys unless keys.empty?
814
+
815
+ sql = <<~SQL
816
+ SELECT column_name FROM #{schema_name}.INFORMATION_SCHEMA.COLUMNS
817
+ WHERE table_name != '#{table_name}'
818
+ and (column_name like '#{singular}%'
819
+ or column_name like '%_id'
820
+ or column_name like '%Id'
821
+ or column_name like '%_#{primary_key}'
822
+ or column_name like '%#{capitalized}')
823
+ SQL
824
+ column_names(run_query_bigquery(sql, client)).uniq
825
+ end
826
+
827
+ def get_schema_column_info_bigquery(client, schema_name, table_names)
828
+ Array(table_names).map do |table|
829
+ table_schema, table_name = table_identity(table, schema_name)
830
+ sql = <<~SQL
831
+ SELECT column_name as columnName, data_type as dataType
832
+ FROM #{table_schema}.INFORMATION_SCHEMA.COLUMNS
833
+ WHERE table_name = '#{table_name}'
834
+ ORDER BY ordinal_position
835
+ SQL
836
+ results = run_query_bigquery(sql, client)
837
+ {
838
+ tableName: "#{table_schema}.#{table_name}",
839
+ displayName: "#{table_schema}.#{table_name}",
840
+ columns: results[:rows].map do |row|
841
+ column_name = row_get(row, 'columnName')
842
+ field_type = row_get(row, 'dataType')
843
+ {
844
+ columnName: column_name,
845
+ displayName: column_name,
846
+ dataTypeID: convert_bigquery_to_postgres(field_type),
847
+ fieldType: field_type
848
+ }
849
+ end
850
+ }
851
+ end
852
+ end
853
+
854
+ # Node's inferType, on a value already in the JSON shape Node returns.
855
+ # Booleans are varchar: JS `typeof true` is not `"number"`.
856
+ def infer_type(elem)
857
+ return VARCHAR_OID if elem == true || elem == false
858
+ return 23 if elem.is_a?(Integer)
859
+ if elem.is_a?(Float)
860
+ return 23 if elem.finite? && elem == elem.to_i
861
+
862
+ return 700
863
+ end
864
+ if elem.is_a?(Hash)
865
+ oid = value_pattern_oid(row_get(elem, 'value'))
866
+ return oid unless oid.nil?
867
+ end
868
+ if elem.is_a?(String)
869
+ oid = value_pattern_oid(elem)
870
+ return oid unless oid.nil?
871
+ end
872
+ VARCHAR_OID
873
+ end
874
+
875
+ def convert_bigquery_to_postgres(value)
876
+ text = value.to_s.upcase
877
+ base = text.split('<', 2).first.to_s.split('(', 2).first.to_s.strip
878
+ return TYPE_TO_OID[base] if TYPE_TO_OID.key?(base)
879
+
880
+ VARCHAR_OID
881
+ end
882
+
883
+ def row_get(row, name)
884
+ return nil unless row.is_a?(Hash)
885
+ return row[name] if row.key?(name)
886
+
887
+ symbol = name.to_sym
888
+ return row[symbol] if row.key?(symbol)
889
+
890
+ string = name.to_s
891
+ return row[string] if row.key?(string)
892
+
893
+ nil
894
+ end
895
+
896
+ def field_attr(field, *keys)
897
+ if field.is_a?(Hash)
898
+ keys.each do |key|
899
+ return field[key] if field.key?(key)
900
+ return field[key.to_s] if field.key?(key.to_s)
901
+ return field[key.to_sym] if field.key?(key.to_sym)
902
+ end
903
+ return nil
904
+ end
905
+ keys.each do |key|
906
+ return field.public_send(key) if field.respond_to?(key)
907
+ end
908
+ nil
909
+ end
910
+
911
+ # Whole floats inside MAX_SAFE_INTEGER become Integer. 0 stays 0.
912
+ def js_number(value)
913
+ return value if value == true || value == false
914
+ return value if value.is_a?(Integer)
915
+
916
+ number = value.is_a?(Float) ? value : Float(value.to_s)
917
+ return number unless number.finite?
918
+ return number.to_i if number == number.to_i && number.abs <= MAX_SAFE_INTEGER
919
+
920
+ number
921
+ end
922
+
923
+ private
924
+
925
+ def resolve_using_connection_string(config)
926
+ flag = config_value(config, :usingConnectionString)
927
+ flag = config_value(config, :using_connection_string) if flag.nil?
928
+ return flag if flag == true || flag == false
929
+
930
+ creds = config_value(config, :credentials)
931
+ path = service_account_path(config)
932
+ return false if blank?(creds) && !blank?(path)
933
+
934
+ true
935
+ end
936
+
937
+ def resolve_project(config, credentials)
938
+ project = config_value(config, :projectId)
939
+ project = config_value(config, :project) if blank?(project)
940
+ if blank?(project) && credentials.is_a?(Hash)
941
+ project = credentials['project_id'] || credentials[:project_id]
942
+ end
943
+ raise 'BigQuery project id is missing.' if blank?(project)
944
+
945
+ project
946
+ end
947
+
948
+ def resolve_dataset(config)
949
+ name = config_value(config, :datasetName)
950
+ name = config_value(config, :dataset_id) if blank?(name)
951
+ name = config_value(config, :dataset) if blank?(name)
952
+ name.to_s
953
+ end
954
+
955
+ def resolve_credentials(config, using_connection_string)
956
+ if using_connection_string == false
957
+ path = service_account_path(config)
958
+ raise 'BigQuery service account file path is missing.' if blank?(path)
959
+
960
+ begin
961
+ parsed = JSON.parse(File.read(path))
962
+ rescue JSON::ParserError => e
963
+ raise "Failed to parse JSON string: #{e.message}"
964
+ end
965
+ unless parsed.is_a?(Hash)
966
+ raise 'Invalid service account JSON. Required fields are missing.'
967
+ end
968
+ return parsed
969
+ end
970
+
971
+ creds = config_value(config, :credentials)
972
+ creds = JSON.parse(creds) if creds.is_a?(String)
973
+ raise 'BigQuery credentials are missing.' if blank?(creds)
974
+ raise 'Invalid service account JSON. Required fields are missing.' unless creds.is_a?(Hash)
975
+
976
+ creds
977
+ end
978
+
979
+ def service_account_path(config)
980
+ path = config_value(config, :service_account_file_path)
981
+ path = config_value(config, :keyFilename) if blank?(path)
982
+ path = config_value(config, :key_filename) if blank?(path)
983
+ path
984
+ end
985
+
986
+ def dataset_identifier(dataset)
987
+ return nil if dataset.nil?
988
+ return dataset if dataset.is_a?(String)
989
+
990
+ if dataset.is_a?(Hash)
991
+ return row_get(dataset, 'datasetId') || row_get(dataset, 'dataset_id') || row_get(dataset, 'id')
992
+ end
993
+ return dataset.dataset_id if dataset.respond_to?(:dataset_id) && !dataset.dataset_id.nil?
994
+ return dataset.id if dataset.respond_to?(:id)
995
+
996
+ nil
997
+ end
998
+
999
+ def column_names(results)
1000
+ results[:rows].map { |row| row_get(row, 'column_name') }
1001
+ end
1002
+
1003
+ def table_identity(table, fallback_schema)
1004
+ schema_name = row_get(table, 'schemaName') || row_get(table, 'schema_name') || fallback_schema
1005
+ table_name = row_get(table, 'tableName') || row_get(table, 'table_name')
1006
+ [schema_name, table_name]
1007
+ end
1008
+
1009
+ def depluralize(text)
1010
+ return "#{text[0..-4]}y" if text.end_with?('ies')
1011
+ return text[0..-2].to_s if text.end_with?('s')
1012
+
1013
+ text
1014
+ end
1015
+
1016
+ def capitalize_word(text)
1017
+ return text if text.empty?
1018
+
1019
+ text[0].upcase + text[1..]
1020
+ end
1021
+
1022
+ def result_schema(result)
1023
+ return [] unless result.respond_to?(:schema)
1024
+
1025
+ schema = result.schema
1026
+ return [] if schema.nil?
1027
+ return schema['fields'] || schema[:fields] || [] if schema.is_a?(Hash)
1028
+
1029
+ schema
1030
+ end
1031
+
1032
+ def result_rows(result)
1033
+ if result.respond_to?(:rows)
1034
+ rows = result.rows
1035
+ return [] if rows.nil?
1036
+
1037
+ return rows.to_a
1038
+ end
1039
+ return [] unless result.respond_to?(:each)
1040
+
1041
+ result.to_a
1042
+ end
1043
+
1044
+ def decoders_for(schema)
1045
+ Array(schema).map { |field| [field_name(field), decoder_for(field)] }
1046
+ end
1047
+
1048
+ def field_name(field)
1049
+ field_attr(field, :name).to_s
1050
+ end
1051
+
1052
+ def field_type_name(field)
1053
+ (field_attr(field, :field_type, :type) || '').to_s.upcase
1054
+ end
1055
+
1056
+ def field_mode(field)
1057
+ field_attr(field, :mode)
1058
+ end
1059
+
1060
+ def field_fields(field)
1061
+ field_attr(field, :fields) || []
1062
+ end
1063
+
1064
+ def decoder_for(field)
1065
+ scalar = scalar_decoder(field)
1066
+ if field_mode(field) == 'REPEATED'
1067
+ return lambda { |value|
1068
+ return nil if value.nil?
1069
+
1070
+ items = value.is_a?(Array) ? value : value.to_a
1071
+ items.map { |item| scalar.call(item) }
1072
+ }
1073
+ end
1074
+
1075
+ lambda { |value|
1076
+ return nil if value.nil?
1077
+
1078
+ scalar.call(value)
1079
+ }
1080
+ end
1081
+
1082
+ def scalar_decoder(field)
1083
+ case field_type_name(field)
1084
+ when 'RECORD', 'STRUCT'
1085
+ children = decoders_for(field_fields(field))
1086
+ lambda { |value|
1087
+ return nil if value.nil?
1088
+
1089
+ raw = value.is_a?(Hash) ? value : value.to_h
1090
+ children.each_with_object({}) do |(name, child), built|
1091
+ built[name] = child.call(row_get(raw, name))
1092
+ end
1093
+ }
1094
+ when 'NUMERIC', 'BIGNUMERIC'
1095
+ ->(value) { numeric_string(value) }
1096
+ when 'DATE'
1097
+ as_value(->(value) { date_text(value) })
1098
+ when 'DATETIME'
1099
+ as_value(->(value) { datetime_text(value) })
1100
+ when 'TIME'
1101
+ as_value(->(value) { time_text(value) })
1102
+ when 'TIMESTAMP'
1103
+ as_value(->(value) { timestamp_text(value) })
1104
+ when 'GEOGRAPHY'
1105
+ ->(value) { geography(value) }
1106
+ when 'BYTES'
1107
+ ->(value) { buffer(value) }
1108
+ when 'JSON'
1109
+ ->(value) { json_text(value) }
1110
+ when 'FLOAT', 'FLOAT64'
1111
+ ->(value) { float_value(value) }
1112
+ when 'INTEGER', 'INT64'
1113
+ ->(value) { integer_value(value) }
1114
+ else
1115
+ ->(value) { value }
1116
+ end
1117
+ end
1118
+
1119
+ def as_value(text_fn)
1120
+ lambda do |value|
1121
+ return nil if value.nil?
1122
+
1123
+ { 'value' => text_fn.call(value) }
1124
+ end
1125
+ end
1126
+
1127
+ def integer_value(value)
1128
+ return js_number(value) if value.is_a?(Float)
1129
+
1130
+ value
1131
+ end
1132
+
1133
+ def float_value(value)
1134
+ js_number(value)
1135
+ end
1136
+
1137
+ def numeric_string(value)
1138
+ if value.is_a?(String) && (plain = plain_decimal(value))
1139
+ return plain
1140
+ end
1141
+
1142
+ decimal = value.is_a?(BigDecimal) ? value : BigDecimal(value.to_s)
1143
+ text = decimal.to_s('F')
1144
+ if text.include?('.')
1145
+ text = text.sub(/0+\z/, '')
1146
+ text = text.sub(/\.\z/, '')
1147
+ end
1148
+ return '0' if text.empty? || text == '-0'
1149
+
1150
+ text
1151
+ end
1152
+
1153
+ # "20.00" -> "20", "10.50" -> "10.5", "-0.00" -> "0". nil when the text
1154
+ # is scientific notation or otherwise not a plain decimal.
1155
+ def plain_decimal(text)
1156
+ size = text.bytesize
1157
+ return nil if size.zero?
1158
+
1159
+ index = 0
1160
+ negative = false
1161
+ byte = text.getbyte(0)
1162
+ if byte == 45
1163
+ negative = true
1164
+ index = 1
1165
+ elsif byte == 43
1166
+ index = 1
1167
+ end
1168
+ return nil if index >= size
1169
+
1170
+ digits = []
1171
+ saw_digit = false
1172
+ saw_dot = false
1173
+ while index < size
1174
+ byte = text.getbyte(index)
1175
+ if byte == 46
1176
+ return nil if saw_dot
1177
+
1178
+ saw_dot = true
1179
+ digits << 46
1180
+ elsif byte >= 48 && byte <= 57
1181
+ saw_digit = true
1182
+ digits << byte
1183
+ else
1184
+ return nil
1185
+ end
1186
+ index += 1
1187
+ end
1188
+ return nil unless saw_digit
1189
+
1190
+ if saw_dot
1191
+ digits.pop while digits.last == 48
1192
+ digits.pop if digits.last == 46
1193
+ end
1194
+ return '0' if digits.empty? || digits == [48]
1195
+
1196
+ body = digits.pack('C*')
1197
+ return '0' if body == '0'
1198
+
1199
+ negative ? "-#{body}" : body
1200
+ end
1201
+
1202
+ def geography(value)
1203
+ { 'value' => value.is_a?(String) ? value : value.to_s }
1204
+ end
1205
+
1206
+ def buffer(value)
1207
+ data = value.is_a?(Array) ? value : value.to_s.b.bytes
1208
+ { 'type' => 'Buffer', 'data' => data }
1209
+ end
1210
+
1211
+ def json_text(value)
1212
+ return value if value.is_a?(String)
1213
+
1214
+ JSON.generate(value)
1215
+ end
1216
+
1217
+ def date_text(value)
1218
+ if value.is_a?(Time) || value.is_a?(Date)
1219
+ return format('%04d-%02d-%02d', value.year, value.month, value.day)
1220
+ end
1221
+
1222
+ value.to_s
1223
+ end
1224
+
1225
+ def datetime_text(value)
1226
+ return clock_stamp(value) if value.is_a?(Time) || value.is_a?(DateTime)
1227
+
1228
+ value.to_s
1229
+ end
1230
+
1231
+ def time_text(value)
1232
+ return value if value.is_a?(String)
1233
+ return clock_only(value) if value.is_a?(Time) || value.is_a?(DateTime) || clock?(value)
1234
+
1235
+ value.to_s
1236
+ end
1237
+
1238
+ def timestamp_text(value)
1239
+ unless value.is_a?(Time) || value.is_a?(DateTime)
1240
+ return value.to_s
1241
+ end
1242
+
1243
+ year, month, day, hour, minute, second, usec = utc_parts(value)
1244
+ base = format('%04d-%02d-%02dT%02d:%02d:%02d', year, month, day, hour, minute, second)
1245
+ base + timestamp_fraction(usec)
1246
+ end
1247
+
1248
+ def clock_stamp(value)
1249
+ year, month, day, hour, minute, second, usec = wall_parts(value)
1250
+ text = format('%04d-%02d-%02dT%02d:%02d:%02d', year, month, day, hour, minute, second)
1251
+ text + fraction_suffix(usec)
1252
+ end
1253
+
1254
+ def clock_only(value)
1255
+ hour, minute, second, usec = clock_parts(value)
1256
+ format('%02d:%02d:%02d', hour, minute, second) + fraction_suffix(usec)
1257
+ end
1258
+
1259
+ def fraction_suffix(usec)
1260
+ usec = usec.to_i
1261
+ return '' if usec.zero?
1262
+
1263
+ format('.%06d', usec).sub(/0+\z/, '')
1264
+ end
1265
+
1266
+ def timestamp_fraction(usec)
1267
+ usec = usec.to_i
1268
+ return format('.%06dZ', usec) if (usec % 1000) != 0
1269
+
1270
+ format('.%03dZ', usec / 1000)
1271
+ end
1272
+
1273
+ def wall_parts(value)
1274
+ [value.year, value.month, value.day, value.hour, minute_of(value), second_of(value), usec_of(value)]
1275
+ end
1276
+
1277
+ def utc_parts(value)
1278
+ if value.is_a?(Time)
1279
+ utc = value.utc? ? value : value.getutc
1280
+ return [utc.year, utc.month, utc.day, utc.hour, utc.min, utc.sec, utc.usec]
1281
+ end
1282
+
1283
+ utc = value.offset.zero? ? value : value.new_offset(0)
1284
+ [utc.year, utc.month, utc.day, utc.hour, utc.min, utc.sec, usec_of(utc)]
1285
+ end
1286
+
1287
+ def clock_parts(value)
1288
+ [value.hour, minute_of(value), second_of(value), usec_of(value)]
1289
+ end
1290
+
1291
+ def minute_of(value)
1292
+ value.respond_to?(:min) ? value.min : value.minute
1293
+ end
1294
+
1295
+ def second_of(value)
1296
+ value.respond_to?(:sec) ? value.sec : value.second
1297
+ end
1298
+
1299
+ def usec_of(value)
1300
+ return value.usec if value.respond_to?(:usec)
1301
+ return (value.sec_fraction * 1_000_000).round if value.is_a?(DateTime)
1302
+ return value.microsecond if value.respond_to?(:microsecond)
1303
+
1304
+ 0
1305
+ end
1306
+
1307
+ def clock?(value)
1308
+ return false if value.is_a?(String) || value.is_a?(Numeric)
1309
+
1310
+ value.respond_to?(:hour) && (value.respond_to?(:min) || value.respond_to?(:minute)) && !value.respond_to?(:year)
1311
+ end
1312
+
1313
+ def value_pattern_oid(text)
1314
+ return nil unless text.is_a?(String)
1315
+ return 1082 if DATE_RE.match?(text) || DATE_SLASH_RE.match?(text)
1316
+ return 1114 if TIMESTAMP_RE.match?(text)
1317
+ return 1184 if TIMESTAMPTZ_RE.match?(text)
1318
+ return 1083 if TIME_RE.match?(text)
1319
+
1320
+ nil
1321
+ end
1322
+
1323
+ def config_value(config, key)
1324
+ return nil unless config.respond_to?(:key?)
1325
+
1326
+ [key, key.to_s, key.to_sym].each do |candidate|
1327
+ return config[candidate] if config.key?(candidate)
1328
+ end
1329
+ nil
1330
+ end
1331
+
1332
+ def present_field?(value)
1333
+ return false if value.nil? || value == false || value == 0
1334
+ return false if value.is_a?(String) && value.empty?
1335
+
1336
+ true
1337
+ end
1338
+
1339
+ def blank?(value)
1340
+ return true if value.nil?
1341
+ return true if value.respond_to?(:empty?) && value.empty?
1342
+
1343
+ false
1344
+ end
1345
+ end
1346
+ end