drizzle-orm
Version:
Drizzle ORM package for SQL databases
1 lines • 69.3 kB
Source Map (JSON)
{"version":3,"sources":["../../src/gel-core/dialect.ts"],"sourcesContent":["import { aliasedTable, aliasedTableColumn, mapColumnsInAliasedSQLToAlias, mapColumnsInSQLToAlias } from '~/alias.ts';\nimport { CasingCache } from '~/casing.ts';\nimport { Column } from '~/column.ts';\nimport { entityKind, is } from '~/entity.ts';\nimport { DrizzleError } from '~/errors.ts';\nimport { GelColumn, GelDecimal, GelJson, GelUUID } from '~/gel-core/columns/index.ts';\nimport type {\n\tAnyGelSelectQueryBuilder,\n\tGelDeleteConfig,\n\tGelInsertConfig,\n\tGelSelectJoinConfig,\n\tGelUpdateConfig,\n} from '~/gel-core/query-builders/index.ts';\nimport type { GelSelectConfig, SelectedFieldsOrdered } from '~/gel-core/query-builders/select.types.ts';\nimport { GelTable } from '~/gel-core/table.ts';\nimport {\n\ttype BuildRelationalQueryResult,\n\ttype DBQueryConfig,\n\tgetOperators,\n\tgetOrderByOperators,\n\tMany,\n\tnormalizeRelation,\n\tOne,\n\ttype Relation,\n\ttype TableRelationalConfig,\n\ttype TablesRelationalConfig,\n} from '~/relations.ts';\nimport { and, eq, View } from '~/sql/index.ts';\nimport {\n\ttype DriverValueEncoder,\n\ttype Name,\n\tParam,\n\ttype QueryTypingsValue,\n\ttype QueryWithTypings,\n\tSQL,\n\tsql,\n\ttype SQLChunk,\n} from '~/sql/sql.ts';\nimport { Subquery } from '~/subquery.ts';\nimport { getTableName, getTableUniqueName, Table } from '~/table.ts';\nimport { type Casing, orderSelectedFields, type UpdateSet } from '~/utils.ts';\nimport { ViewBaseConfig } from '~/view-common.ts';\nimport { GelTimestamp } from './columns/timestamp.ts';\nimport { GelViewBase } from './view-base.ts';\nimport type { GelMaterializedView } from './view.ts';\n\nexport interface GelDialectConfig {\n\tcasing?: Casing;\n}\n\nexport class GelDialect {\n\tstatic readonly [entityKind]: string = 'GelDialect';\n\n\t/** @internal */\n\treadonly casing: CasingCache;\n\n\tconstructor(config?: GelDialectConfig) {\n\t\tthis.casing = new CasingCache(config?.casing);\n\t}\n\n\t// TODO can not migrate gel with drizzle\n\t// async migrate(migrations: MigrationMeta[], session: GelSession, config: string | MigrationConfig): Promise<void> {\n\t// \tconst migrationsTable = typeof config === 'string'\n\t// \t\t? '__drizzle_migrations'\n\t// \t\t: config.migrationsTable ?? '__drizzle_migrations';\n\t// \tconst migrationsSchema = typeof config === 'string' ? 'drizzle' : config.migrationsSchema ?? 'drizzle';\n\t// \tconst migrationTableCreate = sql`\n\t// \t\tCREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} (\n\t// \t\t\tid SERIAL PRIMARY KEY,\n\t// \t\t\thash text NOT NULL,\n\t// \t\t\tcreated_at bigint\n\t// \t\t)\n\t// \t`;\n\t// \tawait session.execute(sql`CREATE SCHEMA IF NOT EXISTS ${sql.identifier(migrationsSchema)}`);\n\t// \tawait session.execute(migrationTableCreate);\n\n\t// \tconst dbMigrations = await session.all<{ id: number; hash: string; created_at: string }>(\n\t// \t\tsql`select id, hash, created_at from ${sql.identifier(migrationsSchema)}.${\n\t// \t\t\tsql.identifier(migrationsTable)\n\t// \t\t} order by created_at desc limit 1`,\n\t// \t);\n\n\t// \tconst lastDbMigration = dbMigrations[0];\n\t// \tawait session.transaction(async (tx) => {\n\t// \t\tfor await (const migration of migrations) {\n\t// \t\t\tif (\n\t// \t\t\t\t!lastDbMigration\n\t// \t\t\t\t|| Number(lastDbMigration.created_at) < migration.folderMillis\n\t// \t\t\t) {\n\t// \t\t\t\tfor (const stmt of migration.sql) {\n\t// \t\t\t\t\tawait tx.execute(sql.raw(stmt));\n\t// \t\t\t\t}\n\t// \t\t\t\tawait tx.execute(\n\t// \t\t\t\t\tsql`insert into ${sql.identifier(migrationsSchema)}.${\n\t// \t\t\t\t\t\tsql.identifier(migrationsTable)\n\t// \t\t\t\t\t} (\"hash\", \"created_at\") values(${migration.hash}, ${migration.folderMillis})`,\n\t// \t\t\t\t);\n\t// \t\t\t}\n\t// \t\t}\n\t// \t});\n\t// }\n\n\tescapeName(name: string): string {\n\t\treturn `\"${name}\"`;\n\t}\n\n\tescapeParam(num: number): string {\n\t\treturn `$${num + 1}`;\n\t}\n\n\tescapeString(str: string): string {\n\t\treturn `'${str.replace(/'/g, \"''\")}'`;\n\t}\n\n\tprivate buildWithCTE(queries: Subquery[] | undefined): SQL | undefined {\n\t\tif (!queries?.length) return undefined;\n\n\t\tconst withSqlChunks = [sql`with `];\n\t\tfor (const [i, w] of queries.entries()) {\n\t\t\twithSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`);\n\t\t\tif (i < queries.length - 1) {\n\t\t\t\twithSqlChunks.push(sql`, `);\n\t\t\t}\n\t\t}\n\t\twithSqlChunks.push(sql` `);\n\t\treturn sql.join(withSqlChunks);\n\t}\n\n\tbuildDeleteQuery({ table, where, returning, withList }: GelDeleteConfig): SQL {\n\t\tconst withSql = this.buildWithCTE(withList);\n\n\t\tconst returningSql = returning\n\t\t\t? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}`\n\t\t\t: undefined;\n\n\t\tconst whereSql = where ? sql` where ${where}` : undefined;\n\n\t\treturn sql`${withSql}delete from ${table}${whereSql}${returningSql}`;\n\t}\n\n\tbuildUpdateSet(table: GelTable, set: UpdateSet): SQL {\n\t\tconst tableColumns = table[Table.Symbol.Columns];\n\n\t\tconst columnNames = Object.keys(tableColumns).filter((colName) =>\n\t\t\tset[colName] !== undefined || tableColumns[colName]?.onUpdateFn !== undefined\n\t\t);\n\n\t\tconst setSize = columnNames.length;\n\t\treturn sql.join(columnNames.flatMap((colName, i) => {\n\t\t\tconst col = tableColumns[colName]!;\n\n\t\t\tconst value = set[colName] ?? sql.param(col.onUpdateFn!(), col);\n\t\t\tconst res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;\n\n\t\t\tif (i < setSize - 1) {\n\t\t\t\treturn [res, sql.raw(', ')];\n\t\t\t}\n\t\t\treturn [res];\n\t\t}));\n\t}\n\n\tbuildUpdateQuery({ table, set, where, returning, withList, from, joins }: GelUpdateConfig): SQL {\n\t\tconst withSql = this.buildWithCTE(withList);\n\n\t\tconst tableName = table[GelTable.Symbol.Name];\n\t\tconst tableSchema = table[GelTable.Symbol.Schema];\n\t\tconst origTableName = table[GelTable.Symbol.OriginalName];\n\t\tconst alias = tableName === origTableName ? undefined : tableName;\n\t\tconst tableSql = sql`${tableSchema ? sql`${sql.identifier(tableSchema)}.` : undefined}${\n\t\t\tsql.identifier(origTableName)\n\t\t}${alias && sql` ${sql.identifier(alias)}`}`;\n\n\t\tconst setSql = this.buildUpdateSet(table, set);\n\n\t\tconst fromSql = from && sql.join([sql.raw(' from '), this.buildFromTable(from)]);\n\n\t\tconst joinsSql = this.buildJoins(joins);\n\n\t\tconst returningSql = returning\n\t\t\t? sql` returning ${this.buildSelection(returning, { isSingleTable: !from })}`\n\t\t\t: undefined;\n\n\t\tconst whereSql = where ? sql` where ${where}` : undefined;\n\n\t\treturn sql`${withSql}update ${tableSql} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}`;\n\t}\n\n\t/**\n\t * Builds selection SQL with provided fields/expressions\n\t *\n\t * Examples:\n\t *\n\t * `select <selection> from`\n\t *\n\t * `insert ... returning <selection>`\n\t *\n\t * If `isSingleTable` is true, then columns won't be prefixed with table name\n\t * ^ Temporarily disabled behaviour, see comments within method for a reasoning\n\t */\n\tprivate buildSelection(\n\t\tfields: SelectedFieldsOrdered,\n\t\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\t\t{ isSingleTable = false }: { isSingleTable?: boolean } = {},\n\t): SQL {\n\t\tconst columnsLen = fields.length;\n\n\t\tconst chunks = fields\n\t\t\t.flatMap(({ field }, i) => {\n\t\t\t\tconst chunk: SQLChunk[] = [];\n\n\t\t\t\tif (is(field, SQL.Aliased) && field.isSelectionField) {\n\t\t\t\t\tchunk.push(sql.identifier(field.fieldAlias));\n\t\t\t\t} else if (is(field, SQL.Aliased) || is(field, SQL)) {\n\t\t\t\t\tconst query = is(field, SQL.Aliased) ? field.sql : field;\n\n\t\t\t\t\t// Gel throws an error when more than one similarly named columns exist within context instead of preferring the closest one\n\t\t\t\t\t// thus forcing us to be explicit about column's source\n\t\t\t\t\t// if (isSingleTable) {\n\t\t\t\t\t// \tchunk.push(\n\t\t\t\t\t// \t\tnew SQL(\n\t\t\t\t\t// \t\t\tquery.queryChunks.map((c) => {\n\t\t\t\t\t// \t\t\t\tif (is(c, GelColumn)) {\n\t\t\t\t\t// \t\t\t\t\treturn sql.identifier(this.casing.getColumnCasing(c));\n\t\t\t\t\t// \t\t\t\t}\n\t\t\t\t\t// \t\t\t\treturn c;\n\t\t\t\t\t// \t\t\t}),\n\t\t\t\t\t// \t\t),\n\t\t\t\t\t// \t);\n\t\t\t\t\t// } else {\n\t\t\t\t\tchunk.push(query);\n\t\t\t\t\t// }\n\n\t\t\t\t\tif (is(field, SQL.Aliased)) {\n\t\t\t\t\t\tchunk.push(sql` as ${sql.identifier(field.fieldAlias)}`);\n\t\t\t\t\t}\n\t\t\t\t} else if (is(field, Column)) {\n\t\t\t\t\t// Gel throws an error when more than one similarly named columns exist within context instead of preferring the closest one\n\t\t\t\t\t// thus forcing us to be explicit about column's source\n\t\t\t\t\t// if (isSingleTable) {\n\t\t\t\t\t// \tchunk.push(sql.identifier(this.casing.getColumnCasing(field)));\n\t\t\t\t\t// } else {\n\t\t\t\t\tchunk.push(field);\n\t\t\t\t\t// }\n\t\t\t\t}\n\n\t\t\t\tif (i < columnsLen - 1) {\n\t\t\t\t\tchunk.push(sql`, `);\n\t\t\t\t}\n\n\t\t\t\treturn chunk;\n\t\t\t});\n\n\t\treturn sql.join(chunks);\n\t}\n\n\tprivate buildJoins(joins: GelSelectJoinConfig[] | undefined): SQL | undefined {\n\t\tif (!joins || joins.length === 0) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst joinsArray: SQL[] = [];\n\n\t\tfor (const [index, joinMeta] of joins.entries()) {\n\t\t\tif (index === 0) {\n\t\t\t\tjoinsArray.push(sql` `);\n\t\t\t}\n\t\t\tconst table = joinMeta.table;\n\t\t\tconst lateralSql = joinMeta.lateral ? sql` lateral` : undefined;\n\t\t\tconst onSql = joinMeta.on ? sql` on ${joinMeta.on}` : undefined;\n\n\t\t\tif (is(table, GelTable)) {\n\t\t\t\tconst tableName = table[GelTable.Symbol.Name];\n\t\t\t\tconst tableSchema = table[GelTable.Symbol.Schema];\n\t\t\t\tconst origTableName = table[GelTable.Symbol.OriginalName];\n\t\t\t\tconst alias = tableName === origTableName ? undefined : joinMeta.alias;\n\t\t\t\tjoinsArray.push(\n\t\t\t\t\tsql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${\n\t\t\t\t\t\ttableSchema ? sql`${sql.identifier(tableSchema)}.` : undefined\n\t\t\t\t\t}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`,\n\t\t\t\t);\n\t\t\t} else if (is(table, View)) {\n\t\t\t\tconst viewName = table[ViewBaseConfig].name;\n\t\t\t\tconst viewSchema = table[ViewBaseConfig].schema;\n\t\t\t\tconst origViewName = table[ViewBaseConfig].originalName;\n\t\t\t\tconst alias = viewName === origViewName ? undefined : joinMeta.alias;\n\t\t\t\tjoinsArray.push(\n\t\t\t\t\tsql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${\n\t\t\t\t\t\tviewSchema ? sql`${sql.identifier(viewSchema)}.` : undefined\n\t\t\t\t\t}${sql.identifier(origViewName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tjoinsArray.push(\n\t\t\t\t\tsql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${table}${onSql}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (index < joins.length - 1) {\n\t\t\t\tjoinsArray.push(sql` `);\n\t\t\t}\n\t\t}\n\n\t\treturn sql.join(joinsArray);\n\t}\n\n\tprivate buildFromTable(\n\t\ttable: SQL | Subquery | GelViewBase | GelTable | undefined,\n\t): SQL | Subquery | GelViewBase | GelTable | undefined {\n\t\tif (is(table, Table) && table[Table.Symbol.OriginalName] !== table[Table.Symbol.Name]) {\n\t\t\tlet fullName = sql`${sql.identifier(table[Table.Symbol.OriginalName])}`;\n\t\t\tif (table[Table.Symbol.Schema]) {\n\t\t\t\tfullName = sql`${sql.identifier(table[Table.Symbol.Schema]!)}.${fullName}`;\n\t\t\t}\n\t\t\treturn sql`${fullName} ${sql.identifier(table[Table.Symbol.Name])}`;\n\t\t}\n\n\t\treturn table;\n\t}\n\n\tbuildSelectQuery(\n\t\t{\n\t\t\twithList,\n\t\t\tfields,\n\t\t\tfieldsFlat,\n\t\t\twhere,\n\t\t\thaving,\n\t\t\ttable,\n\t\t\tjoins,\n\t\t\torderBy,\n\t\t\tgroupBy,\n\t\t\tlimit,\n\t\t\toffset,\n\t\t\tlockingClause,\n\t\t\tdistinct,\n\t\t\tsetOperators,\n\t\t}: GelSelectConfig,\n\t): SQL {\n\t\tconst fieldsList = fieldsFlat ?? orderSelectedFields<GelColumn>(fields);\n\t\tfor (const f of fieldsList) {\n\t\t\tif (\n\t\t\t\tis(f.field, Column)\n\t\t\t\t&& getTableName(f.field.table)\n\t\t\t\t\t!== (is(table, Subquery)\n\t\t\t\t\t\t? table._.alias\n\t\t\t\t\t\t: is(table, GelViewBase)\n\t\t\t\t\t\t? table[ViewBaseConfig].name\n\t\t\t\t\t\t: is(table, SQL)\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: getTableName(table))\n\t\t\t\t&& !((table) =>\n\t\t\t\t\tjoins?.some(({ alias }) =>\n\t\t\t\t\t\talias === (table[Table.Symbol.IsAlias] ? getTableName(table) : table[Table.Symbol.BaseName])\n\t\t\t\t\t))(f.field.table)\n\t\t\t) {\n\t\t\t\tconst tableName = getTableName(f.field.table);\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Your \"${\n\t\t\t\t\t\tf.path.join('->')\n\t\t\t\t\t}\" field references a column \"${tableName}\".\"${f.field.name}\", but the table \"${tableName}\" is not part of the query! Did you forget to join it?`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst isSingleTable = !joins || joins.length === 0;\n\n\t\tconst withSql = this.buildWithCTE(withList);\n\n\t\tlet distinctSql: SQL | undefined;\n\t\tif (distinct) {\n\t\t\tdistinctSql = distinct === true ? sql` distinct` : sql` distinct on (${sql.join(distinct.on, sql`, `)})`;\n\t\t}\n\n\t\tconst selection = this.buildSelection(fieldsList, { isSingleTable });\n\n\t\tconst tableSql = this.buildFromTable(table);\n\n\t\tconst joinsSql = this.buildJoins(joins);\n\n\t\tconst whereSql = where ? sql` where ${where}` : undefined;\n\n\t\tconst havingSql = having ? sql` having ${having}` : undefined;\n\n\t\tlet orderBySql;\n\t\tif (orderBy && orderBy.length > 0) {\n\t\t\torderBySql = sql` order by ${sql.join(orderBy, sql`, `)}`;\n\t\t}\n\n\t\tlet groupBySql;\n\t\tif (groupBy && groupBy.length > 0) {\n\t\t\tgroupBySql = sql` group by ${sql.join(groupBy, sql`, `)}`;\n\t\t}\n\n\t\tconst limitSql = typeof limit === 'object' || (typeof limit === 'number' && limit >= 0)\n\t\t\t? sql` limit ${limit}`\n\t\t\t: undefined;\n\n\t\tconst offsetSql = offset ? sql` offset ${offset}` : undefined;\n\n\t\tconst lockingClauseSql = sql.empty();\n\t\tif (lockingClause) {\n\t\t\tconst clauseSql = sql` for ${sql.raw(lockingClause.strength)}`;\n\t\t\tif (lockingClause.config.of) {\n\t\t\t\tclauseSql.append(\n\t\t\t\t\tsql` of ${\n\t\t\t\t\t\tsql.join(\n\t\t\t\t\t\t\tArray.isArray(lockingClause.config.of) ? lockingClause.config.of : [lockingClause.config.of],\n\t\t\t\t\t\t\tsql`, `,\n\t\t\t\t\t\t)\n\t\t\t\t\t}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (lockingClause.config.noWait) {\n\t\t\t\tclauseSql.append(sql` nowait`);\n\t\t\t} else if (lockingClause.config.skipLocked) {\n\t\t\t\tclauseSql.append(sql` skip locked`);\n\t\t\t}\n\t\t\tlockingClauseSql.append(clauseSql);\n\t\t}\n\t\tconst finalQuery =\n\t\t\tsql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClauseSql}`;\n\n\t\tif (setOperators.length > 0) {\n\t\t\treturn this.buildSetOperations(finalQuery, setOperators);\n\t\t}\n\n\t\treturn finalQuery;\n\t}\n\n\tbuildSetOperations(leftSelect: SQL, setOperators: GelSelectConfig['setOperators']): SQL {\n\t\tconst [setOperator, ...rest] = setOperators;\n\n\t\tif (!setOperator) {\n\t\t\tthrow new Error('Cannot pass undefined values to any set operator');\n\t\t}\n\n\t\tif (rest.length === 0) {\n\t\t\treturn this.buildSetOperationQuery({ leftSelect, setOperator });\n\t\t}\n\n\t\t// Some recursive magic here\n\t\treturn this.buildSetOperations(\n\t\t\tthis.buildSetOperationQuery({ leftSelect, setOperator }),\n\t\t\trest,\n\t\t);\n\t}\n\n\tbuildSetOperationQuery({\n\t\tleftSelect,\n\t\tsetOperator: { type, isAll, rightSelect, limit, orderBy, offset },\n\t}: { leftSelect: SQL; setOperator: GelSelectConfig['setOperators'][number] }): SQL {\n\t\tconst leftChunk = sql`(${leftSelect.getSQL()}) `;\n\t\tconst rightChunk = sql`(${rightSelect.getSQL()})`;\n\n\t\tlet orderBySql;\n\t\tif (orderBy && orderBy.length > 0) {\n\t\t\tconst orderByValues: (SQL<unknown> | Name)[] = [];\n\n\t\t\t// The next bit is necessary because the sql operator replaces ${table.column} with `table`.`column`\n\t\t\t// which is invalid Sql syntax, Table from one of the SELECTs cannot be used in global ORDER clause\n\t\t\tfor (const singleOrderBy of orderBy) {\n\t\t\t\tif (is(singleOrderBy, GelColumn)) {\n\t\t\t\t\torderByValues.push(sql.identifier(singleOrderBy.name));\n\t\t\t\t} else if (is(singleOrderBy, SQL)) {\n\t\t\t\t\tfor (let i = 0; i < singleOrderBy.queryChunks.length; i++) {\n\t\t\t\t\t\tconst chunk = singleOrderBy.queryChunks[i];\n\n\t\t\t\t\t\tif (is(chunk, GelColumn)) {\n\t\t\t\t\t\t\tsingleOrderBy.queryChunks[i] = sql.identifier(chunk.name);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\torderByValues.push(sql`${singleOrderBy}`);\n\t\t\t\t} else {\n\t\t\t\t\torderByValues.push(sql`${singleOrderBy}`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\torderBySql = sql` order by ${sql.join(orderByValues, sql`, `)} `;\n\t\t}\n\n\t\tconst limitSql = typeof limit === 'object' || (typeof limit === 'number' && limit >= 0)\n\t\t\t? sql` limit ${limit}`\n\t\t\t: undefined;\n\n\t\tconst operatorChunk = sql.raw(`${type} ${isAll ? 'all ' : ''}`);\n\n\t\tconst offsetSql = offset ? sql` offset ${offset}` : undefined;\n\n\t\treturn sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;\n\t}\n\n\tbuildInsertQuery(\n\t\t{ table, values: valuesOrSelect, onConflict, returning, withList, select, overridingSystemValue_ }: GelInsertConfig,\n\t): SQL {\n\t\tconst valuesSqlList: ((SQLChunk | SQL)[] | SQL)[] = [];\n\t\tconst columns: Record<string, GelColumn> = table[Table.Symbol.Columns];\n\n\t\tconst colEntries: [string, GelColumn][] = Object.entries(columns).filter(([_, col]) => !col.shouldDisableInsert());\n\n\t\tconst insertOrder = colEntries.map(\n\t\t\t([, column]) => sql.identifier(this.casing.getColumnCasing(column)),\n\t\t);\n\n\t\tif (select) {\n\t\t\tconst select = valuesOrSelect as AnyGelSelectQueryBuilder | SQL;\n\n\t\t\tif (is(select, SQL)) {\n\t\t\t\tvaluesSqlList.push(select);\n\t\t\t} else {\n\t\t\t\tvaluesSqlList.push(select.getSQL());\n\t\t\t}\n\t\t} else {\n\t\t\tconst values = valuesOrSelect as Record<string, Param | SQL>[];\n\t\t\tvaluesSqlList.push(sql.raw('values '));\n\n\t\t\tfor (const [valueIndex, value] of values.entries()) {\n\t\t\t\tconst valueList: (SQLChunk | SQL)[] = [];\n\t\t\t\tfor (const [fieldName, col] of colEntries) {\n\t\t\t\t\tconst colValue = value[fieldName];\n\t\t\t\t\tif (colValue === undefined || (is(colValue, Param) && colValue.value === undefined)) {\n\t\t\t\t\t\t// eslint-disable-next-line unicorn/no-negated-condition\n\t\t\t\t\t\tif (col.defaultFn !== undefined) {\n\t\t\t\t\t\t\tconst defaultFnResult = col.defaultFn();\n\t\t\t\t\t\t\tconst defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);\n\t\t\t\t\t\t\tvalueList.push(defaultValue);\n\t\t\t\t\t\t\t// eslint-disable-next-line unicorn/no-negated-condition\n\t\t\t\t\t\t} else if (!col.default && col.onUpdateFn !== undefined) {\n\t\t\t\t\t\t\tconst onUpdateFnResult = col.onUpdateFn();\n\t\t\t\t\t\t\tconst newValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);\n\t\t\t\t\t\t\tvalueList.push(newValue);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tvalueList.push(sql`default`);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvalueList.push(colValue);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tvaluesSqlList.push(valueList);\n\t\t\t\tif (valueIndex < values.length - 1) {\n\t\t\t\t\tvaluesSqlList.push(sql`, `);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst withSql = this.buildWithCTE(withList);\n\n\t\tconst valuesSql = sql.join(valuesSqlList);\n\n\t\tconst returningSql = returning\n\t\t\t? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}`\n\t\t\t: undefined;\n\n\t\tconst onConflictSql = onConflict ? sql` on conflict ${onConflict}` : undefined;\n\n\t\tconst overridingSql = overridingSystemValue_ === true ? sql`overriding system value ` : undefined;\n\n\t\treturn sql`${withSql}insert into ${table} ${insertOrder} ${overridingSql}${valuesSql}${onConflictSql}${returningSql}`;\n\t}\n\n\tbuildRefreshMaterializedViewQuery(\n\t\t{ view, concurrently, withNoData }: { view: GelMaterializedView; concurrently?: boolean; withNoData?: boolean },\n\t): SQL {\n\t\tconst concurrentlySql = concurrently ? sql` concurrently` : undefined;\n\t\tconst withNoDataSql = withNoData ? sql` with no data` : undefined;\n\n\t\treturn sql`refresh materialized view${concurrentlySql} ${view}${withNoDataSql}`;\n\t}\n\n\tprepareTyping(encoder: DriverValueEncoder<unknown, unknown>): QueryTypingsValue {\n\t\tif (is(encoder, GelJson)) {\n\t\t\treturn 'json';\n\t\t} else if (is(encoder, GelDecimal)) {\n\t\t\treturn 'decimal';\n\t\t} else if (is(encoder, GelTimestamp)) {\n\t\t\treturn 'timestamp';\n\t\t} else if (is(encoder, GelUUID)) {\n\t\t\treturn 'uuid';\n\t\t} else {\n\t\t\treturn 'none';\n\t\t}\n\t}\n\n\tsqlToQuery(sql: SQL, invokeSource?: 'indexes' | undefined): QueryWithTypings {\n\t\treturn sql.toQuery({\n\t\t\tcasing: this.casing,\n\t\t\tescapeName: this.escapeName,\n\t\t\tescapeParam: this.escapeParam,\n\t\t\tescapeString: this.escapeString,\n\t\t\tprepareTyping: this.prepareTyping,\n\t\t\tinvokeSource,\n\t\t});\n\t}\n\n\t// buildRelationalQueryWithPK({\n\t// \tfullSchema,\n\t// \tschema,\n\t// \ttableNamesMap,\n\t// \ttable,\n\t// \ttableConfig,\n\t// \tqueryConfig: config,\n\t// \ttableAlias,\n\t// \tisRoot = false,\n\t// \tjoinOn,\n\t// }: {\n\t// \tfullSchema: Record<string, unknown>;\n\t// \tschema: TablesRelationalConfig;\n\t// \ttableNamesMap: Record<string, string>;\n\t// \ttable: GelTable;\n\t// \ttableConfig: TableRelationalConfig;\n\t// \tqueryConfig: true | DBQueryConfig<'many', true>;\n\t// \ttableAlias: string;\n\t// \tisRoot?: boolean;\n\t// \tjoinOn?: SQL;\n\t// }): BuildRelationalQueryResult<GelTable, GelColumn> {\n\t// \t// For { \"<relation>\": true }, return a table with selection of all columns\n\t// \tif (config === true) {\n\t// \t\tconst selectionEntries = Object.entries(tableConfig.columns);\n\t// \t\tconst selection: BuildRelationalQueryResult<GelTable, GelColumn>['selection'] = selectionEntries.map((\n\t// \t\t\t[key, value],\n\t// \t\t) => ({\n\t// \t\t\tdbKey: value.name,\n\t// \t\t\ttsKey: key,\n\t// \t\t\tfield: value as GelColumn,\n\t// \t\t\trelationTableTsKey: undefined,\n\t// \t\t\tisJson: false,\n\t// \t\t\tselection: [],\n\t// \t\t}));\n\n\t// \t\treturn {\n\t// \t\t\ttableTsKey: tableConfig.tsName,\n\t// \t\t\tsql: table,\n\t// \t\t\tselection,\n\t// \t\t};\n\t// \t}\n\n\t// \t// let selection: BuildRelationalQueryResult<GelTable, GelColumn>['selection'] = [];\n\t// \t// let selectionForBuild = selection;\n\n\t// \tconst aliasedColumns = Object.fromEntries(\n\t// \t\tObject.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]),\n\t// \t);\n\n\t// \tconst aliasedRelations = Object.fromEntries(\n\t// \t\tObject.entries(tableConfig.relations).map(([key, value]) => [key, aliasedRelation(value, tableAlias)]),\n\t// \t);\n\n\t// \tconst aliasedFields = Object.assign({}, aliasedColumns, aliasedRelations);\n\n\t// \tlet where, hasUserDefinedWhere;\n\t// \tif (config.where) {\n\t// \t\tconst whereSql = typeof config.where === 'function' ? config.where(aliasedFields, operators) : config.where;\n\t// \t\twhere = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);\n\t// \t\thasUserDefinedWhere = !!where;\n\t// \t}\n\t// \twhere = and(joinOn, where);\n\n\t// \t// const fieldsSelection: { tsKey: string; value: GelColumn | SQL.Aliased; isExtra?: boolean }[] = [];\n\t// \tlet joins: Join[] = [];\n\t// \tlet selectedColumns: string[] = [];\n\n\t// \t// Figure out which columns to select\n\t// \tif (config.columns) {\n\t// \t\tlet isIncludeMode = false;\n\n\t// \t\tfor (const [field, value] of Object.entries(config.columns)) {\n\t// \t\t\tif (value === undefined) {\n\t// \t\t\t\tcontinue;\n\t// \t\t\t}\n\n\t// \t\t\tif (field in tableConfig.columns) {\n\t// \t\t\t\tif (!isIncludeMode && value === true) {\n\t// \t\t\t\t\tisIncludeMode = true;\n\t// \t\t\t\t}\n\t// \t\t\t\tselectedColumns.push(field);\n\t// \t\t\t}\n\t// \t\t}\n\n\t// \t\tif (selectedColumns.length > 0) {\n\t// \t\t\tselectedColumns = isIncludeMode\n\t// \t\t\t\t? selectedColumns.filter((c) => config.columns?.[c] === true)\n\t// \t\t\t\t: Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));\n\t// \t\t}\n\t// \t} else {\n\t// \t\t// Select all columns if selection is not specified\n\t// \t\tselectedColumns = Object.keys(tableConfig.columns);\n\t// \t}\n\n\t// \t// for (const field of selectedColumns) {\n\t// \t// \tconst column = tableConfig.columns[field]! as GelColumn;\n\t// \t// \tfieldsSelection.push({ tsKey: field, value: column });\n\t// \t// }\n\n\t// \tlet initiallySelectedRelations: {\n\t// \t\ttsKey: string;\n\t// \t\tqueryConfig: true | DBQueryConfig<'many', false>;\n\t// \t\trelation: Relation;\n\t// \t}[] = [];\n\n\t// \t// let selectedRelations: BuildRelationalQueryResult<GelTable, GelColumn>['selection'] = [];\n\n\t// \t// Figure out which relations to select\n\t// \tif (config.with) {\n\t// \t\tinitiallySelectedRelations = Object.entries(config.with)\n\t// \t\t\t.filter((entry): entry is [typeof entry[0], NonNullable<typeof entry[1]>] => !!entry[1])\n\t// \t\t\t.map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey]! }));\n\t// \t}\n\n\t// \tconst manyRelations = initiallySelectedRelations.filter((r) =>\n\t// \t\tis(r.relation, Many)\n\t// \t\t&& (schema[tableNamesMap[r.relation.referencedTable[Table.Symbol.Name]]!]?.primaryKey.length ?? 0) > 0\n\t// \t);\n\t// \t// If this is the last Many relation (or there are no Many relations), we are on the innermost subquery level\n\t// \tconst isInnermostQuery = manyRelations.length < 2;\n\n\t// \tconst selectedExtras: {\n\t// \t\ttsKey: string;\n\t// \t\tvalue: SQL.Aliased;\n\t// \t}[] = [];\n\n\t// \t// Figure out which extras to select\n\t// \tif (isInnermostQuery && config.extras) {\n\t// \t\tconst extras = typeof config.extras === 'function'\n\t// \t\t\t? config.extras(aliasedFields, { sql })\n\t// \t\t\t: config.extras;\n\t// \t\tfor (const [tsKey, value] of Object.entries(extras)) {\n\t// \t\t\tselectedExtras.push({\n\t// \t\t\t\ttsKey,\n\t// \t\t\t\tvalue: mapColumnsInAliasedSQLToAlias(value, tableAlias),\n\t// \t\t\t});\n\t// \t\t}\n\t// \t}\n\n\t// \t// Transform `fieldsSelection` into `selection`\n\t// \t// `fieldsSelection` shouldn't be used after this point\n\t// \t// for (const { tsKey, value, isExtra } of fieldsSelection) {\n\t// \t// \tselection.push({\n\t// \t// \t\tdbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey]!.name,\n\t// \t// \t\ttsKey,\n\t// \t// \t\tfield: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,\n\t// \t// \t\trelationTableTsKey: undefined,\n\t// \t// \t\tisJson: false,\n\t// \t// \t\tisExtra,\n\t// \t// \t\tselection: [],\n\t// \t// \t});\n\t// \t// }\n\n\t// \tlet orderByOrig = typeof config.orderBy === 'function'\n\t// \t\t? config.orderBy(aliasedFields, orderByOperators)\n\t// \t\t: config.orderBy ?? [];\n\t// \tif (!Array.isArray(orderByOrig)) {\n\t// \t\torderByOrig = [orderByOrig];\n\t// \t}\n\t// \tconst orderBy = orderByOrig.map((orderByValue) => {\n\t// \t\tif (is(orderByValue, Column)) {\n\t// \t\t\treturn aliasedTableColumn(orderByValue, tableAlias) as GelColumn;\n\t// \t\t}\n\t// \t\treturn mapColumnsInSQLToAlias(orderByValue, tableAlias);\n\t// \t});\n\n\t// \tconst limit = isInnermostQuery ? config.limit : undefined;\n\t// \tconst offset = isInnermostQuery ? config.offset : undefined;\n\n\t// \t// For non-root queries without additional config except columns, return a table with selection\n\t// \tif (\n\t// \t\t!isRoot\n\t// \t\t&& initiallySelectedRelations.length === 0\n\t// \t\t&& selectedExtras.length === 0\n\t// \t\t&& !where\n\t// \t\t&& orderBy.length === 0\n\t// \t\t&& limit === undefined\n\t// \t\t&& offset === undefined\n\t// \t) {\n\t// \t\treturn {\n\t// \t\t\ttableTsKey: tableConfig.tsName,\n\t// \t\t\tsql: table,\n\t// \t\t\tselection: selectedColumns.map((key) => ({\n\t// \t\t\t\tdbKey: tableConfig.columns[key]!.name,\n\t// \t\t\t\ttsKey: key,\n\t// \t\t\t\tfield: tableConfig.columns[key] as GelColumn,\n\t// \t\t\t\trelationTableTsKey: undefined,\n\t// \t\t\t\tisJson: false,\n\t// \t\t\t\tselection: [],\n\t// \t\t\t})),\n\t// \t\t};\n\t// \t}\n\n\t// \tconst selectedRelationsWithoutPK:\n\n\t// \t// Process all relations without primary keys, because they need to be joined differently and will all be on the same query level\n\t// \tfor (\n\t// \t\tconst {\n\t// \t\t\ttsKey: selectedRelationTsKey,\n\t// \t\t\tqueryConfig: selectedRelationConfigValue,\n\t// \t\t\trelation,\n\t// \t\t} of initiallySelectedRelations\n\t// \t) {\n\t// \t\tconst normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);\n\t// \t\tconst relationTableName = relation.referencedTable[Table.Symbol.Name];\n\t// \t\tconst relationTableTsName = tableNamesMap[relationTableName]!;\n\t// \t\tconst relationTable = schema[relationTableTsName]!;\n\n\t// \t\tif (relationTable.primaryKey.length > 0) {\n\t// \t\t\tcontinue;\n\t// \t\t}\n\n\t// \t\tconst relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;\n\t// \t\tconst joinOn = and(\n\t// \t\t\t...normalizedRelation.fields.map((field, i) =>\n\t// \t\t\t\teq(\n\t// \t\t\t\t\taliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),\n\t// \t\t\t\t\taliasedTableColumn(field, tableAlias),\n\t// \t\t\t\t)\n\t// \t\t\t),\n\t// \t\t);\n\t// \t\tconst builtRelation = this.buildRelationalQueryWithoutPK({\n\t// \t\t\tfullSchema,\n\t// \t\t\tschema,\n\t// \t\t\ttableNamesMap,\n\t// \t\t\ttable: fullSchema[relationTableTsName] as GelTable,\n\t// \t\t\ttableConfig: schema[relationTableTsName]!,\n\t// \t\t\tqueryConfig: selectedRelationConfigValue,\n\t// \t\t\ttableAlias: relationTableAlias,\n\t// \t\t\tjoinOn,\n\t// \t\t\tnestedQueryRelation: relation,\n\t// \t\t});\n\t// \t\tconst field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier('data')}`.as(selectedRelationTsKey);\n\t// \t\tjoins.push({\n\t// \t\t\ton: sql`true`,\n\t// \t\t\ttable: new Subquery(builtRelation.sql as SQL, {}, relationTableAlias),\n\t// \t\t\talias: relationTableAlias,\n\t// \t\t\tjoinType: 'left',\n\t// \t\t\tlateral: true,\n\t// \t\t});\n\t// \t\tselectedRelations.push({\n\t// \t\t\tdbKey: selectedRelationTsKey,\n\t// \t\t\ttsKey: selectedRelationTsKey,\n\t// \t\t\tfield,\n\t// \t\t\trelationTableTsKey: relationTableTsName,\n\t// \t\t\tisJson: true,\n\t// \t\t\tselection: builtRelation.selection,\n\t// \t\t});\n\t// \t}\n\n\t// \tconst oneRelations = initiallySelectedRelations.filter((r): r is typeof r & { relation: One } =>\n\t// \t\tis(r.relation, One)\n\t// \t);\n\n\t// \t// Process all One relations with PKs, because they can all be joined on the same level\n\t// \tfor (\n\t// \t\tconst {\n\t// \t\t\ttsKey: selectedRelationTsKey,\n\t// \t\t\tqueryConfig: selectedRelationConfigValue,\n\t// \t\t\trelation,\n\t// \t\t} of oneRelations\n\t// \t) {\n\t// \t\tconst normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);\n\t// \t\tconst relationTableName = relation.referencedTable[Table.Symbol.Name];\n\t// \t\tconst relationTableTsName = tableNamesMap[relationTableName]!;\n\t// \t\tconst relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;\n\t// \t\tconst relationTable = schema[relationTableTsName]!;\n\n\t// \t\tif (relationTable.primaryKey.length === 0) {\n\t// \t\t\tcontinue;\n\t// \t\t}\n\n\t// \t\tconst joinOn = and(\n\t// \t\t\t...normalizedRelation.fields.map((field, i) =>\n\t// \t\t\t\teq(\n\t// \t\t\t\t\taliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),\n\t// \t\t\t\t\taliasedTableColumn(field, tableAlias),\n\t// \t\t\t\t)\n\t// \t\t\t),\n\t// \t\t);\n\t// \t\tconst builtRelation = this.buildRelationalQueryWithPK({\n\t// \t\t\tfullSchema,\n\t// \t\t\tschema,\n\t// \t\t\ttableNamesMap,\n\t// \t\t\ttable: fullSchema[relationTableTsName] as GelTable,\n\t// \t\t\ttableConfig: schema[relationTableTsName]!,\n\t// \t\t\tqueryConfig: selectedRelationConfigValue,\n\t// \t\t\ttableAlias: relationTableAlias,\n\t// \t\t\tjoinOn,\n\t// \t\t});\n\t// \t\tconst field = sql`case when ${sql.identifier(relationTableAlias)} is null then null else json_build_array(${\n\t// \t\t\tsql.join(\n\t// \t\t\t\tbuiltRelation.selection.map(({ field }) =>\n\t// \t\t\t\t\tis(field, SQL.Aliased)\n\t// \t\t\t\t\t\t? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}`\n\t// \t\t\t\t\t\t: is(field, Column)\n\t// \t\t\t\t\t\t? aliasedTableColumn(field, relationTableAlias)\n\t// \t\t\t\t\t\t: field\n\t// \t\t\t\t),\n\t// \t\t\t\tsql`, `,\n\t// \t\t\t)\n\t// \t\t}) end`.as(selectedRelationTsKey);\n\t// \t\tconst isLateralJoin = is(builtRelation.sql, SQL);\n\t// \t\tjoins.push({\n\t// \t\t\ton: isLateralJoin ? sql`true` : joinOn,\n\t// \t\t\ttable: is(builtRelation.sql, SQL)\n\t// \t\t\t\t? new Subquery(builtRelation.sql, {}, relationTableAlias)\n\t// \t\t\t\t: aliasedTable(builtRelation.sql, relationTableAlias),\n\t// \t\t\talias: relationTableAlias,\n\t// \t\t\tjoinType: 'left',\n\t// \t\t\tlateral: is(builtRelation.sql, SQL),\n\t// \t\t});\n\t// \t\tselectedRelations.push({\n\t// \t\t\tdbKey: selectedRelationTsKey,\n\t// \t\t\ttsKey: selectedRelationTsKey,\n\t// \t\t\tfield,\n\t// \t\t\trelationTableTsKey: relationTableTsName,\n\t// \t\t\tisJson: true,\n\t// \t\t\tselection: builtRelation.selection,\n\t// \t\t});\n\t// \t}\n\n\t// \tlet distinct: GelSelectConfig['distinct'];\n\t// \tlet tableFrom: GelTable | Subquery = table;\n\n\t// \t// Process first Many relation - each one requires a nested subquery\n\t// \tconst manyRelation = manyRelations[0];\n\t// \tif (manyRelation) {\n\t// \t\tconst {\n\t// \t\t\ttsKey: selectedRelationTsKey,\n\t// \t\t\tqueryConfig: selectedRelationQueryConfig,\n\t// \t\t\trelation,\n\t// \t\t} = manyRelation;\n\n\t// \t\tdistinct = {\n\t// \t\t\ton: tableConfig.primaryKey.map((c) => aliasedTableColumn(c as GelColumn, tableAlias)),\n\t// \t\t};\n\n\t// \t\tconst normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);\n\t// \t\tconst relationTableName = relation.referencedTable[Table.Symbol.Name];\n\t// \t\tconst relationTableTsName = tableNamesMap[relationTableName]!;\n\t// \t\tconst relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;\n\t// \t\tconst joinOn = and(\n\t// \t\t\t...normalizedRelation.fields.map((field, i) =>\n\t// \t\t\t\teq(\n\t// \t\t\t\t\taliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),\n\t// \t\t\t\t\taliasedTableColumn(field, tableAlias),\n\t// \t\t\t\t)\n\t// \t\t\t),\n\t// \t\t);\n\n\t// \t\tconst builtRelationJoin = this.buildRelationalQueryWithPK({\n\t// \t\t\tfullSchema,\n\t// \t\t\tschema,\n\t// \t\t\ttableNamesMap,\n\t// \t\t\ttable: fullSchema[relationTableTsName] as GelTable,\n\t// \t\t\ttableConfig: schema[relationTableTsName]!,\n\t// \t\t\tqueryConfig: selectedRelationQueryConfig,\n\t// \t\t\ttableAlias: relationTableAlias,\n\t// \t\t\tjoinOn,\n\t// \t\t});\n\n\t// \t\tconst builtRelationSelectionField = sql`case when ${\n\t// \t\t\tsql.identifier(relationTableAlias)\n\t// \t\t} is null then '[]' else json_agg(json_build_array(${\n\t// \t\t\tsql.join(\n\t// \t\t\t\tbuiltRelationJoin.selection.map(({ field }) =>\n\t// \t\t\t\t\tis(field, SQL.Aliased)\n\t// \t\t\t\t\t\t? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}`\n\t// \t\t\t\t\t\t: is(field, Column)\n\t// \t\t\t\t\t\t? aliasedTableColumn(field, relationTableAlias)\n\t// \t\t\t\t\t\t: field\n\t// \t\t\t\t),\n\t// \t\t\t\tsql`, `,\n\t// \t\t\t)\n\t// \t\t})) over (partition by ${sql.join(distinct.on, sql`, `)}) end`.as(selectedRelationTsKey);\n\t// \t\tconst isLateralJoin = is(builtRelationJoin.sql, SQL);\n\t// \t\tjoins.push({\n\t// \t\t\ton: isLateralJoin ? sql`true` : joinOn,\n\t// \t\t\ttable: isLateralJoin\n\t// \t\t\t\t? new Subquery(builtRelationJoin.sql as SQL, {}, relationTableAlias)\n\t// \t\t\t\t: aliasedTable(builtRelationJoin.sql as GelTable, relationTableAlias),\n\t// \t\t\talias: relationTableAlias,\n\t// \t\t\tjoinType: 'left',\n\t// \t\t\tlateral: isLateralJoin,\n\t// \t\t});\n\n\t// \t\t// Build the \"from\" subquery with the remaining Many relations\n\t// \t\tconst builtTableFrom = this.buildRelationalQueryWithPK({\n\t// \t\t\tfullSchema,\n\t// \t\t\tschema,\n\t// \t\t\ttableNamesMap,\n\t// \t\t\ttable,\n\t// \t\t\ttableConfig,\n\t// \t\t\tqueryConfig: {\n\t// \t\t\t\t...config,\n\t// \t\t\t\twhere: undefined,\n\t// \t\t\t\torderBy: undefined,\n\t// \t\t\t\tlimit: undefined,\n\t// \t\t\t\toffset: undefined,\n\t// \t\t\t\twith: manyRelations.slice(1).reduce<NonNullable<typeof config['with']>>(\n\t// \t\t\t\t\t(result, { tsKey, queryConfig: configValue }) => {\n\t// \t\t\t\t\t\tresult[tsKey] = configValue;\n\t// \t\t\t\t\t\treturn result;\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\t{},\n\t// \t\t\t\t),\n\t// \t\t\t},\n\t// \t\t\ttableAlias,\n\t// \t\t});\n\n\t// \t\tselectedRelations.push({\n\t// \t\t\tdbKey: selectedRelationTsKey,\n\t// \t\t\ttsKey: selectedRelationTsKey,\n\t// \t\t\tfield: builtRelationSelectionField,\n\t// \t\t\trelationTableTsKey: relationTableTsName,\n\t// \t\t\tisJson: true,\n\t// \t\t\tselection: builtRelationJoin.selection,\n\t// \t\t});\n\n\t// \t\t// selection = builtTableFrom.selection.map((item) =>\n\t// \t\t// \tis(item.field, SQL.Aliased)\n\t// \t\t// \t\t? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` }\n\t// \t\t// \t\t: item\n\t// \t\t// );\n\t// \t\t// selectionForBuild = [{\n\t// \t\t// \tdbKey: '*',\n\t// \t\t// \ttsKey: '*',\n\t// \t\t// \tfield: sql`${sql.identifier(tableAlias)}.*`,\n\t// \t\t// \tselection: [],\n\t// \t\t// \tisJson: false,\n\t// \t\t// \trelationTableTsKey: undefined,\n\t// \t\t// }];\n\t// \t\t// const newSelectionItem: (typeof selection)[number] = {\n\t// \t\t// \tdbKey: selectedRelationTsKey,\n\t// \t\t// \ttsKey: selectedRelationTsKey,\n\t// \t\t// \tfield,\n\t// \t\t// \trelationTableTsKey: relationTableTsName,\n\t// \t\t// \tisJson: true,\n\t// \t\t// \tselection: builtRelationJoin.selection,\n\t// \t\t// };\n\t// \t\t// selection.push(newSelectionItem);\n\t// \t\t// selectionForBuild.push(newSelectionItem);\n\n\t// \t\ttableFrom = is(builtTableFrom.sql, GelTable)\n\t// \t\t\t? builtTableFrom.sql\n\t// \t\t\t: new Subquery(builtTableFrom.sql, {}, tableAlias);\n\t// \t}\n\n\t// \tif (selectedColumns.length === 0 && selectedRelations.length === 0 && selectedExtras.length === 0) {\n\t// \t\tthrow new DrizzleError(`No fields selected for table \"${tableConfig.tsName}\" (\"${tableAlias}\")`);\n\t// \t}\n\n\t// \tlet selection: BuildRelationalQueryResult<GelTable, GelColumn>['selection'];\n\n\t// \tfunction prepareSelectedColumns() {\n\t// \t\treturn selectedColumns.map((key) => ({\n\t// \t\t\tdbKey: tableConfig.columns[key]!.name,\n\t// \t\t\ttsKey: key,\n\t// \t\t\tfield: tableConfig.columns[key] as GelColumn,\n\t// \t\t\trelationTableTsKey: undefined,\n\t// \t\t\tisJson: false,\n\t// \t\t\tselection: [],\n\t// \t\t}));\n\t// \t}\n\n\t// \tfunction prepareSelectedExtras() {\n\t// \t\treturn selectedExtras.map((item) => ({\n\t// \t\t\tdbKey: item.value.fieldAlias,\n\t// \t\t\ttsKey: item.tsKey,\n\t// \t\t\tfield: item.value,\n\t// \t\t\trelationTableTsKey: undefined,\n\t// \t\t\tisJson: false,\n\t// \t\t\tselection: [],\n\t// \t\t}));\n\t// \t}\n\n\t// \tif (isRoot) {\n\t// \t\tselection = [\n\t// \t\t\t...prepareSelectedColumns(),\n\t// \t\t\t...prepareSelectedExtras(),\n\t// \t\t];\n\t// \t}\n\n\t// \tif (hasUserDefinedWhere || orderBy.length > 0) {\n\t// \t\ttableFrom = new Subquery(\n\t// \t\t\tthis.buildSelectQuery({\n\t// \t\t\t\ttable: is(tableFrom, GelTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom,\n\t// \t\t\t\tfields: {},\n\t// \t\t\t\tfieldsFlat: selectionForBuild.map(({ field }) => ({\n\t// \t\t\t\t\tpath: [],\n\t// \t\t\t\t\tfield: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,\n\t// \t\t\t\t})),\n\t// \t\t\t\tjoins,\n\t// \t\t\t\tdistinct,\n\t// \t\t\t}),\n\t// \t\t\t{},\n\t// \t\t\ttableAlias,\n\t// \t\t);\n\t// \t\tselectionForBuild = selection.map((item) =>\n\t// \t\t\tis(item.field, SQL.Aliased)\n\t// \t\t\t\t? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` }\n\t// \t\t\t\t: item\n\t// \t\t);\n\t// \t\tjoins = [];\n\t// \t\tdistinct = undefined;\n\t// \t}\n\n\t// \tconst result = this.buildSelectQuery({\n\t// \t\ttable: is(tableFrom, GelTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom,\n\t// \t\tfields: {},\n\t// \t\tfieldsFlat: selectionForBuild.map(({ field }) => ({\n\t// \t\t\tpath: [],\n\t// \t\t\tfield: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,\n\t// \t\t})),\n\t// \t\twhere,\n\t// \t\tlimit,\n\t// \t\toffset,\n\t// \t\tjoins,\n\t// \t\torderBy,\n\t// \t\tdistinct,\n\t// \t});\n\n\t// \treturn {\n\t// \t\ttableTsKey: tableConfig.tsName,\n\t// \t\tsql: result,\n\t// \t\tselection,\n\t// \t};\n\t// }\n\n\tbuildRelationalQueryWithoutPK({\n\t\tfullSchema,\n\t\tschema,\n\t\ttableNamesMap,\n\t\ttable,\n\t\ttableConfig,\n\t\tqueryConfig: config,\n\t\ttableAlias,\n\t\tnestedQueryRelation,\n\t\tjoinOn,\n\t}: {\n\t\tfullSchema: Record<string, unknown>;\n\t\tschema: TablesRelationalConfig;\n\t\ttableNamesMap: Record<string, string>;\n\t\ttable: GelTable;\n\t\ttableConfig: TableRelationalConfig;\n\t\tqueryConfig: true | DBQueryConfig<'many', true>;\n\t\ttableAlias: string;\n\t\tnestedQueryRelation?: Relation;\n\t\tjoinOn?: SQL;\n\t}): BuildRelationalQueryResult<GelTable, GelColumn> {\n\t\tlet selection: BuildRelationalQueryResult<GelTable, GelColumn>['selection'] = [];\n\t\tlet limit, offset, orderBy: NonNullable<GelSelectConfig['orderBy']> = [], where;\n\t\tconst joins: GelSelectJoinConfig[] = [];\n\n\t\tif (config === true) {\n\t\t\tconst selectionEntries = Object.entries(tableConfig.columns);\n\t\t\tselection = selectionEntries.map((\n\t\t\t\t[key, value],\n\t\t\t) => ({\n\t\t\t\tdbKey: value.name,\n\t\t\t\ttsKey: key,\n\t\t\t\tfield: aliasedTableColumn(value as GelColumn, tableAlias),\n\t\t\t\trelationTableTsKey: undefined,\n\t\t\t\tisJson: false,\n\t\t\t\tselection: [],\n\t\t\t}));\n\t\t} else {\n\t\t\tconst aliasedColumns = Object.fromEntries(\n\t\t\t\tObject.entries(tableConfig.columns).map((\n\t\t\t\t\t[key, value],\n\t\t\t\t) => [key, aliasedTableColumn(value, tableAlias)]),\n\t\t\t);\n\n\t\t\tif (config.where) {\n\t\t\t\tconst whereSql = typeof config.where === 'function'\n\t\t\t\t\t? config.where(aliasedColumns, getOperators())\n\t\t\t\t\t: config.where;\n\t\t\t\twhere = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);\n\t\t\t}\n\n\t\t\tconst fieldsSelection: { tsKey: string; value: GelColumn | SQL.Aliased }[] = [];\n\t\t\tlet selectedColumns: string[] = [];\n\n\t\t\t// Figure out which columns to select\n\t\t\tif (config.columns) {\n\t\t\t\tlet isIncludeMode = false;\n\n\t\t\t\tfor (const [field, value] of Object.entries(config.columns)) {\n\t\t\t\t\tif (value === undefined) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (field in tableConfig.columns) {\n\t\t\t\t\t\tif (!isIncludeMode && value === true) {\n\t\t\t\t\t\t\tisIncludeMode = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tselectedColumns.push(field);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (selectedColumns.length > 0) {\n\t\t\t\t\tselectedColumns = isIncludeMode\n\t\t\t\t\t\t? selectedColumns.filter((c) => config.columns?.[c] === true)\n\t\t\t\t\t\t: Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Select all columns if selection is not specified\n\t\t\t\tselectedColumns = Object.keys(tableConfig.columns);\n\t\t\t}\n\n\t\t\tfor (const field of selectedColumns) {\n\t\t\t\tconst column = tableConfig.columns[field]! as GelColumn;\n\t\t\t\tfieldsSelection.push({ tsKey: field, value: column });\n\t\t\t}\n\n\t\t\tlet selectedRelations: {\n\t\t\t\ttsKey: string;\n\t\t\t\tqueryConfig: true | DBQueryConfig<'many', false>;\n\t\t\t\trelation: Relation;\n\t\t\t}[] = [];\n\n\t\t\t// Figure out which relations to select\n\t\t\tif (config.with) {\n\t\t\t\tselectedRelations = Object.entries(config.with)\n\t\t\t\t\t.filter((entry): entry is [typeof entry[0], NonNullable<typeof entry[1]>] => !!entry[1])\n\t\t\t\t\t.map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey]! }));\n\t\t\t}\n\n\t\t\tlet extras;\n\n\t\t\t// Figure out which extras to select\n\t\t\tif (config.extras) {\n\t\t\t\textras = typeof config.extras === 'function'\n\t\t\t\t\t? config.extras(aliasedColumns, { sql })\n\t\t\t\t\t: config.extras;\n\t\t\t\tfor (const [tsKey, value] of Object.entries(extras)) {\n\t\t\t\t\tfieldsSelection.push({\n\t\t\t\t\t\ttsKey,\n\t\t\t\t\t\tvalue: mapColumnsInAliasedSQLToAlias(value, tableAlias),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Transform `fieldsSelection` into `selection`\n\t\t\t// `fieldsSelection` shouldn't be used after this point\n\t\t\tfor (const { tsKey, value } of fieldsSelection) {\n\t\t\t\tselection.push({\n\t\t\t\t\tdbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey]!.name,\n\t\t\t\t\ttsKey,\n\t\t\t\t\tfield: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,\n\t\t\t\t\trelationTableTsKey: undefined,\n\t\t\t\t\tisJson: false,\n\t\t\t\t\tselection: [],\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tlet orderByOrig = typeof config.orderBy === 'function'\n\t\t\t\t? config.orderBy(aliasedColumns, getOrderByOperators())\n\t\t\t\t: config.orderBy ?? [];\n\t\t\tif (!Array.isArray(orderByOrig)) {\n\t\t\t\torderByOrig = [orderByOrig];\n\t\t\t}\n\t\t\torderBy = orderByOrig.map((orderByValue) => {\n\t\t\t\tif (is(orderByValue, Column)) {\n\t\t\t\t\treturn aliasedTableColumn(orderByValue, tableAlias) as GelColumn;\n\t\t\t\t}\n\t\t\t\treturn mapColumnsInSQLToAlias(orderByValue, tableAlias);\n\t\t\t});\n\n\t\t\tlimit = config.limit;\n\t\t\toffset = config.offset;\n\n\t\t\t// Process all relations\n\t\t\tfor (\n\t\t\t\tconst {\n\t\t\t\t\ttsKey: selectedRelationTsKey,\n\t\t\t\t\tqueryConfig: selectedRelationConfigValue,\n\t\t\t\t\trelation,\n\t\t\t\t} of selectedRelations\n\t\t\t) {\n\t\t\t\tconst normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);\n\t\t\t\tconst relationTableName = getTableUniqueName(relation.referencedTable);\n\t\t\t\tconst relationTableTsName = tableNamesMap[relationTableName]!;\n\t\t\t\tconst relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;\n\t\t\t\tconst joinOn = and(\n\t\t\t\t\t...normalizedRelation.fields.map((field, i) =>\n\t\t\t\t\t\teq(\n\t\t\t\t\t\t\taliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),\n\t\t\t\t\t\t\taliasedTableColumn(field, tableAlias),\n\t\t\t\t\t\t)\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tconst builtRelation = this.buildRelationalQueryWithoutPK({\n\t\t\t\t\tfullSchema,\n\t\t\t\t\tschema,\n\t\t\t\t\ttableNamesMap,\n\t\t\t\t\ttable: fullSchema[relationTableTsName] as GelTable,\n\t\t\t\t\ttableConfig: schema[relationTableTsName]!,\n\t\t\t\t\tqueryConfig: is(relation, One)\n\t\t\t\t\t\t? (selectedRelationConfigValue === true\n\t\t\t\t\t\t\t? { limit: 1 }\n\t\t\t\t\t\t\t: { ...selectedRelationConfigValue, limit: 1 })\n\t\t\t\t\t\t: selectedRelationConfigValue,\n\t\t\t\t\ttableAlias: relationTableAlias,\n\t\t\t\t\tjoinOn,\n\t\t\t\t\tnestedQueryRelation: relation,\n\t\t\t\t});\n\t\t\t\tconst field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier('data')}`.as(selectedRelationTsKey);\n\t\t\t\tjoins.push({\n\t\t\t\t\ton: sql`true`,\n\t\t\t\t\ttable: new Subquery(builtRelation.sql as SQL, {}, relationTableAlias),\n\t\t\t\t\talias: relationTableAlias,\n\t\t\t\t\tjoinType: 'left',\n\t\t\t\t\tlateral: true,\n\t\t\t\t});\n\t\t\t\tselection.push({\n\t\t\t\t\tdbKey: selectedRelationTsKey,\n\t\t\t\t\ttsKey: selectedRelationTsKey,\n\t\t\t\t\tfield,\n\t\t\t\t\trelationTableTsKey: relationTableTsName,\n\t\t\t\t\tisJson: true,\n\t\t\t\t\tselection: builtRelation.selection,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tif (selection.length === 0) {\n\t\t\tthrow new DrizzleError({ message: `No fields selected for table \"${tableConfig.tsName}\" (\"${tableAlias}\")` });\n\t\t}\n\n\t\tlet result;\n\n\t\twhere = and(joinOn, where);\n\n\t\tif (nestedQueryRelation) {\n\t\t\tlet field = sql`json_build_array(${\n\t\t\t\tsql.join(\n\t\t\t\t\tselection.map(({ field, tsKey, isJson }) =>\n\t\t\t\t\t\tisJson\n\t\t\t\t\t\t\t? sql`${sql.identifier(`${tableAlias}_${tsKey}`)}.${sql.identifier('data')}`\n\t\t\t\t\t\t\t: is(field, SQL.Aliased)\n\t\t\t\t\t\t\t? field.sql\n\t\t\t\t\t\t\t: field\n\t\t\t\t\t),\n\t\t\t\t\tsql`, `,\n\t\t\t\t)\n\t\t\t})`;\n\t\t\tif (is(nestedQueryRelation, Many)) {\n\t\t\t\tfield = sql`coalesce(json_agg(${field}${\n\t\t\t\t\torderBy.length > 0 ? sql` order by ${sql.join(orderBy, sql`, `)}` : undefined\n\t\t\t\t}), '[]'::json)`;\n\t\t\t\t// orderBy = [];\n\t\t\t}\n\t\t\tconst nestedSelection = [{\n\t\t\t\tdbKey: 'data',\n\t\t\t\ttsKey: 'data',\n\t\t\t\tfield: field.as('data'),\n\t\t\t\tisJson: true,\n\t\t\t\trelationTableTsKey: tableConfig.tsName,\n\t\t\t\tselection,\n\t\t\t}];\n\n\t\t\tconst needsSubquery = limit !== undefined || offset !== undefined || orderBy.length > 0;\n\n\t\t\tif (needsSubquery) {\n\t\t\t\tresult = this.buildSelectQuery({\n\t\t\t\t\ttable: aliasedTable(table, tableAlias),\n\t\t\t\t\tfields: {},\n\t\t\t\t\tfieldsFlat: [{\n\t\t\t\t\t\tpath: [],\n\t\t\t\t\t\tfield: sql.raw('*'),\n\t\t\t\t\t}],\n\t\t\t\t\twhere,\n\t\t\t\t\tlimit,\n\t\t\t\t\toffset,\n\t\t\t\t\torderBy,\n\t\t\t\t\tsetOperators: [],\n\t\t\t\t});\n\n\t\t\t\twhere = undefined;\n\t\t\t\tlimit = undefined;\n\t\t\t\toffset = undefined;\n\t\t\t\torderBy = [];\n\t\t\t} else {\n\t\t\t\tresult = aliasedTable(table, tableAlias);\n\t\t\t}\n\n\t\t\tresult = this.buildSelectQuery({\n\t\t\t\ttable: is(result, GelTable) ? result : new Subquery(result, {