import { Col } from "./Column"; import { compileUpdate, finalCols } from "./Compile"; import { runCustomQuery } from "./CustomQuery"; import { litToPgParam, tagSql } from "./Frontend"; import { pg } from "./pg"; import { MakeCols, MakeTable, toTup, Write } from "./Query"; import { Table } from "./Table"; import { ColName } from "./Types"; /** * Update rows of a table, with a RETURNING clause * * @param sqlTag Will be injected as a comment into the SQL that is sent to the server. Useful for identifying the query during log analysis and performance analysis * @param pred Which rows should be updated (the WHERE clause) * @param upd A function that returns the new values for a row. * * You may use [[defaultValue]] on "default-able" columns. * * Should have an explicit annotation of the return type, in order to catch excess properties. * See: */ export async function updateReturning(sqlTag: string | undefined, conn: pg.Client, table: Table, pred: (c: MakeCols) => Col, upd: (c: MakeCols) => MakeTable, returning: (c: MakeCols) => MakeCols): Promise { // TODO Make return value of `upd` param a Partial<...> for slightly better ergonomics const [sqlText, params] = compileUpdate(table, pred, upd, returning); const pgParams = params.map(x => litToPgParam(x.param)); const names = table.tableCols.map<[ColName, string, (val: string) => any]>(x => [x.name, x.propName, x.parser]); const cs = toTup(names, null); // tslint:disable-line:no-unnecessary-type-assertion const rs = finalCols(returning(cs)); const rows = await runCustomQuery(conn, rs.map((r: any) => r.propName), rs.map((r: any) => r.parser), tagSql(sqlTag, sqlText), pgParams); return rows; } /** * Update rows of a table * * @param sqlTag Will be injected as a comment into the SQL that is sent to the server. Useful for identifying the query during log analysis and performance analysis * @param pred Which rows should be updated (the WHERE clause) * @param upd A function that returns the new values for a row. * * You may use [[defaultValue]] on "default-able" columns. * * Should have an explicit annotation of the return type, in order to catch excess properties. * See: * @return number of rows updated */ export async function update(sqlTag: string | undefined, conn: pg.Client, table: Table, pred: (c: MakeCols) => Col, upd: (c: MakeCols) => MakeTable): Promise { // TODO Make return value of `upd` param a Partial<...> for slightly better ergonomics const [sqlText, params] = compileUpdate(table, pred, upd, undefined); const pgParams = params.map(x => litToPgParam(x.param)); const result = await pg.query(conn, tagSql(sqlTag, sqlText), pgParams); return result.rowCount; }