import { RDSDataService } from "aws-sdk"; import { LeQuerybuilderAuroraMysqlDataApiError, LeQuerybuilderAuroraMysqlDataApiErrorEnum, QueryBuilderBaseParamEnum } from ".."; import { classLikeFormation } from "../utils"; import { getParameterField } from "./aurora-data-api-query-builder-common"; import { formatJoinableTables, JoinableTable } from "./join-query"; import { formatOrder, resetOrder } from "./order-query"; import { resetPagination } from "./pagination-query"; import { formatSelect, QBSelectedField, QBSelectField, resetSelect, select } from "./select-query"; import { formatWhere, WhereQuery } from "./where-query"; export interface QBSelectBuilder { tables: JoinableTable[]; wheres: WhereQuery[]; selects: QBSelectField[]; orders: string[]; offset: number; limit: number; } export function sbFormation any; }>(obj: T, classConf: QBSelectBuilder) { return classLikeFormation(obj, classConf); } export function sbNew(): QBSelectBuilder { return { tables: [], wheres: [], selects: [], orders: [], offset: 0, limit: 0, }; } export function sbCountAndFormat(confobj: QBSelectBuilder, field: QBSelectField) { const cloneConf: QBSelectBuilder = JSON.parse(JSON.stringify(confobj)); resetOrder(cloneConf); resetPagination(cloneConf); resetSelect(cloneConf); select(cloneConf, field); return sbFormat(cloneConf); } export function sbFormat(confobj: QBSelectBuilder): { parameters: RDSDataService.SqlParameter[]; selectedFields: QBSelectedField[], sql: string; } { if (confobj.tables.length === 0) { throw new LeQuerybuilderAuroraMysqlDataApiError(LeQuerybuilderAuroraMysqlDataApiErrorEnum.FormatError); } if (confobj.selects.length === 0) { throw new LeQuerybuilderAuroraMysqlDataApiError(LeQuerybuilderAuroraMysqlDataApiErrorEnum.FormatError); } const parameters: RDSDataService.SqlParameter[] = []; let paramCounter = 0; const selectFormatPart = formatSelect(confobj); const tableFormatPart = formatJoinableTables(confobj); let tableStr = tableFormatPart.str; for (const param of tableFormatPart.params) { const paramName = `p${paramCounter++}`; const val = getParameterField(param.type, param.val); tableStr = tableStr.replace(":?", ":" + paramName); parameters.push({ name: paramName, value: val, }); } const whereFormatPart = formatWhere(confobj); let whereStr = whereFormatPart.str; for (const param of whereFormatPart.params) { const paramName = `p${paramCounter++}`; const val = getParameterField(param.type, param.val); whereStr = whereStr.replace(":?", ":" + paramName); parameters.push({ name: paramName, value: val, }); } const finalSql = [`SELECT ${selectFormatPart.str} FROM ${tableStr}`]; if (whereStr) { finalSql.push(`WHERE ${whereStr}`); } if (confobj.orders.length > 0) { finalSql.push(`ORDER BY ${formatOrder(confobj).str}`); } if (confobj.limit) { finalSql.push(`LIMIT ${confobj.limit}`); if (confobj.offset) { finalSql.push(`OFFSET ${confobj.offset}`); } } return { parameters, selectedFields: selectFormatPart.selectedFields, sql: finalSql.join(" ") + ";", }; }