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,457 @@
1
+ # Pivot Template System - SDK SIDE
2
+ #
3
+ # Port of node-sdk/src/utils/pivotTemplate.ts. The metadata server returns a
4
+ # SQL template plus a distinctValuesQuery; the SDK runs that query against the
5
+ # customer database, then hydrates the template with the distinct values.
6
+ require 'json'
7
+
8
+ module PivotTemplate
9
+ MAX_PIVOT_UNIQUE_VALUES = 250
10
+ PIVOT_COLUMN_MARKER = '{{QUILL_PIVOT_COLUMNS}}'.freeze
11
+ PIVOT_COLUMN_ALIAS_MARKER = '{{QUILL_PIVOT_COLUMN_ALIASES}}'.freeze
12
+
13
+ module_function
14
+
15
+ # post_quill symbolizes keys, but be tolerant of string keys too.
16
+ def get(hash, key)
17
+ return nil unless hash.is_a?(Hash)
18
+ hash.key?(key.to_sym) ? hash[key.to_sym] : hash[key.to_s]
19
+ end
20
+
21
+ # ------------------------------------------------------------------
22
+ # Helpers
23
+ # ------------------------------------------------------------------
24
+
25
+ # Dialects whose single-quoted string literals treat backslash as an escape
26
+ # character, so a backslash in the value must itself be escaped or a trailing
27
+ # `\` would swallow the closing quote. Postgres (standard_conforming_strings,
28
+ # the default) and MSSQL treat backslash literally.
29
+ BACKSLASH_ESCAPES_IN_STRINGS = %w[snowflake clickhouse mysql bigquery databricks].freeze
30
+
31
+ # Dialects whose quoted identifiers treat backslash as an escape character.
32
+ BACKSLASH_ESCAPES_IN_IDENTIFIERS = %w[clickhouse bigquery].freeze
33
+
34
+ # NUL can terminate the statement in some drivers; it is never valid data here.
35
+ def strip_nul(value)
36
+ value.to_s.delete("\0")
37
+ end
38
+
39
+ # Escapes `value` for use inside a single-quoted SQL string literal. The
40
+ # distinct values this is applied to come from the customer's database, so
41
+ # they must be treated as hostile.
42
+ #
43
+ # `''` is the portable quote escape and is what MSSQL and Postgres require.
44
+ # BigQuery and Databricks do not treat `''` as an escape (adjacent literals
45
+ # concatenate instead), so they get `\'`; their backslashes are escaped first
46
+ # so the result is unambiguous.
47
+ #
48
+ # Block form throughout: a plain "\\'" replacement string would mean post-match.
49
+ def process_single_quotes(value, database_type)
50
+ dialect = database_type.to_s.downcase
51
+ escaped = strip_nul(value)
52
+ escaped = escaped.gsub('\\') { '\\\\' } if BACKSLASH_ESCAPES_IN_STRINGS.include?(dialect)
53
+ if %w[bigquery databricks].include?(dialect)
54
+ escaped.gsub("'") { "\\'" }
55
+ else
56
+ escaped.gsub("'") { "''" }
57
+ end
58
+ end
59
+
60
+ # Escapes `name` for use inside a quoted identifier (the pivot column alias).
61
+ # Returns the body only; the caller adds the delimiters. The delimiter is
62
+ # doubled rather than stripped so the alias round-trips to the distinct value.
63
+ def escape_identifier(name, database_type)
64
+ dialect = database_type.to_s.downcase
65
+ escaped = strip_nul(name)
66
+ escaped = escaped.gsub('\\') { '\\\\' } if BACKSLASH_ESCAPES_IN_IDENTIFIERS.include?(dialect)
67
+ case dialect
68
+ when 'postgresql', 'redshift', 'snowflake' then escaped.gsub('"') { '""' }
69
+ when 'clickhouse' then escaped.gsub('"') { '\\"' }
70
+ when 'mysql', 'databricks' then escaped.gsub('`') { '``' }
71
+ when 'bigquery' then escaped.gsub('`') { '\\`' }
72
+ when 'mssql' then escaped.gsub(']') { ']]' }
73
+ else escaped
74
+ end
75
+ end
76
+
77
+ # Aggregate names that may be emitted as a bare function name. This is exactly
78
+ # the `aggregationType` enum on the Pivot schema. The value is concatenated
79
+ # straight into SQL with no re-parse, so anything not on this list has to
80
+ # degrade to something that is definitely a function.
81
+ #
82
+ # `percentage` is deliberately absent: it is not a SQL function. Its normal
83
+ # path is a dedicated branch in the template generator, and it only reaches
84
+ # here when that branch has already been skipped.
85
+ AGGREGATE_FUNCTIONS = {
86
+ 'sum' => 'sum', 'average' => 'AVG', 'avg' => 'avg',
87
+ 'min' => 'min', 'max' => 'max', 'count' => 'count'
88
+ }.freeze
89
+
90
+ def process_agg_type(agg_type, has_column_field = false)
91
+ requested = agg_type.to_s.strip.downcase
92
+ # A count over a bool is summed so the boolean is counted, not reported as a
93
+ # boolean; a percentage that fell through keeps the same semantics.
94
+ return 'SUM' if %w[count percentage].include?(requested) && has_column_field
95
+ AGGREGATE_FUNCTIONS.fetch(requested, 'count')
96
+ end
97
+
98
+ def get_float_type_name(database_type)
99
+ case database_type.to_s.downcase
100
+ when 'bigquery'
101
+ 'FLOAT64'
102
+ when 'clickhouse', 'click'
103
+ 'Nullable(Float64)'
104
+ else
105
+ 'FLOAT'
106
+ end
107
+ end
108
+
109
+ def cast_to_float(expression, database_type)
110
+ "CAST(#{expression} AS #{get_float_type_name(database_type)})"
111
+ end
112
+
113
+ # The delimiter pair each dialect uses for a quoted identifier.
114
+ IDENTIFIER_DELIMITERS = {
115
+ 'postgresql' => ['"', '"'],
116
+ 'redshift' => ['"', '"'],
117
+ 'snowflake' => ['"', '"'],
118
+ 'clickhouse' => ['"', '"'],
119
+ 'mysql' => ['`', '`'],
120
+ 'bigquery' => ['`', '`'],
121
+ 'databricks' => ['`', '`'],
122
+ 'mssql' => ['[', ']']
123
+ }.freeze
124
+
125
+ # Removes one *matching* outer quote pair and undoes the body escaping.
126
+ # Config text that already went through hydration (a saved pivot carries its
127
+ # hydrated column references) is pre-quoted, and quoting it again has to be a
128
+ # fixed point: `"a""b"` must come back as a`"`b rather than being escaped on
129
+ # top of itself.
130
+ #
131
+ # The inverse follows the dialect's own escape. The doubling dialects collapse
132
+ # `""` back to `"`; ClickHouse and BigQuery read a backslash as the escape and
133
+ # need `\"` decoded to `"` (and `\\` to `\`). One pass either way keeps the
134
+ # two backslash forms in order, which two chained gsubs would not.
135
+ def unquote_part(part, open, close, dialect)
136
+ return part unless part.length >= 2 && part.start_with?(open) && part.end_with?(close)
137
+
138
+ body = part[1..-2]
139
+ return body.gsub(close + close, close) unless BACKSLASH_ESCAPES_IN_IDENTIFIERS.include?(dialect)
140
+
141
+ decoded = +''
142
+ index = 0
143
+ while index < body.length
144
+ if body[index] == '\\' && index + 1 < body.length
145
+ decoded << body[index + 1]
146
+ index += 2
147
+ else
148
+ decoded << body[index]
149
+ index += 1
150
+ end
151
+ end
152
+ decoded
153
+ end
154
+
155
+ # Quotes `column` as an identifier, escaping the delimiter rather than
156
+ # deleting it so the name round-trips. `table.column` is quoted per part.
157
+ # Collapses a per-part quoted qualification into a single label. A saved pivot
158
+ # stores what hydration wrote at a *reference* (`"dbo"."status"`), but an
159
+ # alias is one label and `AS "a"."b"` is a syntax error, so each part is
160
+ # stripped of its own delimiters first. A value that is not delimited part by
161
+ # part is left alone, so a single label containing a dot is not split.
162
+ def collapse_qualified_identifier(value, database_type)
163
+ dialect = database_type.to_s.downcase
164
+ open, close = IDENTIFIER_DELIMITERS.fetch(dialect, ['"', '"'])
165
+ parts = value.split('.')
166
+ return value if parts.length < 2
167
+
168
+ # a fully delimited single label (`"a.b"`) is not a qualification
169
+ if unquote_part(value, open, close, dialect) != value
170
+ inner = value[1..-2]
171
+ return value unless inner.include?(open) || inner.include?(close)
172
+ end
173
+
174
+ unquoted = parts.map { |part| unquote_part(part, open, close, dialect) }
175
+ return value if unquoted.zip(parts).any? { |u, p| u == p }
176
+
177
+ unquoted.join('.')
178
+ end
179
+
180
+ # Quotes `column` as one identifier label. `quote_column_reference` is the
181
+ # variant that treats a dot as a qualification; an output alias must use this
182
+ # one, because `AS "a"."b"` is a syntax error and an alias is a single label
183
+ # even when the name contains a dot.
184
+ def quote_identifier(column, database_type)
185
+ dialect = database_type.to_s.downcase
186
+ open, close = IDENTIFIER_DELIMITERS.fetch(dialect, ['"', '"'])
187
+ body = escape_identifier(
188
+ unquote_part(collapse_qualified_identifier(column.to_s, database_type), open, close, dialect),
189
+ database_type
190
+ )
191
+ body = body.gsub('/', 'quill_forward_slash') if dialect == 'bigquery'
192
+ "#{open}#{body}#{close}"
193
+ end
194
+
195
+ # Quotes `column` as a reference, where a dot is a qualification
196
+ # (`job.status` becomes `"job"."status"`). A single fully delimited label may
197
+ # contain dots itself, so it is not a qualification.
198
+ def quote_column_reference(column, database_type)
199
+ dialect = database_type.to_s.downcase
200
+ open, close = IDENTIFIER_DELIMITERS.fetch(dialect, ['"', '"'])
201
+ value = column.to_s
202
+ parts = value.split('.')
203
+ return quote_identifier(value, database_type) if parts.length == 1
204
+ # a single fully delimited label may itself contain dots (`"a.b"`), so a
205
+ # value whose delimiters wrap the whole thing is one label
206
+ if unquote_part(value, open, close, dialect) != value
207
+ inner = value[1..-2]
208
+ return quote_identifier(value, database_type) unless inner.include?(open) || inner.include?(close)
209
+ end
210
+
211
+ parts.map do |part|
212
+ quote_identifier(unquote_part(part, open, close, dialect), database_type)
213
+ end.join('.')
214
+ end
215
+
216
+ def process_column_reference(column, database_type, fallback_on_null = nil, is_column_field_alias = false, is_value_field_alias = false)
217
+ return quote_identifier(fallback_on_null || '_', database_type) if column == ''
218
+
219
+ # Quoting is positional: an alias is one label, a reference is quoted per
220
+ # part. The server writes the alias and the SDK references it, so the two
221
+ # have to agree exactly.
222
+ if is_column_field_alias || is_value_field_alias
223
+ return quote_identifier(column, database_type)
224
+ end
225
+ quote_column_reference(column, database_type)
226
+ end
227
+
228
+ # `value_field` arrives as an already resolved alias, so it is re-quoted as
229
+ # one label rather than re-split on its dots.
230
+ def process_value_field(agg_type, database_type, value_field)
231
+ if agg_type == 'min' || agg_type == 'max' || agg_type.to_s.downcase == 'average'
232
+ return "#{quote_identifier(value_field, database_type)} ELSE null"
233
+ end
234
+ return '1 ELSE 0' if agg_type == 'count'
235
+ value_field != '' ? "#{quote_identifier(value_field, database_type)} ELSE 0" : '1 ELSE 0'
236
+ end
237
+
238
+ # A bool value field is aggregated as 0/1. SQL Server has no boolean
239
+ # expressions, so a BIT column cannot stand alone as a CASE condition there.
240
+ def bool_to_int_expr(bool_column, database_type)
241
+ condition = database_type.to_s.downcase == 'mssql' ? "#{bool_column} = 1" : bool_column
242
+ "CASE WHEN #{condition} THEN 1 ELSE 0 END"
243
+ end
244
+
245
+ # Floor a percentage denominator at 1 so an empty group divides by 1, not 0.
246
+ # GREATEST only exists from SQL Server 2022, so mssql spells it out.
247
+ def at_least_one(expr, database_type)
248
+ if database_type.to_s.downcase == 'mssql'
249
+ "(CASE WHEN #{expr} > 1 THEN #{expr} ELSE 1 END)"
250
+ else
251
+ "GREATEST(#{expr}, 1)"
252
+ end
253
+ end
254
+
255
+ # ------------------------------------------------------------------
256
+ # match_casing (mirrors node-sdk matchCasing)
257
+ # ------------------------------------------------------------------
258
+
259
+ def match_casing(text, template)
260
+ return text.to_s if text.to_s.empty? || template.to_s.empty?
261
+ if template.match?(/\A[A-Z][a-z]*([A-Z][a-z]*)*\z/)
262
+ text.downcase.gsub(/\b\w/) { |c| c.upcase }
263
+ elsif template.match?(/\A[a-z]+([A-Z][a-z]*)*\z/)
264
+ text.gsub(/_./) { |m| m[1].upcase }.downcase
265
+ elsif template.match?(/\A[a-z0-9]+(_[a-z0-9]+)*\z/)
266
+ text.gsub(/[A-Z]/) { |m| "_#{m.downcase}" }
267
+ elsif template.match?(/\A[a-z]+\z/)
268
+ text.downcase
269
+ elsif template.match?(/\A[A-Z]+\z/)
270
+ text.upcase
271
+ elsif template.match?(/\A[A-Z][a-z]*\z/)
272
+ text[0].upcase + text[1..].downcase
273
+ elsif template.match?(/\A[A-Z][A-Z0-9]*(_[A-Z0-9]+)*\z/)
274
+ text.gsub(/([A-Z])/, '_\1').sub(/\A_/, '').upcase
275
+ else
276
+ text
277
+ end
278
+ end
279
+
280
+ # ------------------------------------------------------------------
281
+ # Distinct values parsing
282
+ # ------------------------------------------------------------------
283
+
284
+ # Parses a Postgres array literal such as {a,"b, c",NULL}.
285
+ def parse_pg_array_literal(literal)
286
+ literal = literal.strip
287
+ return [] unless literal.length >= 2 && literal.start_with?('{') && literal.end_with?('}')
288
+ inner = literal[1..-2]
289
+ return [] if inner.empty?
290
+
291
+ values = []
292
+ current = +''
293
+ in_quotes = false
294
+ quoted = false
295
+ i = 0
296
+ while i < inner.length
297
+ c = inner[i]
298
+ if in_quotes && c == '\\' && i + 1 < inner.length
299
+ i += 1
300
+ current << inner[i]
301
+ elsif c == '"'
302
+ in_quotes = !in_quotes
303
+ quoted = true
304
+ elsif c == ',' && !in_quotes
305
+ values << (!quoted && current == 'NULL' ? '' : current)
306
+ current = +''
307
+ quoted = false
308
+ else
309
+ current << c
310
+ end
311
+ i += 1
312
+ end
313
+ values << (!quoted && current == 'NULL' ? '' : current)
314
+ values
315
+ end
316
+
317
+ # Extracts the string_values column of the first row of a distinctValuesQuery
318
+ # result (one entry of run_queries[:queryResults]).
319
+ def parse_distinct_values(query_result, database_type)
320
+ rows = get(query_result, :rows)
321
+ return [] if rows.nil? || rows.empty?
322
+ raw = get(rows.first, :string_values)
323
+ return [] if raw.nil?
324
+
325
+ values =
326
+ if raw.is_a?(Array)
327
+ raw
328
+ elsif raw.is_a?(String)
329
+ str = raw.strip
330
+ if database_type.to_s.downcase == 'mssql'
331
+ str.split(',').map(&:strip)
332
+ elsif str.start_with?('[')
333
+ begin
334
+ parsed = JSON.parse(str)
335
+ parsed.is_a?(Array) ? parsed : []
336
+ rescue JSON::ParserError
337
+ []
338
+ end
339
+ elsif str.start_with?('{')
340
+ parse_pg_array_literal(str)
341
+ else
342
+ []
343
+ end
344
+ else
345
+ []
346
+ end
347
+
348
+ values.reject { |v| v.nil? || v == '' }.map(&:to_s)
349
+ end
350
+
351
+ # ------------------------------------------------------------------
352
+ # Template hydration
353
+ # ------------------------------------------------------------------
354
+
355
+ # Hydrates a pivot query template with actual distinct values.
356
+ # Mirrors node-sdk hydratePivotTemplate.
357
+ def hydrate_pivot_template(template, distinct_values, config)
358
+ column_field = get(config, :columnField)
359
+ row_field = get(config, :rowField)
360
+ aggregations = get(config, :aggregations) || []
361
+ database_type = get(config, :databaseType) || 'postgresql'
362
+
363
+ return template if !get(config, :requiresDistinctValues) || column_field.to_s.empty? || row_field.to_s.empty?
364
+
365
+ filtered_values = distinct_values.reject { |v| v.nil? || v == '' }.first(MAX_PIVOT_UNIQUE_VALUES)
366
+
367
+ column_field_alias = process_column_reference(column_field, database_type, nil, false, true)
368
+ row_field_alias = process_column_reference(row_field, database_type, nil, false, true)
369
+
370
+ column_aliases = ["#{process_column_reference(row_field, database_type, nil, true)} AS #{row_field_alias}"]
371
+ case_when_columns = []
372
+ seen_aggs = Hash.new { |h, k| h[k] = Hash.new(0) }
373
+
374
+ aggregations.each do |agg|
375
+ agg_type = get(agg, :aggregationType).to_s
376
+ value_field = get(agg, :valueField).to_s
377
+ value_field2 = get(agg, :valueField2).to_s
378
+ value_field_type = get(agg, :valueFieldType)
379
+ value_field2_type = get(agg, :valueField2Type)
380
+
381
+ seen_aggs[agg_type][value_field] += 1
382
+ disambiguation_index = seen_aggs[agg_type][value_field].to_s
383
+ disambiguation_index = '' if disambiguation_index == '1'
384
+
385
+ value_field_source = value_field.empty? ? (row_field.to_s.empty? ? 'count' : row_field) : value_field
386
+ value_field_alias = process_column_reference(value_field_source, database_type, nil, false, true)
387
+ value_alias_substring = value_field.empty? ? '' : "#{process_column_reference(value_field, database_type, nil, true)} AS #{value_field_alias}"
388
+
389
+ disambiguation_field = seen_aggs[agg_type].values.sum > 1 ? "_#{value_field}#{disambiguation_index}" : ''
390
+ disambiguation = ''
391
+ if aggregations.length > 1
392
+ disambiguation = disambiguation_field.empty? ? "_#{agg_type}" : "#{disambiguation_field}_#{match_casing(agg_type, value_field)}"
393
+ end
394
+
395
+ has_value_field = !value_field.empty?
396
+ value_expr =
397
+ if value_field_type == 'bool'
398
+ bool_to_int_expr(value_field_alias, database_type)
399
+ elsif agg_type == 'percentage' && !has_value_field
400
+ '1 ELSE 0'
401
+ else
402
+ process_value_field(agg_type, database_type, value_field_alias)
403
+ end
404
+
405
+ if agg_type == 'percentage'
406
+ has_any_value_field = !value_field.empty? || !value_field2.empty?
407
+ value_field2_source = value_field2.empty? ? (value_field.empty? ? 'count' : value_field) : value_field2
408
+ value_field2_alias = process_column_reference(value_field2_source, database_type, nil, false, true)
409
+ value2_expr = (value_field2_type || value_field_type) == 'bool' ? bool_to_int_expr(value_field2_alias, database_type) : value_field2_alias
410
+ value2_alias_substring =
411
+ if !value_field2.empty? && value_field != value_field2
412
+ "#{process_column_reference(value_field2, database_type, nil, true)} AS #{value_field2_alias}"
413
+ else
414
+ ''
415
+ end
416
+
417
+ if value_field == value_field2 || value_field2.empty?
418
+ denominator_expr = has_any_value_field ? "sum(#{value2_expr})" : 'COUNT(*)'
419
+ filtered_values.each do |column|
420
+ numerator = "sum(CASE WHEN #{column_field_alias} = '#{process_single_quotes(column, database_type)}' THEN #{value_expr} END)"
421
+ case_when_columns << "#{cast_to_float(numerator, database_type)} / #{at_least_one(denominator_expr, database_type)} AS #{process_column_reference(column.to_s + disambiguation, database_type, '_', true)}"
422
+ end
423
+ else
424
+ filtered_values.each do |column|
425
+ quoted = process_single_quotes(column, database_type)
426
+ numerator = "sum(CASE WHEN #{column_field_alias} = '#{quoted}' THEN #{value_expr} END)"
427
+ denominator = "sum(CASE WHEN #{column_field_alias} = '#{quoted}' THEN #{value2_expr} END)"
428
+ case_when_columns << "#{cast_to_float(numerator, database_type)} / #{at_least_one(denominator, database_type)} AS #{process_column_reference(column.to_s + disambiguation, database_type, '_', true)}"
429
+ end
430
+ column_aliases << value2_alias_substring unless value2_alias_substring.empty?
431
+ end
432
+ else
433
+ filtered_values.each do |column|
434
+ case_when_columns << "#{process_agg_type(agg_type, true)}(CASE WHEN #{column_field_alias} = '#{process_single_quotes(column, database_type)}' THEN #{value_expr} END) AS #{process_column_reference(column.to_s + disambiguation, database_type, '_', true)}"
435
+ end
436
+ end
437
+
438
+ column_aliases << value_alias_substring unless value_alias_substring.empty?
439
+ end
440
+
441
+ column_aliases << "#{process_column_reference(column_field, database_type, nil, true)} AS #{column_field_alias}"
442
+
443
+ # Block form on purpose: SQL may contain backslashes/quotes that gsub would
444
+ # otherwise interpret as back-references in a replacement string.
445
+ aliases_sql = column_aliases.uniq.join(', ')
446
+ hydrated = template.gsub(PIVOT_COLUMN_ALIAS_MARKER) { aliases_sql }
447
+ if case_when_columns.empty?
448
+ hydrated = hydrated.gsub(/,\s*\{\{QUILL_PIVOT_COLUMNS\}\}/, '')
449
+ hydrated = hydrated.gsub(/\s*\{\{QUILL_PIVOT_COLUMNS\}\},?/, '')
450
+ hydrated = hydrated.gsub(PIVOT_COLUMN_MARKER, '')
451
+ else
452
+ columns_sql = case_when_columns.join(', ')
453
+ hydrated = hydrated.gsub(PIVOT_COLUMN_MARKER) { columns_sql }
454
+ end
455
+ hydrated
456
+ end
457
+ end
@@ -0,0 +1,169 @@
1
+ require 'json'
2
+ require 'net/http'
3
+ require 'openssl'
4
+ require 'pg'
5
+
6
+ class QuillAPIError < StandardError; end
7
+
8
+ # This call failed. `public_message` is the string that goes on `error`.
9
+ class QuillRequestError < QuillAPIError
10
+ # `public_message` says what the failure means, without its fields; safe to send to a browser.
11
+ # `unreachable` is true when the peer could not be reached, so it never answered.
12
+ attr_reader :origin, :public_message, :unreachable
13
+
14
+ def initialize(origin, message, public_message, unreachable)
15
+ super(message)
16
+ @origin = origin
17
+ @public_message = public_message
18
+ @unreachable = unreachable
19
+ end
20
+ end
21
+
22
+ # Formats and logs every SDK failure.
23
+ module ReportError
24
+ PG_WIRE = {
25
+ severity: PG::PG_DIAG_SEVERITY, code: PG::PG_DIAG_SQLSTATE, detail: PG::PG_DIAG_MESSAGE_DETAIL,
26
+ hint: PG::PG_DIAG_MESSAGE_HINT, position: PG::PG_DIAG_STATEMENT_POSITION,
27
+ internalQuery: PG::PG_DIAG_INTERNAL_QUERY, schema: PG::PG_DIAG_SCHEMA_NAME,
28
+ table: PG::PG_DIAG_TABLE_NAME, column: PG::PG_DIAG_COLUMN_NAME,
29
+ constraint: PG::PG_DIAG_CONSTRAINT_NAME, routine: PG::PG_DIAG_SOURCE_FUNCTION
30
+ }.freeze
31
+ # The diagnostic fields each origin reports, in order, and where the driver keeps each one:
32
+ # a field of the PG wire error, or a method of the error (for metadata, of the HTTP response).
33
+ FIELDS = {
34
+ 'postgres' => PG_WIRE, 'redshift' => PG_WIRE,
35
+ 'mysql' => { errno: :error_number, sqlState: :sql_state },
36
+ 'mssql' => { number: :db_error_number, class: :severity },
37
+ 'snowflake' => { code: :code, sqlState: :sql_state },
38
+ 'bigquery' => { code: :code, reason: :reason, location: :location },
39
+ 'clickhouse' => { code: :code, type: :type },
40
+ 'databricks' => { errorCode: :error_code, sqlState: :sql_state },
41
+ 'metadata' => { status: :code, body: :body }, 'cache' => {}, 'sdk' => {}
42
+ }.freeze
43
+ # What each origin is called on `error`.
44
+ LABELS = {
45
+ 'postgres' => 'PostgreSQL', 'redshift' => 'Redshift', 'mysql' => 'MySQL', 'mssql' => 'SQL Server',
46
+ 'snowflake' => 'Snowflake', 'bigquery' => 'BigQuery', 'clickhouse' => 'ClickHouse',
47
+ 'databricks' => 'Databricks', 'metadata' => 'Quill server', 'cache' => 'Cache', 'sdk' => 'Quill SDK'
48
+ }.freeze
49
+ # The three failures `error` words itself, the same on every engine. Any other failure keeps
50
+ # the database's message.
51
+ SENTENCES = [
52
+ 'The login was rejected.',
53
+ 'The database user does not have permission to run this query.',
54
+ 'The query timed out or was cancelled.'
55
+ ].freeze
56
+ PG_CODES = ['28000 28P01', '42501', '57014'].freeze
57
+ # The codes each engine gives those three failures, in that order.
58
+ ENGINE_CODES = {
59
+ 'postgres' => PG_CODES, 'redshift' => PG_CODES,
60
+ 'mysql' => ['1045 1698', '1044 1142 1143 1227', '1317 3024'],
61
+ 'mssql' => ['18456', '229 230 262', ''],
62
+ 'snowflake' => %w[390100 42501 57014],
63
+ 'clickhouse' => ['516', '497', '159 394'],
64
+ # An HTTP status, and the `reason` of a BigQuery error.
65
+ 'bigquery' => ['401', 'accessDenied', 'timeout stopped'],
66
+ 'databricks' => ['401', '42501', '57KD0 HY008']
67
+ }.freeze
68
+ # The fields above that hold a code.
69
+ CODE_FIELDS = %i[code errno number sqlState errorCode reason].freeze
70
+ # When each background line was last logged, and the repeats skipped since. The tests clear it.
71
+ REPEATS = {}
72
+
73
+ # The origin a database type reports under. A type the SDK has no driver for is `sdk`.
74
+ def self.origin_of(database_type)
75
+ name = database_type.to_s.downcase
76
+ name = 'postgres' if name == 'postgresql'
77
+ FIELDS.key?(name) && !%w[metadata cache].include?(name) ? name : 'sdk'
78
+ end
79
+
80
+ # Reports a failure once: an error that was already reported is returned as it is.
81
+ def self.report_request(origin, context, err)
82
+ err.is_a?(QuillRequestError) ? err : QuillRequestError.new(origin, *report('request', origin, context, err))
83
+ end
84
+
85
+ def self.report_background(origin, context, err)
86
+ report('background', origin, context, err)
87
+ nil
88
+ end
89
+
90
+ # True when the peer never answered: a socket, DNS, TLS or timeout failure, pg's connection
91
+ # failure, the connect errors of mysql2 (CR_*) and tiny_tds (SYBECONN, SYBEUHST), or an
92
+ # error one of these caused.
93
+ def self.unreachable?(err)
94
+ return false unless err.is_a?(Exception)
95
+
96
+ [SystemCallError, SocketError, Timeout::Error, OpenSSL::SSL::SSLError, PG::ConnectionBad]
97
+ .any? { |type| err.is_a?(type) } ||
98
+ (err.respond_to?(:error_number) && [2002, 2003, 2005].include?(err.error_number)) ||
99
+ (err.respond_to?(:db_error_number) && [20_009, 20_012].include?(err.db_error_number)) ||
100
+ unreachable?(err.cause)
101
+ end
102
+
103
+ # True when the peer took the connection and then did not answer in time, or for an error
104
+ # that such a timeout caused.
105
+ def self.read_timeout?(err)
106
+ err.is_a?(Exception) && (err.is_a?(Net::ReadTimeout) || read_timeout?(err.cause))
107
+ end
108
+
109
+ # Logs a background line. One that keeps repeating is logged once a minute, with a count.
110
+ def self.log_background(line)
111
+ now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
112
+ last = REPEATS[line]
113
+ if last && now - last[:at] < 60
114
+ last[:skipped] += 1
115
+ return
116
+ end
117
+ # A line carries text from the failure, so the map is emptied before it grows without limit.
118
+ REPEATS.clear if REPEATS.size >= 1000
119
+ REPEATS[line] = { at: now, skipped: 0 }
120
+ warn(last && last[:skipped].positive? ? "#{line} (#{last[:skipped]} more since last logged)" : line)
121
+ end
122
+
123
+ # Builds the `[full, public]` strings for one failure, logs the full one, and says whether
124
+ # the peer never answered. The full string is the raw failure with its fields; the public one
125
+ # says what it means. `err` is an error, a message, or a metadata server's response.
126
+ def self.report(kind, origin, context, err)
127
+ fallback = if context == 'connect' then 'Could not connect'
128
+ elsif origin == 'metadata' then 'Metadata request failed'
129
+ else "#{context.tr(':', ' ').capitalize} failed"
130
+ end
131
+ wire = err.result if err.is_a?(PG::Error)
132
+ http = err.is_a?(Net::HTTPResponse)
133
+ data = (JSON.parse(err.body.to_s) rescue err.body.to_s) if http
134
+ sent = data['error'] if data.is_a?(Hash)
135
+ # A driver can pass on bytes that are not valid in the message's encoding, so it is scrubbed.
136
+ message = if http then sent.is_a?(String) ? sent : (sent.to_json if sent)
137
+ else wire&.error_field(PG::PG_DIAG_MESSAGE_PRIMARY) || (err.is_a?(Exception) ? err.message : err)
138
+ end.to_s.scrub.strip.gsub(/\s*\n\s*/, ' ')
139
+ # A database or a Quill server that answered the connection and not the request is slow,
140
+ # not unreachable.
141
+ timed_out = (ENGINE_CODES.key?(origin) || origin == 'metadata') && read_timeout?(err)
142
+ unreachable = unreachable?(err) && !timed_out
143
+
144
+ values = FIELDS[origin].to_h do |name, source|
145
+ [name, if source.is_a?(Integer) then wire&.error_field(source)
146
+ elsif name == :body then (data[0, 500] if data.is_a?(String))
147
+ elsif err.respond_to?(source) then err.public_send(source)
148
+ end]
149
+ end
150
+ summary = message.empty? ? fallback : message
151
+ parts = values.filter_map { |name, value| "#{name}: #{value}" unless value.to_s.empty? || value.to_s == message }
152
+ full = "#{origin}: #{summary}#{" (#{parts.join('; ')})" unless parts.empty?}"
153
+ line = "[quill] #{kind} #{origin} #{context}: #{full}"
154
+ kind == 'request' ? warn(line) : log_background(line)
155
+
156
+ codes = values.values_at(*CODE_FIELDS).map(&:to_s)
157
+ failure = ENGINE_CODES.fetch(origin, []).index { |row| (row.split & codes).any? }
158
+ text = if failure then SENTENCES[failure]
159
+ elsif timed_out then origin == 'metadata' ? 'Metadata request timed out' : SENTENCES[2]
160
+ elsif !unreachable then summary
161
+ elsif ENGINE_CODES.key?(origin) then 'Connection to database failed.'
162
+ else 'The connection failed.'
163
+ end
164
+ # The metadata server's own message reaches the caller as the server wrote it, because
165
+ # clients match on its text.
166
+ passed_on = sent.is_a?(String) && !sent.strip.empty?
167
+ [full, passed_on ? sent : "#{LABELS[origin]}: #{text}", unreachable]
168
+ end
169
+ end
@@ -12,6 +12,12 @@ end
12
12
  module RunQueryProcesses
13
13
  def self.remove_fields(query_results, fields_to_remove)
14
14
  fields = query_results[:fields].reject { |field| fields_to_remove.include?(field[:name]) }
15
+ first_row = query_results[:rows].first
16
+ if fields.length == query_results[:fields].length &&
17
+ (first_row.nil? || fields_to_remove.none? { |field| first_row.key?(field) })
18
+ return { fields: fields, rows: query_results[:rows] }
19
+ end
20
+
15
21
  rows = query_results[:rows].map do |row|
16
22
  fields_to_remove.each { |field| row.delete(field) }
17
23
  row
@@ -19,10 +25,26 @@ module RunQueryProcesses
19
25
  { fields: fields, rows: rows }
20
26
  end
21
27
 
22
- def self.map_queries(queries, target_connection)
23
- queries.map do |query|
24
- result = target_connection.query(query)
25
- result[:rows]
28
+ def self.map_queries(queries, target_connection, overwrite_cache = false)
29
+ run = ->(query) { target_connection.query(query, overwrite_cache)[:rows] }
30
+ # Postgres and Redshift each check out their own pooled connection; the other clients are not pooled.
31
+ return queries.map(&run) unless %w[postgresql redshift].include?(target_connection.database_type.to_s.downcase)
32
+
33
+ threads = []
34
+ begin
35
+ queries.each do |query|
36
+ threads << Thread.new do
37
+ Thread.current.report_on_exception = false
38
+ run.call(query)
39
+ end
40
+ end
41
+ threads.map(&:value)
42
+ ensure
43
+ threads.each do |t|
44
+ t.join
45
+ rescue StandardError
46
+ nil
47
+ end
26
48
  end
27
49
  end
28
50