|
| 1 | +import { parse } from 'pgsql-ast-parser'; |
| 2 | +import { ParameterValueClause, QuerySchema, StreamParseOptions } from './types.js'; |
| 3 | +import { SqlRuleError } from './errors.js'; |
| 4 | +import { isSelectStatement } from './utils.js'; |
| 5 | +import { checkUnsupportedFeatures, isClauseError } from './sql_support.js'; |
| 6 | +import { SqlDataQuery, SqlDataQueryOptions } from './SqlDataQuery.js'; |
| 7 | +import { RowValueExtractor } from './BaseSqlDataQuery.js'; |
| 8 | +import { TablePattern } from './TablePattern.js'; |
| 9 | +import { TableQuerySchema } from './TableQuerySchema.js'; |
| 10 | +import { SqlTools } from './sql_filters.js'; |
| 11 | +import { ExpressionType } from './ExpressionType.js'; |
| 12 | +import { SqlParameterQuery } from './SqlParameterQuery.js'; |
| 13 | +import { StaticSqlParameterQuery } from './StaticSqlParameterQuery.js'; |
| 14 | +import { DEFAULT_BUCKET_PRIORITY } from './BucketDescription.js'; |
| 15 | + |
| 16 | +/** |
| 17 | + * Represents a query backing a stream definition. |
| 18 | + * |
| 19 | + * Streams are a new way to define sync rules that don't require separate data and |
| 20 | + * parameter queries. However, since most of the sync service is built around that |
| 21 | + * distiction at the moment, stream queries are implemented by desugaring a unified |
| 22 | + * query into its individual components. |
| 23 | + */ |
| 24 | +export class StreamQuery { |
| 25 | + inferredParameters: (SqlParameterQuery | StaticSqlParameterQuery)[]; |
| 26 | + data: SqlDataQuery; |
| 27 | + |
| 28 | + static fromSql(descriptorName: string, sql: string, options: StreamParseOptions): [StreamQuery, SqlRuleError[]] { |
| 29 | + const [query, ...illegalRest] = parse(sql, { locationTracking: true }); |
| 30 | + const schema = options.schema; |
| 31 | + const parameters: (SqlParameterQuery | StaticSqlParameterQuery)[] = []; |
| 32 | + const errors: SqlRuleError[] = []; |
| 33 | + |
| 34 | + // TODO: Share more of this code with SqlDataQuery |
| 35 | + if (illegalRest.length > 0) { |
| 36 | + throw new SqlRuleError('Only a single SELECT statement is supported', sql, illegalRest[0]?._location); |
| 37 | + } |
| 38 | + |
| 39 | + if (!isSelectStatement(query)) { |
| 40 | + throw new SqlRuleError('Only SELECT statements are supported', sql, query._location); |
| 41 | + } |
| 42 | + |
| 43 | + if (query.from == null || query.from.length != 1 || query.from[0].type != 'table') { |
| 44 | + throw new SqlRuleError('Must SELECT from a single table', sql, query.from?.[0]._location); |
| 45 | + } |
| 46 | + |
| 47 | + errors.push(...checkUnsupportedFeatures(sql, query)); |
| 48 | + |
| 49 | + const tableRef = query.from?.[0].name; |
| 50 | + if (tableRef?.name == null) { |
| 51 | + throw new SqlRuleError('Must SELECT from a single table', sql, query.from?.[0]._location); |
| 52 | + } |
| 53 | + const alias: string = tableRef.alias ?? tableRef.name; |
| 54 | + |
| 55 | + const sourceTable = new TablePattern(tableRef.schema ?? options.defaultSchema, tableRef.name); |
| 56 | + let querySchema: QuerySchema | undefined = undefined; |
| 57 | + if (schema) { |
| 58 | + const tables = schema.getTables(sourceTable); |
| 59 | + if (tables.length == 0) { |
| 60 | + const e = new SqlRuleError( |
| 61 | + `Table ${sourceTable.schema}.${sourceTable.tablePattern} not found`, |
| 62 | + sql, |
| 63 | + query.from?.[0]?._location |
| 64 | + ); |
| 65 | + e.type = 'warning'; |
| 66 | + |
| 67 | + errors.push(e); |
| 68 | + } else { |
| 69 | + querySchema = new TableQuerySchema(tables, alias); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + const where = query.where; |
| 74 | + const tools = new SqlTools({ |
| 75 | + table: alias, |
| 76 | + parameterTables: [], |
| 77 | + valueTables: [alias], |
| 78 | + sql, |
| 79 | + schema: querySchema, |
| 80 | + supportsStreamInputs: true, |
| 81 | + supportsParameterExpressions: true |
| 82 | + }); |
| 83 | + tools.checkSpecificNameCase(tableRef); |
| 84 | + const filter = tools.compileWhereClause(where); |
| 85 | + const inputParameterNames = filter.inputParameters.map((p) => `bucket.${p.key}`); |
| 86 | + |
| 87 | + // Build parameter queries based on inferred bucket parameters |
| 88 | + if (tools.inferredParameters.length) { |
| 89 | + const extractors: Record<string, ParameterValueClause> = {}; |
| 90 | + for (const inferred of tools.inferredParameters) { |
| 91 | + extractors[inferred.name] = inferred.clause; |
| 92 | + } |
| 93 | + |
| 94 | + parameters.push( |
| 95 | + new StaticSqlParameterQuery({ |
| 96 | + sql, |
| 97 | + queryId: 'static', |
| 98 | + descriptorName, |
| 99 | + parameterExtractors: extractors, |
| 100 | + bucketParameters: tools.inferredParameters.map((p) => p.name), |
| 101 | + filter: undefined, // TODO |
| 102 | + priority: DEFAULT_BUCKET_PRIORITY // Ignored here |
| 103 | + }) |
| 104 | + ); |
| 105 | + } |
| 106 | + |
| 107 | + let hasId = false; |
| 108 | + let hasWildcard = false; |
| 109 | + let extractors: RowValueExtractor[] = []; |
| 110 | + |
| 111 | + for (let column of query.columns ?? []) { |
| 112 | + const name = tools.getOutputName(column); |
| 113 | + if (name != '*') { |
| 114 | + const clause = tools.compileRowValueExtractor(column.expr); |
| 115 | + if (isClauseError(clause)) { |
| 116 | + // Error logged already |
| 117 | + continue; |
| 118 | + } |
| 119 | + extractors.push({ |
| 120 | + extract: (tables, output) => { |
| 121 | + output[name] = clause.evaluate(tables); |
| 122 | + }, |
| 123 | + getTypes(schema, into) { |
| 124 | + const def = clause.getColumnDefinition(schema); |
| 125 | + |
| 126 | + into[name] = { name, type: def?.type ?? ExpressionType.NONE, originalType: def?.originalType }; |
| 127 | + } |
| 128 | + }); |
| 129 | + } else { |
| 130 | + extractors.push({ |
| 131 | + extract: (tables, output) => { |
| 132 | + const row = tables[alias]; |
| 133 | + for (let key in row) { |
| 134 | + if (key.startsWith('_')) { |
| 135 | + continue; |
| 136 | + } |
| 137 | + output[key] ??= row[key]; |
| 138 | + } |
| 139 | + }, |
| 140 | + getTypes(schema, into) { |
| 141 | + for (let column of schema.getColumns(alias)) { |
| 142 | + into[column.name] ??= column; |
| 143 | + } |
| 144 | + } |
| 145 | + }); |
| 146 | + } |
| 147 | + if (name == 'id') { |
| 148 | + hasId = true; |
| 149 | + } else if (name == '*') { |
| 150 | + hasWildcard = true; |
| 151 | + if (querySchema == null) { |
| 152 | + // Not performing schema-based validation - assume there is an id |
| 153 | + hasId = true; |
| 154 | + } else { |
| 155 | + const idType = querySchema.getColumn(alias, 'id')?.type ?? ExpressionType.NONE; |
| 156 | + if (!idType.isNone()) { |
| 157 | + hasId = true; |
| 158 | + } |
| 159 | + } |
| 160 | + } |
| 161 | + } |
| 162 | + if (!hasId) { |
| 163 | + const error = new SqlRuleError(`Query must return an "id" column`, sql, query.columns?.[0]._location); |
| 164 | + if (hasWildcard) { |
| 165 | + // Schema-based validations are always warnings |
| 166 | + error.type = 'warning'; |
| 167 | + } |
| 168 | + errors.push(error); |
| 169 | + } |
| 170 | + |
| 171 | + errors.push(...tools.errors); |
| 172 | + |
| 173 | + const data: SqlDataQueryOptions = { |
| 174 | + sourceTable, |
| 175 | + table: alias, |
| 176 | + sql, |
| 177 | + filter, |
| 178 | + columns: query.columns ?? [], |
| 179 | + descriptorName, |
| 180 | + bucketParameters: inputParameterNames, |
| 181 | + tools, |
| 182 | + extractors |
| 183 | + }; |
| 184 | + return [new StreamQuery(parameters, data), errors]; |
| 185 | + } |
| 186 | + |
| 187 | + private constructor(parameters: (SqlParameterQuery | StaticSqlParameterQuery)[], data: SqlDataQueryOptions) { |
| 188 | + this.inferredParameters = parameters; |
| 189 | + this.data = new SqlDataQuery(data); |
| 190 | + } |
| 191 | +} |
0 commit comments