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.
- checksums.yaml +4 -4
- data/README.md +5 -1
- data/lib/client_token.rb +43 -0
- data/lib/db/bigquery.rb +1346 -0
- data/lib/db/cached_connection.rb +187 -17
- data/lib/db/civil_time.rb +60 -0
- data/lib/db/clickhouse.rb +164 -48
- data/lib/db/databricks.rb +498 -61
- data/lib/db/db_helper.rb +112 -2
- data/lib/db/mssql.rb +917 -0
- data/lib/db/mysql.rb +934 -0
- data/lib/db/postgres.rb +222 -47
- data/lib/db/redshift.rb +164 -0
- data/lib/db/snowflake.rb +1167 -0
- data/lib/models/filters.rb +1 -1
- data/lib/quill-sql.rb +468 -100
- data/lib/utils/pivot_template.rb +457 -0
- data/lib/utils/report_error.rb +169 -0
- data/lib/utils/run_query_processes.rb +26 -4
- metadata +128 -12
data/lib/db/databricks.rb
CHANGED
|
@@ -1,9 +1,34 @@
|
|
|
1
1
|
require 'uri'
|
|
2
2
|
require 'json'
|
|
3
3
|
require 'net/http'
|
|
4
|
+
require 'base64'
|
|
5
|
+
require 'bigdecimal'
|
|
6
|
+
require 'date'
|
|
4
7
|
require 'active_support/inflector'
|
|
8
|
+
require_relative 'civil_time'
|
|
5
9
|
|
|
6
10
|
module DatabricksHelper
|
|
11
|
+
# A request or statement Databricks rejected, with the code and SQLSTATE it sent.
|
|
12
|
+
class QueryError < RuntimeError
|
|
13
|
+
attr_reader :error_code, :sql_state
|
|
14
|
+
|
|
15
|
+
def initialize(message, error_code, sql_state = nil)
|
|
16
|
+
super(message)
|
|
17
|
+
@error_code = error_code
|
|
18
|
+
@sql_state = sql_state
|
|
19
|
+
end
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
# JS Number.MAX_SAFE_INTEGER. Whole floats inside this range stringify as
|
|
23
|
+
# integers (`20`, not `20.0`), matching JSON.stringify.
|
|
24
|
+
MAX_SAFE_INTEGER = 9_007_199_254_740_991
|
|
25
|
+
# Resolved here so cell conversion does not look the class up per value.
|
|
26
|
+
# A singleton method's constant scope does not see Object::BigDecimal.
|
|
27
|
+
DECIMAL_CLASS = BigDecimal
|
|
28
|
+
DATE_CLASS = Date
|
|
29
|
+
DATETIME_CLASS = DateTime
|
|
30
|
+
|
|
31
|
+
# Information-schema `data_type` names -> Postgres OID. Node's name map.
|
|
7
32
|
DATABRICKS_DATATYPE_NAME_MAP = {
|
|
8
33
|
# Numeric Types
|
|
9
34
|
'BIGINT' => 20, # int8
|
|
@@ -30,15 +55,103 @@ module DatabricksHelper
|
|
|
30
55
|
'OBJECT' => 3802 # jsonb
|
|
31
56
|
}.freeze
|
|
32
57
|
|
|
58
|
+
# Thrift TTypeId -> Postgres OID. Query fields use this, not the name map:
|
|
59
|
+
# STRING is text (25) here and varchar (1043) in the name map; FLOAT is
|
|
60
|
+
# float4 (700) here and float8 (701) in the name map.
|
|
61
|
+
DATABRICKS_DATATYPE_ID_MAP = {
|
|
62
|
+
0 => 16, # boolean
|
|
63
|
+
1 => 21, # tinyint
|
|
64
|
+
2 => 21, # smallint
|
|
65
|
+
3 => 23, # int
|
|
66
|
+
4 => 20, # bigint
|
|
67
|
+
5 => 700, # float
|
|
68
|
+
6 => 701, # double
|
|
69
|
+
7 => 25, # string
|
|
70
|
+
8 => 1114, # timestamp
|
|
71
|
+
9 => 17, # binary
|
|
72
|
+
10 => 2277, # array
|
|
73
|
+
11 => 3802, # map
|
|
74
|
+
12 => 3802, # struct
|
|
75
|
+
13 => 3802, # union
|
|
76
|
+
14 => 3802, # user_defined
|
|
77
|
+
15 => 1700, # decimal
|
|
78
|
+
16 => 1043, # null
|
|
79
|
+
17 => 1082, # date
|
|
80
|
+
18 => 1043, # varchar
|
|
81
|
+
19 => 1042, # char
|
|
82
|
+
20 => 1186, # interval_year_month
|
|
83
|
+
21 => 1186 # interval_day_time
|
|
84
|
+
}.freeze
|
|
85
|
+
|
|
86
|
+
# SQL names and the REST API's ColumnInfoTypeName spellings (LONG, BYTE, ...).
|
|
87
|
+
DATABRICKS_DATATYPE_CODE_MAP = {
|
|
88
|
+
'boolean' => 16,
|
|
89
|
+
'tinyint' => 21,
|
|
90
|
+
'byte' => 21,
|
|
91
|
+
'smallint' => 21,
|
|
92
|
+
'short' => 21,
|
|
93
|
+
'int' => 23,
|
|
94
|
+
'integer' => 23,
|
|
95
|
+
'bigint' => 20,
|
|
96
|
+
'long' => 20,
|
|
97
|
+
'float' => 700,
|
|
98
|
+
'double' => 701,
|
|
99
|
+
'string' => 25,
|
|
100
|
+
'timestamp' => 1114,
|
|
101
|
+
'timestamp_ntz' => 1114,
|
|
102
|
+
'binary' => 17,
|
|
103
|
+
'array' => 2277,
|
|
104
|
+
'map' => 3802,
|
|
105
|
+
'struct' => 3802,
|
|
106
|
+
'union' => 3802,
|
|
107
|
+
'user_defined' => 3802,
|
|
108
|
+
'user_defined_type' => 3802,
|
|
109
|
+
'decimal' => 1700,
|
|
110
|
+
'null' => 1043,
|
|
111
|
+
'date' => 1082,
|
|
112
|
+
'varchar' => 1043,
|
|
113
|
+
'char' => 1042,
|
|
114
|
+
'interval_year_month' => 1186,
|
|
115
|
+
'interval_day_time' => 1186,
|
|
116
|
+
'interval' => 1186,
|
|
117
|
+
'void' => 2278,
|
|
118
|
+
'variant' => 3802,
|
|
119
|
+
'object' => 3802
|
|
120
|
+
}.freeze
|
|
121
|
+
|
|
122
|
+
# No type descriptor -> struct/jsonb. An unknown descriptor -> varchar.
|
|
123
|
+
MISSING_TYPE_OID = 3802
|
|
124
|
+
UNKNOWN_TYPE_OID = 1043
|
|
125
|
+
|
|
126
|
+
TIMESTAMP_RE = /\A(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:?\d{2})?\z/.freeze
|
|
127
|
+
# Nested STRING elements are already JSON text. Walking them only to
|
|
128
|
+
# return the same string dominated array/map columns.
|
|
129
|
+
STRING_BASES = { 'string' => true, 'varchar' => true, 'char' => true }.freeze
|
|
130
|
+
|
|
33
131
|
class << self
|
|
34
|
-
def
|
|
35
|
-
|
|
132
|
+
def type_code_to_oid(type_code)
|
|
133
|
+
return MISSING_TYPE_OID if type_code.nil?
|
|
134
|
+
return DATABRICKS_DATATYPE_ID_MAP[type_code] || UNKNOWN_TYPE_OID if type_code.is_a?(Integer)
|
|
135
|
+
|
|
136
|
+
normalized = type_code.to_s.strip.downcase
|
|
137
|
+
normalized = normalized.split('(', 2).first.split('<', 2).first
|
|
138
|
+
normalized = normalized.sub(/_type\z/, '')
|
|
139
|
+
DATABRICKS_DATATYPE_CODE_MAP[normalized] || UNKNOWN_TYPE_OID
|
|
140
|
+
end
|
|
36
141
|
|
|
37
|
-
|
|
142
|
+
def data_type_to_oid(data_type)
|
|
143
|
+
base = data_type.to_s.split('<', 2).first.split('(', 2).first.strip.upcase
|
|
144
|
+
DATABRICKS_DATATYPE_NAME_MAP[base] || UNKNOWN_TYPE_OID
|
|
145
|
+
end
|
|
146
|
+
def connect_to_databricks(config)
|
|
147
|
+
client = {
|
|
38
148
|
host: config[:host],
|
|
39
|
-
warehouse_id:
|
|
149
|
+
warehouse_id: config[:path].to_s.split('/').reject(&:empty?).last,
|
|
40
150
|
token: config[:token]
|
|
41
151
|
}
|
|
152
|
+
catalog = config[:catalog].to_s.strip
|
|
153
|
+
client[:catalog] = catalog unless catalog.empty?
|
|
154
|
+
client
|
|
42
155
|
end
|
|
43
156
|
|
|
44
157
|
def disconnect_from_databricks(client)
|
|
@@ -53,67 +166,58 @@ module DatabricksHelper
|
|
|
53
166
|
request = Net::HTTP::Post.new(uri)
|
|
54
167
|
request['Authorization'] = "Bearer #{client[:token]}"
|
|
55
168
|
request['Content-Type'] = 'application/json'
|
|
56
|
-
request.body = JSON.generate(
|
|
57
|
-
statement: sql,
|
|
58
|
-
warehouse_id: client[:warehouse_id],
|
|
59
|
-
wait_timeout: '50s'
|
|
60
|
-
})
|
|
169
|
+
request.body = JSON.generate(statement_request_body(sql, client))
|
|
61
170
|
|
|
62
171
|
response = http.request(request)
|
|
63
172
|
|
|
64
|
-
|
|
173
|
+
unless response.is_a?(Net::HTTPSuccess)
|
|
174
|
+
sent = (JSON.parse(response.body) rescue nil)
|
|
175
|
+
sent = {} unless sent.is_a?(Hash)
|
|
176
|
+
raise QueryError.new(sent['message'] || "Query failed: #{response.body}", sent['error_code'])
|
|
177
|
+
end
|
|
65
178
|
|
|
66
|
-
result = JSON.parse(response.body)
|
|
67
|
-
|
|
68
|
-
|
|
179
|
+
status = (result = JSON.parse(response.body))['status']
|
|
180
|
+
unless status['state'] == 'SUCCEEDED'
|
|
181
|
+
failure = status['error'] || {}
|
|
182
|
+
raise QueryError.new(failure['message'] || "Query state: #{status['state']}", failure['error_code'], status['sql_state'])
|
|
183
|
+
end
|
|
69
184
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
column_types = columns.map { |col| col['type_name'] }
|
|
185
|
+
rows_from_statement(result)
|
|
186
|
+
end
|
|
73
187
|
|
|
74
|
-
|
|
188
|
+
def statement_request_body(sql, client)
|
|
189
|
+
body = {
|
|
190
|
+
statement: sql,
|
|
191
|
+
warehouse_id: client[:warehouse_id],
|
|
192
|
+
wait_timeout: '50s'
|
|
193
|
+
}
|
|
194
|
+
catalog = client[:catalog].to_s.strip
|
|
195
|
+
body[:catalog] = catalog unless catalog.empty?
|
|
196
|
+
body
|
|
197
|
+
end
|
|
75
198
|
|
|
199
|
+
# REST `data_array` cells are strings. Rewrite them into the JSON shapes
|
|
200
|
+
# the Node driver produces: dates as toISOString(), whole decimals as
|
|
201
|
+
# integers, BINARY (including values nested in ARRAY/MAP/STRUCT) as
|
|
202
|
+
# `{type: "Buffer", data: [...]}`.
|
|
203
|
+
def rows_from_statement(result)
|
|
204
|
+
columns = result.dig('manifest', 'schema', 'columns') || []
|
|
205
|
+
types = columns.map { |column| parse_type_text(column_type_text(column)) }
|
|
76
206
|
fields = columns.map do |column|
|
|
77
207
|
{
|
|
78
208
|
name: column['name'],
|
|
79
|
-
dataTypeID:
|
|
209
|
+
dataTypeID: type_code_to_oid(column_type_text(column))
|
|
80
210
|
}
|
|
81
211
|
end
|
|
82
212
|
|
|
83
|
-
|
|
84
|
-
rows =
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
# Transform the data array into rows of hashes
|
|
88
|
-
result['result']['data_array'].map do |row_array|
|
|
89
|
-
row_hash = column_names.zip(row_array).to_h
|
|
90
|
-
transformed_row = {}
|
|
91
|
-
|
|
92
|
-
column_names.each_with_index do |key, idx|
|
|
93
|
-
value = row_hash[key]
|
|
94
|
-
type = column_types[idx]
|
|
95
|
-
# parse JSON if the field is a JSON type
|
|
96
|
-
transformed_value = if value.is_a?(String) && json_like_types.include?(type.upcase)
|
|
97
|
-
begin
|
|
98
|
-
parsed = JSON.parse(value)
|
|
99
|
-
parsed.is_a?(Array) ? parsed.map(&:to_s) : parsed
|
|
100
|
-
rescue JSON::ParserError
|
|
101
|
-
value
|
|
102
|
-
end
|
|
103
|
-
else
|
|
104
|
-
value
|
|
105
|
-
end
|
|
106
|
-
transformed_row[key] = transformed_value
|
|
107
|
-
end
|
|
108
|
-
|
|
109
|
-
transformed_row
|
|
213
|
+
data_array = result.dig('result', 'data_array') || []
|
|
214
|
+
rows = data_array.map do |row_array|
|
|
215
|
+
columns.each_with_index.each_with_object({}) do |(column, index), row|
|
|
216
|
+
row[column['name']] = node_value(row_array[index], types[index])
|
|
110
217
|
end
|
|
111
218
|
end
|
|
112
219
|
|
|
113
|
-
{
|
|
114
|
-
fields: fields,
|
|
115
|
-
rows: rows
|
|
116
|
-
}
|
|
220
|
+
{ fields: fields, rows: rows }
|
|
117
221
|
end
|
|
118
222
|
|
|
119
223
|
def get_schemas_databricks(client)
|
|
@@ -170,41 +274,374 @@ module DatabricksHelper
|
|
|
170
274
|
[]
|
|
171
275
|
end
|
|
172
276
|
|
|
173
|
-
def get_schema_column_info_databricks(client,
|
|
277
|
+
def get_schema_column_info_databricks(client, _schema_name, table_names)
|
|
174
278
|
table_names.map do |table|
|
|
279
|
+
table_schema, table_name = table_identity(table)
|
|
175
280
|
sql = <<~SQL
|
|
176
|
-
SELECT
|
|
281
|
+
SELECT
|
|
177
282
|
column_name as columnName,
|
|
178
283
|
data_type as dataType
|
|
179
284
|
FROM system.information_schema.columns
|
|
180
|
-
WHERE table_schema = '#{
|
|
181
|
-
AND table_name = '#{
|
|
285
|
+
WHERE table_schema = '#{table_schema}'
|
|
286
|
+
AND table_name = '#{table_name}'
|
|
182
287
|
ORDER BY ordinal_position
|
|
183
288
|
SQL
|
|
184
289
|
|
|
185
290
|
results = run_query_databricks(sql, client)
|
|
186
291
|
{
|
|
187
|
-
tableName: "#{
|
|
292
|
+
tableName: "#{table_schema}.#{table_name}",
|
|
293
|
+
displayName: "#{table_schema}.#{table_name}",
|
|
188
294
|
columns: results[:rows].map do |row|
|
|
189
|
-
data_type = row['dataType'].split('<')[0].upcase
|
|
190
295
|
{
|
|
191
296
|
columnName: row['columnName'],
|
|
192
297
|
displayName: row['columnName'],
|
|
193
298
|
fieldType: row['dataType'],
|
|
194
|
-
dataTypeID:
|
|
299
|
+
dataTypeID: data_type_to_oid(row['dataType'])
|
|
195
300
|
}
|
|
196
301
|
end
|
|
197
302
|
}
|
|
198
303
|
end
|
|
199
304
|
end
|
|
200
305
|
|
|
306
|
+
# `databricks://token:<access_token>@<host>/<http_path>[?catalog=<catalog>]`
|
|
307
|
+
# Path keeps its leading slash. The token is percent-decoded. `catalog` is
|
|
308
|
+
# omitted when the query parameter is absent or blank.
|
|
201
309
|
def format_databricks_config(connection_string)
|
|
202
|
-
parsed = URI(connection_string)
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
310
|
+
parsed = URI.parse(connection_string)
|
|
311
|
+
catalog = URI.decode_www_form(parsed.query.to_s).to_h['catalog'].to_s.strip
|
|
312
|
+
token = parsed.password.to_s
|
|
313
|
+
token = URI.decode_www_form_component(token) unless token.empty?
|
|
314
|
+
config = {
|
|
315
|
+
host: parsed.host || '',
|
|
316
|
+
path: parsed.path || '',
|
|
317
|
+
token: token
|
|
207
318
|
}
|
|
319
|
+
config[:catalog] = catalog unless catalog.empty?
|
|
320
|
+
config
|
|
321
|
+
end
|
|
322
|
+
|
|
323
|
+
private
|
|
324
|
+
|
|
325
|
+
def column_type_text(column)
|
|
326
|
+
text = column['type_text']
|
|
327
|
+
return text unless text.nil? || text.to_s.empty?
|
|
328
|
+
|
|
329
|
+
column['type_name']
|
|
330
|
+
end
|
|
331
|
+
|
|
332
|
+
def parse_type_text(text)
|
|
333
|
+
return { base: nil } if text.nil?
|
|
334
|
+
|
|
335
|
+
stripped = text.to_s.strip
|
|
336
|
+
return { base: nil } if stripped.empty?
|
|
337
|
+
|
|
338
|
+
match = stripped.match(/\A([A-Za-z0-9_]+)\s*(.*)\z/)
|
|
339
|
+
return { base: stripped.downcase } unless match
|
|
340
|
+
|
|
341
|
+
base = match[1].downcase.sub(/_type\z/, '')
|
|
342
|
+
rest = match[2]
|
|
343
|
+
info = { base: base }
|
|
344
|
+
if rest.start_with?('<') && rest.end_with?('>')
|
|
345
|
+
args = split_type_args(rest[1..-2])
|
|
346
|
+
info[:args] = args
|
|
347
|
+
case base
|
|
348
|
+
when 'array'
|
|
349
|
+
info[:element] = parse_type_text(args.first)
|
|
350
|
+
when 'map'
|
|
351
|
+
info[:value_type] = parse_type_text(args[1])
|
|
352
|
+
when 'struct'
|
|
353
|
+
info[:fields] = struct_fields(args)
|
|
354
|
+
end
|
|
355
|
+
end
|
|
356
|
+
|
|
357
|
+
info
|
|
358
|
+
end
|
|
359
|
+
|
|
360
|
+
def split_type_args(inner)
|
|
361
|
+
args = []
|
|
362
|
+
depth = 0
|
|
363
|
+
current = +''
|
|
364
|
+
inner.each_char do |char|
|
|
365
|
+
if char == '<' || char == '('
|
|
366
|
+
depth += 1
|
|
367
|
+
current << char
|
|
368
|
+
elsif char == '>' || char == ')'
|
|
369
|
+
depth -= 1
|
|
370
|
+
current << char
|
|
371
|
+
elsif char == ',' && depth.zero?
|
|
372
|
+
args << current.strip
|
|
373
|
+
current = +''
|
|
374
|
+
else
|
|
375
|
+
current << char
|
|
376
|
+
end
|
|
377
|
+
end
|
|
378
|
+
args << current.strip unless current.strip.empty?
|
|
379
|
+
args
|
|
380
|
+
end
|
|
381
|
+
|
|
382
|
+
def struct_fields(args)
|
|
383
|
+
(args || []).each_with_object({}) do |arg, fields|
|
|
384
|
+
name, type_text = arg.split(':', 2)
|
|
385
|
+
fields[name] = parse_type_text(type_text)
|
|
386
|
+
end
|
|
387
|
+
end
|
|
388
|
+
|
|
389
|
+
def node_value(value, type_info)
|
|
390
|
+
return nil if value.nil?
|
|
391
|
+
|
|
392
|
+
# Connector objects dispatch on class, the same way Python's
|
|
393
|
+
# `_node_value` does. Strings stay on the type-directed path because
|
|
394
|
+
# the REST client receives every cell as text.
|
|
395
|
+
klass = value.class
|
|
396
|
+
if klass.equal?(Integer) || klass.equal?(TrueClass) || klass.equal?(FalseClass)
|
|
397
|
+
return value
|
|
398
|
+
elsif klass.equal?(Float)
|
|
399
|
+
return js_float(value)
|
|
400
|
+
elsif klass.equal?(DECIMAL_CLASS)
|
|
401
|
+
return js_decimal(value)
|
|
402
|
+
elsif klass.equal?(DATE_CLASS)
|
|
403
|
+
return CivilTime.iso_utc(value.year, value.month, value.day, 0, 0, 0, 0)
|
|
404
|
+
elsif klass.equal?(DATETIME_CLASS)
|
|
405
|
+
return datetime_to_utc_iso(value)
|
|
406
|
+
elsif klass.equal?(Time)
|
|
407
|
+
return time_to_utc_iso(value)
|
|
408
|
+
end
|
|
409
|
+
|
|
410
|
+
case type_info[:base]
|
|
411
|
+
when 'boolean'
|
|
412
|
+
boolean_value(value)
|
|
413
|
+
when 'tinyint', 'byte', 'smallint', 'short', 'int', 'integer', 'bigint', 'long'
|
|
414
|
+
integer_value(value)
|
|
415
|
+
when 'float', 'double', 'decimal'
|
|
416
|
+
js_number(value)
|
|
417
|
+
when 'date'
|
|
418
|
+
date_to_iso(value)
|
|
419
|
+
when 'timestamp', 'timestamp_ntz'
|
|
420
|
+
timestamp_to_iso(value)
|
|
421
|
+
when 'binary'
|
|
422
|
+
buffer_value(value)
|
|
423
|
+
when 'array'
|
|
424
|
+
list = json_value(value)
|
|
425
|
+
return value unless list.is_a?(Array)
|
|
426
|
+
|
|
427
|
+
element = type_info[:element] || parse_type_text(type_info[:args]&.first)
|
|
428
|
+
return list if element && STRING_BASES[element[:base]]
|
|
429
|
+
|
|
430
|
+
list.map { |item| node_value(item, element) }
|
|
431
|
+
when 'map'
|
|
432
|
+
hash = json_value(value)
|
|
433
|
+
return value unless hash.is_a?(Hash)
|
|
434
|
+
|
|
435
|
+
value_type = type_info[:value_type] || parse_type_text(type_info[:args]&.[](1))
|
|
436
|
+
return hash if value_type && STRING_BASES[value_type[:base]]
|
|
437
|
+
|
|
438
|
+
hash.each_with_object({}) do |(key, item), converted|
|
|
439
|
+
converted[key] = node_value(item, value_type)
|
|
440
|
+
end
|
|
441
|
+
when 'struct'
|
|
442
|
+
hash = json_value(value)
|
|
443
|
+
return value unless hash.is_a?(Hash)
|
|
444
|
+
|
|
445
|
+
fields = type_info[:fields] || struct_fields(type_info[:args])
|
|
446
|
+
hash.each_with_object({}) do |(key, item), converted|
|
|
447
|
+
converted[key] = node_value(item, fields[key] || { base: 'string' })
|
|
448
|
+
end
|
|
449
|
+
when 'variant', 'object'
|
|
450
|
+
json_value(value)
|
|
451
|
+
else
|
|
452
|
+
value
|
|
453
|
+
end
|
|
454
|
+
end
|
|
455
|
+
|
|
456
|
+
def json_value(value)
|
|
457
|
+
return value unless value.is_a?(String)
|
|
458
|
+
|
|
459
|
+
JSON.parse(value)
|
|
460
|
+
rescue JSON::ParserError
|
|
461
|
+
value
|
|
462
|
+
end
|
|
463
|
+
|
|
464
|
+
def boolean_value(value)
|
|
465
|
+
return value if value == true || value == false
|
|
466
|
+
|
|
467
|
+
value.to_s.downcase == 'true'
|
|
468
|
+
end
|
|
469
|
+
|
|
470
|
+
def integer_value(value)
|
|
471
|
+
return value if value.is_a?(Integer)
|
|
472
|
+
|
|
473
|
+
Integer(value.to_s, 10)
|
|
474
|
+
rescue ArgumentError
|
|
475
|
+
js_number(value)
|
|
476
|
+
end
|
|
477
|
+
|
|
478
|
+
def js_number(value)
|
|
479
|
+
klass = value.class
|
|
480
|
+
return value if klass.equal?(Integer) || klass.equal?(TrueClass) || klass.equal?(FalseClass)
|
|
481
|
+
return js_float(value) if klass.equal?(Float)
|
|
482
|
+
return js_decimal(value) if klass.equal?(DECIMAL_CLASS)
|
|
483
|
+
|
|
484
|
+
number = value.is_a?(String) ? Float(value) : value.to_f
|
|
485
|
+
js_float(number)
|
|
486
|
+
end
|
|
487
|
+
|
|
488
|
+
def js_float(number)
|
|
489
|
+
return number unless number.finite?
|
|
490
|
+
|
|
491
|
+
whole = number.to_i
|
|
492
|
+
return whole if whole.abs < MAX_SAFE_INTEGER && number == whole
|
|
493
|
+
|
|
494
|
+
number
|
|
495
|
+
end
|
|
496
|
+
|
|
497
|
+
def js_decimal(value)
|
|
498
|
+
whole = value.to_i
|
|
499
|
+
return whole if whole.abs < MAX_SAFE_INTEGER && value == whole
|
|
500
|
+
|
|
501
|
+
js_float(value.to_f)
|
|
502
|
+
end
|
|
503
|
+
|
|
504
|
+
def datetime_to_utc_iso(value)
|
|
505
|
+
frac = value.sec_fraction
|
|
506
|
+
milli = frac.zero? ? 0 : (frac * 1000).to_i
|
|
507
|
+
offset = (value.offset * 86_400).to_i
|
|
508
|
+
shift_to_utc_iso(value.year, value.month, value.day, value.hour, value.min, value.sec, milli, offset)
|
|
509
|
+
end
|
|
510
|
+
|
|
511
|
+
def time_to_utc_iso(value)
|
|
512
|
+
shift_to_utc_iso(value.year, value.month, value.day, value.hour, value.min, value.sec, value.usec / 1000, value.utc_offset)
|
|
513
|
+
end
|
|
514
|
+
|
|
515
|
+
def shift_to_utc_iso(year, month, day, hour, minute, second, milli, offset_seconds)
|
|
516
|
+
total = hour * 3600 + minute * 60 + second - offset_seconds
|
|
517
|
+
day_delta, total = total.divmod(86_400)
|
|
518
|
+
hour, remainder = total.divmod(3600)
|
|
519
|
+
minute, second = remainder.divmod(60)
|
|
520
|
+
if day_delta != 0
|
|
521
|
+
year, month, day = CivilTime.civil_from_days(CivilTime.days_from_civil(year, month, day) + day_delta)
|
|
522
|
+
end
|
|
523
|
+
CivilTime.iso_utc(year, month, day, hour, minute, second, milli)
|
|
524
|
+
end
|
|
525
|
+
|
|
526
|
+
def date_to_iso(value)
|
|
527
|
+
if value.class.equal?(DATE_CLASS)
|
|
528
|
+
return CivilTime.iso_utc(value.year, value.month, value.day, 0, 0, 0, 0)
|
|
529
|
+
end
|
|
530
|
+
|
|
531
|
+
text = value.is_a?(String) ? value : value.to_s
|
|
532
|
+
return text unless text.bytesize >= 10 && text.getbyte(4) == 45 && text.getbyte(7) == 45
|
|
533
|
+
|
|
534
|
+
10.times do |index|
|
|
535
|
+
next if index == 4 || index == 7
|
|
536
|
+
|
|
537
|
+
byte = text.getbyte(index)
|
|
538
|
+
return text if byte.nil? || byte < 48 || byte > 57
|
|
539
|
+
end
|
|
540
|
+
"#{text.byteslice(0, 10)}T00:00:00.000Z"
|
|
541
|
+
end
|
|
542
|
+
|
|
543
|
+
def timestamp_to_iso(value)
|
|
544
|
+
text = value.is_a?(String) ? value : value.to_s
|
|
545
|
+
match = TIMESTAMP_RE.match(text)
|
|
546
|
+
return text unless match
|
|
547
|
+
|
|
548
|
+
year, month, day, hour, minute, second, fraction, zone = match.captures
|
|
549
|
+
millis = fraction_to_millis(fraction)
|
|
550
|
+
offset = 0
|
|
551
|
+
if zone && zone != 'Z' && zone != '+00:00' && zone != '+0000' && zone != '-00:00'
|
|
552
|
+
offset = zone_offset(zone, 0, zone.bytesize)
|
|
553
|
+
return text if offset.nil?
|
|
554
|
+
end
|
|
555
|
+
year = year.to_i
|
|
556
|
+
month = month.to_i
|
|
557
|
+
day = day.to_i
|
|
558
|
+
hour = hour.to_i
|
|
559
|
+
minute = minute.to_i
|
|
560
|
+
second = second.to_i
|
|
561
|
+
total = (hour * 3600 + minute * 60 + second) - offset
|
|
562
|
+
day_delta, total = total.divmod(86_400)
|
|
563
|
+
hour, remainder = total.divmod(3600)
|
|
564
|
+
minute, second = remainder.divmod(60)
|
|
565
|
+
if day_delta != 0
|
|
566
|
+
year, month, day = CivilTime.civil_from_days(CivilTime.days_from_civil(year, month, day) + day_delta)
|
|
567
|
+
end
|
|
568
|
+
format_iso(year, month, day, hour, minute, second, millis)
|
|
569
|
+
end
|
|
570
|
+
|
|
571
|
+
def zone_offset(text, index, size)
|
|
572
|
+
sign_byte = text.getbyte(index)
|
|
573
|
+
return nil unless sign_byte == 43 || sign_byte == 45
|
|
574
|
+
|
|
575
|
+
negative = sign_byte == 45
|
|
576
|
+
hour = read_digits(text, index + 1, 2)
|
|
577
|
+
return nil if hour.nil?
|
|
578
|
+
|
|
579
|
+
cursor = index + 3
|
|
580
|
+
if cursor < size && text.getbyte(cursor) == 58
|
|
581
|
+
cursor += 1
|
|
582
|
+
end
|
|
583
|
+
minute = read_digits(text, cursor, 2)
|
|
584
|
+
return nil if minute.nil? || cursor + 2 != size
|
|
585
|
+
|
|
586
|
+
seconds = hour * 3600 + minute * 60
|
|
587
|
+
negative ? -seconds : seconds
|
|
588
|
+
end
|
|
589
|
+
|
|
590
|
+
def read_digits(text, start, count)
|
|
591
|
+
return nil if start + count > text.bytesize
|
|
592
|
+
|
|
593
|
+
number = 0
|
|
594
|
+
count.times do |offset|
|
|
595
|
+
byte = text.getbyte(start + offset)
|
|
596
|
+
return nil if byte < 48 || byte > 57
|
|
597
|
+
|
|
598
|
+
number = number * 10 + (byte - 48)
|
|
599
|
+
end
|
|
600
|
+
number
|
|
601
|
+
end
|
|
602
|
+
|
|
603
|
+
def fraction_to_millis(fraction)
|
|
604
|
+
return 0 if fraction.nil? || fraction.empty?
|
|
605
|
+
|
|
606
|
+
"#{fraction}000000"[0, 6].to_i / 1000
|
|
607
|
+
end
|
|
608
|
+
|
|
609
|
+
def format_iso(year, month, day, hour, minute, second, millis)
|
|
610
|
+
year = year.to_i
|
|
611
|
+
month = month.to_i
|
|
612
|
+
day = day.to_i
|
|
613
|
+
hour = hour.to_i
|
|
614
|
+
minute = minute.to_i
|
|
615
|
+
second = second.to_i
|
|
616
|
+
millis = millis.to_i
|
|
617
|
+
if year.between?(0, 9999) && month.between?(1, 12) && day.between?(1, 31) &&
|
|
618
|
+
hour.between?(0, 23) && minute.between?(0, 59) && second.between?(0, 59) && millis.between?(0, 999)
|
|
619
|
+
return CivilTime.iso_utc(year, month, day, hour, minute, second, millis)
|
|
620
|
+
end
|
|
621
|
+
|
|
622
|
+
format('%04d-%02d-%02dT%02d:%02d:%02d.%03dZ', year, month, day, hour, minute, second, millis)
|
|
623
|
+
end
|
|
624
|
+
|
|
625
|
+
def buffer_value(value)
|
|
626
|
+
return nil if value.nil?
|
|
627
|
+
if value.is_a?(Hash) && value['type'] == 'Buffer'
|
|
628
|
+
return { 'type' => 'Buffer', 'data' => value['data'] }
|
|
629
|
+
end
|
|
630
|
+
if value.is_a?(Array)
|
|
631
|
+
return { 'type' => 'Buffer', 'data' => value }
|
|
632
|
+
end
|
|
633
|
+
# Connector BINARY is raw bytes. REST cells are base64 text.
|
|
634
|
+
if value.is_a?(String) && value.encoding == Encoding::ASCII_8BIT
|
|
635
|
+
return { 'type' => 'Buffer', 'data' => value.bytes }
|
|
636
|
+
end
|
|
637
|
+
|
|
638
|
+
{ 'type' => 'Buffer', 'data' => Base64.decode64(value.to_s).bytes }
|
|
639
|
+
end
|
|
640
|
+
|
|
641
|
+
def table_identity(table)
|
|
642
|
+
schema_name = table[:schemaName] || table['schemaName'] || table[:schema_name] || table['schema_name']
|
|
643
|
+
table_name = table[:tableName] || table['tableName'] || table[:table_name] || table['table_name']
|
|
644
|
+
[schema_name, table_name]
|
|
208
645
|
end
|
|
209
646
|
end
|
|
210
647
|
end
|