import { compile, extractZqlResult } from "../../z2s/src/compiler.js";
import { formatPgInternalConvert } from "../../z2s/src/sql.js";
import { defaultFormat } from "../../zql/src/ivm/default-format.js";
import { AbstractQuery, newQuerySymbol } from "../../zql/src/query/query-impl.js";
export function makeSchemaQuery(schema) {
    class SchemaQueryHandler {
        #dbTransaction;
        #serverSchema;
        constructor(dbTransaction, serverSchema) {
            this.#dbTransaction = dbTransaction;
            this.#serverSchema = serverSchema;
        }
        get(target, prop) {
            if (prop in target) {
                return target[prop];
            }
            if (!(prop in schema.tables)) {
                throw new Error(`Table ${prop} does not exist in schema`);
            }
            const q = new ZPGQuery(schema, this.#serverSchema, prop, this.#dbTransaction, { table: prop }, defaultFormat);
            target[prop] = q;
            return q;
        }
    }
    return (dbTransaction, serverSchema) => new Proxy({}, new SchemaQueryHandler(dbTransaction, serverSchema));
}
export class ZPGQuery extends AbstractQuery {
    #dbTransaction;
    #schema;
    #serverSchema;
    #query;
    constructor(schema, serverSchema, tableName, dbTransaction, ast, format) {
        super(undefined, schema, tableName, ast, format, 'permissions', undefined);
        this.#dbTransaction = dbTransaction;
        this.#schema = schema;
        this.#serverSchema = serverSchema;
    }
    [newQuerySymbol](_delegate, schema, tableName, ast, format) {
        return new ZPGQuery(schema, this.#serverSchema, tableName, this.#dbTransaction, ast, format);
    }
    async run() {
        const sqlQuery = this.#query ??
            formatPgInternalConvert(compile(this.#serverSchema, this.#schema, this._completeAst(), this.format));
        this.#query = sqlQuery;
        const pgIterableResult = await this.#dbTransaction.query(sqlQuery.text, sqlQuery.values);
        const pgArrayResult = Array.isArray(pgIterableResult)
            ? pgIterableResult
            : [...pgIterableResult];
        if (pgArrayResult.length === 0 && this.format.singular) {
            return undefined;
        }
        return extractZqlResult(pgArrayResult);
    }
    preload() {
        throw new Error('Z2SQuery cannot be preloaded');
    }
    materialize() {
        throw new Error('Z2SQuery cannot be materialized');
    }
}
//# sourceMappingURL=query.js.map