import { getTableName } from "drizzle-orm";
import { escapeName } from "../dialect.js";
/** @internal */
const ColumnsSymbol = Symbol.for("drizzle:Columns");
// ---------------------------------------------------------------------------
// Builder
// ---------------------------------------------------------------------------
export class SybaseUpdateBuilder {
    table;
    dialect;
    session;
    setValues = {};
    whereCondition;
    constructor(table, dialect, session) {
        this.table = table;
        this.dialect = dialect;
        this.session = session;
    }
    set(values) {
        this.setValues = values;
        return this;
    }
    where(condition) {
        this.whereCondition = this.dialect.sqlToQuery(condition);
        return this;
    }
    toSQL() {
        return this.buildSql();
    }
    async execute() {
        const rawSql = this.buildSql();
        const result = await this.session.execute(rawSql);
        return { rowCount: result.rowCount, affectedRows: result.affectedRows };
    }
    then(onfulfilled, onrejected) {
        return this.execute().then(onfulfilled, onrejected);
    }
    // ---------------------------------------------------------------------------
    // Private
    // ---------------------------------------------------------------------------
    buildSql() {
        const columns = this.table[ColumnsSymbol];
        const tableName = escapeName(getTableName(this.table));
        const setClauses = [];
        for (const [fieldName, value] of Object.entries(this.setValues)) {
            if (value === undefined) {
                continue;
            }
            const col = columns[fieldName];
            if (!col) {
                continue;
            }
            setClauses.push(`${escapeName(col.name)} = ${this.dialect.serializeColumnValue(value, col)}`);
        }
        // Apply onUpdate functions for columns not explicitly set
        for (const [fieldName, col] of Object.entries(columns)) {
            if (col.onUpdateFn && this.setValues[fieldName] === undefined) {
                const onUpdateResult = col.onUpdateFn();
                setClauses.push(`${escapeName(col.name)} = ${this.dialect.serializeColumnValue(onUpdateResult, col)}`);
            }
        }
        if (setClauses.length === 0) {
            throw new Error("No columns to update");
        }
        let query = `update ${tableName} set ${setClauses.join(", ")}`;
        if (this.whereCondition) {
            query += ` where ${this.whereCondition}`;
        }
        return query;
    }
}
//# sourceMappingURL=update.js.map