@openguardrails/moltguard
Version:
AI agent security plugin for OpenClaw: prompt injection detection, PII sanitization, and monitoring dashboard
1,150 lines (1,099 loc) • 129 kB
JavaScript
export const id = 25;
export const ids = [25];
export const modules = {
/***/ 8575:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Hs: () => (/* binding */ mapColumnsInAliasedSQLToAlias),
/* harmony export */ Ht: () => (/* binding */ ColumnAliasProxyHandler),
/* harmony export */ h_: () => (/* binding */ TableAliasProxyHandler),
/* harmony export */ oG: () => (/* binding */ aliasedTable),
/* harmony export */ ug: () => (/* binding */ aliasedTableColumn),
/* harmony export */ yY: () => (/* binding */ mapColumnsInSQLToAlias)
/* harmony export */ });
/* unused harmony exports RelationTableAliasProxyHandler, aliasedRelation */
/* harmony import */ var _column_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2345);
/* harmony import */ var _entity_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9724);
/* harmony import */ var _sql_sql_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(183);
/* harmony import */ var _table_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8407);
/* harmony import */ var _view_common_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6146);
class ColumnAliasProxyHandler {
constructor(table) {
this.table = table;
}
static [_entity_js__WEBPACK_IMPORTED_MODULE_0__/* .entityKind */ .i] = "ColumnAliasProxyHandler";
get(columnObj, prop) {
if (prop === "table") {
return this.table;
}
return columnObj[prop];
}
}
class TableAliasProxyHandler {
constructor(alias, replaceOriginalName) {
this.alias = alias;
this.replaceOriginalName = replaceOriginalName;
}
static [_entity_js__WEBPACK_IMPORTED_MODULE_0__/* .entityKind */ .i] = "TableAliasProxyHandler";
get(target, prop) {
if (prop === _table_js__WEBPACK_IMPORTED_MODULE_1__/* .Table */ .XI.Symbol.IsAlias) {
return true;
}
if (prop === _table_js__WEBPACK_IMPORTED_MODULE_1__/* .Table */ .XI.Symbol.Name) {
return this.alias;
}
if (this.replaceOriginalName && prop === _table_js__WEBPACK_IMPORTED_MODULE_1__/* .Table */ .XI.Symbol.OriginalName) {
return this.alias;
}
if (prop === _view_common_js__WEBPACK_IMPORTED_MODULE_2__/* .ViewBaseConfig */ .n) {
return {
...target[_view_common_js__WEBPACK_IMPORTED_MODULE_2__/* .ViewBaseConfig */ .n],
name: this.alias,
isAlias: true
};
}
if (prop === _table_js__WEBPACK_IMPORTED_MODULE_1__/* .Table */ .XI.Symbol.Columns) {
const columns = target[_table_js__WEBPACK_IMPORTED_MODULE_1__/* .Table */ .XI.Symbol.Columns];
if (!columns) {
return columns;
}
const proxiedColumns = {};
Object.keys(columns).map((key) => {
proxiedColumns[key] = new Proxy(
columns[key],
new ColumnAliasProxyHandler(new Proxy(target, this))
);
});
return proxiedColumns;
}
const value = target[prop];
if ((0,_entity_js__WEBPACK_IMPORTED_MODULE_0__.is)(value, _column_js__WEBPACK_IMPORTED_MODULE_3__/* .Column */ .V)) {
return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(target, this)));
}
return value;
}
}
class RelationTableAliasProxyHandler {
constructor(alias) {
this.alias = alias;
}
static [_entity_js__WEBPACK_IMPORTED_MODULE_0__/* .entityKind */ .i] = (/* unused pure expression or super */ null && ("RelationTableAliasProxyHandler"));
get(target, prop) {
if (prop === "sourceTable") {
return aliasedTable(target.sourceTable, this.alias);
}
return target[prop];
}
}
function aliasedTable(table, tableAlias) {
return new Proxy(table, new TableAliasProxyHandler(tableAlias, false));
}
function aliasedRelation(relation, tableAlias) {
return new Proxy(relation, new RelationTableAliasProxyHandler(tableAlias));
}
function aliasedTableColumn(column, tableAlias) {
return new Proxy(
column,
new ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false)))
);
}
function mapColumnsInAliasedSQLToAlias(query, alias) {
return new _sql_sql_js__WEBPACK_IMPORTED_MODULE_4__/* .SQL */ .Xs.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias);
}
function mapColumnsInSQLToAlias(query, alias) {
return _sql_sql_js__WEBPACK_IMPORTED_MODULE_4__/* .sql */ .ll.join(query.queryChunks.map((c) => {
if ((0,_entity_js__WEBPACK_IMPORTED_MODULE_0__.is)(c, _column_js__WEBPACK_IMPORTED_MODULE_3__/* .Column */ .V)) {
return aliasedTableColumn(c, alias);
}
if ((0,_entity_js__WEBPACK_IMPORTED_MODULE_0__.is)(c, _sql_sql_js__WEBPACK_IMPORTED_MODULE_4__/* .SQL */ .Xs)) {
return mapColumnsInSQLToAlias(c, alias);
}
if ((0,_entity_js__WEBPACK_IMPORTED_MODULE_0__.is)(c, _sql_sql_js__WEBPACK_IMPORTED_MODULE_4__/* .SQL */ .Xs.Aliased)) {
return mapColumnsInAliasedSQLToAlias(c, alias);
}
return c;
}));
}
//# sourceMappingURL=alias.js.map
/***/ }),
/***/ 568:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Yn: () => (/* binding */ CasingCache)
/* harmony export */ });
/* unused harmony exports toCamelCase, toSnakeCase */
/* harmony import */ var _entity_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9724);
/* harmony import */ var _table_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8407);
function toSnakeCase(input) {
const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
return words.map((word) => word.toLowerCase()).join("_");
}
function toCamelCase(input) {
const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
return words.reduce((acc, word, i) => {
const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`;
return acc + formattedWord;
}, "");
}
function noopCase(input) {
return input;
}
class CasingCache {
static [_entity_js__WEBPACK_IMPORTED_MODULE_0__/* .entityKind */ .i] = "CasingCache";
/** @internal */
cache = {};
cachedTables = {};
convert;
constructor(casing) {
this.convert = casing === "snake_case" ? toSnakeCase : casing === "camelCase" ? toCamelCase : noopCase;
}
getColumnCasing(column) {
if (!column.keyAsName)
return column.name;
const schema = column.table[_table_js__WEBPACK_IMPORTED_MODULE_1__/* .Table */ .XI.Symbol.Schema] ?? "public";
const tableName = column.table[_table_js__WEBPACK_IMPORTED_MODULE_1__/* .Table */ .XI.Symbol.OriginalName];
const key = `${schema}.${tableName}.${column.name}`;
if (!this.cache[key]) {
this.cacheTable(column.table);
}
return this.cache[key];
}
cacheTable(table) {
const schema = table[_table_js__WEBPACK_IMPORTED_MODULE_1__/* .Table */ .XI.Symbol.Schema] ?? "public";
const tableName = table[_table_js__WEBPACK_IMPORTED_MODULE_1__/* .Table */ .XI.Symbol.OriginalName];
const tableKey = `${schema}.${tableName}`;
if (!this.cachedTables[tableKey]) {
for (const column of Object.values(table[_table_js__WEBPACK_IMPORTED_MODULE_1__/* .Table */ .XI.Symbol.Columns])) {
const columnKey = `${tableKey}.${column.name}`;
this.cache[columnKey] = this.convert(column.name);
}
this.cachedTables[tableKey] = true;
}
}
clearCache() {
this.cache = {};
this.cachedTables = {};
}
}
//# sourceMappingURL=casing.js.map
/***/ }),
/***/ 6920:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ j: () => (/* binding */ TransactionRollbackError),
/* harmony export */ n: () => (/* binding */ DrizzleError)
/* harmony export */ });
/* harmony import */ var _entity_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9724);
class DrizzleError extends Error {
static [_entity_js__WEBPACK_IMPORTED_MODULE_0__/* .entityKind */ .i] = "DrizzleError";
constructor({ message, cause }) {
super(message);
this.name = "DrizzleError";
this.cause = cause;
}
}
class TransactionRollbackError extends DrizzleError {
static [_entity_js__WEBPACK_IMPORTED_MODULE_0__/* .entityKind */ .i] = "TransactionRollbackError";
constructor() {
super({ message: "Rollback" });
}
}
//# sourceMappingURL=errors.js.map
/***/ }),
/***/ 6743:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Pv: () => (/* binding */ NoopLogger),
/* harmony export */ w: () => (/* binding */ DefaultLogger)
/* harmony export */ });
/* unused harmony export ConsoleLogWriter */
/* harmony import */ var _entity_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9724);
class ConsoleLogWriter {
static [_entity_js__WEBPACK_IMPORTED_MODULE_0__/* .entityKind */ .i] = "ConsoleLogWriter";
write(message) {
console.log(message);
}
}
class DefaultLogger {
static [_entity_js__WEBPACK_IMPORTED_MODULE_0__/* .entityKind */ .i] = "DefaultLogger";
writer;
constructor(config) {
this.writer = config?.writer ?? new ConsoleLogWriter();
}
logQuery(query, params) {
const stringifiedParams = params.map((p) => {
try {
return JSON.stringify(p);
} catch {
return String(p);
}
});
const paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(", ")}]` : "";
this.writer.write(`Query: ${query}${paramsStr}`);
}
}
class NoopLogger {
static [_entity_js__WEBPACK_IMPORTED_MODULE_0__/* .entityKind */ .i] = "NoopLogger";
logQuery() {
}
}
//# sourceMappingURL=logger.js.map
/***/ }),
/***/ 3025:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
drizzle: () => (/* reexport */ drizzle)
});
// UNUSED EXPORTS: MySql2Database, MySql2Driver, MySql2PreparedQuery, MySql2Session, MySql2Transaction, MySqlDatabase
// EXTERNAL MODULE: external "mysql2"
var external_mysql2_ = __webpack_require__(2530);
// EXTERNAL MODULE: ../../node_modules/.pnpm/drizzle-orm@0.36.4_@libsql+client@0.14.0_@types+better-sqlite3@7.6.13_@types+react@18.3.28_be_bhyfo6jtf7gmzt2fsdpal3g2vq/node_modules/drizzle-orm/entity.js
var entity = __webpack_require__(9724);
// EXTERNAL MODULE: ../../node_modules/.pnpm/drizzle-orm@0.36.4_@libsql+client@0.14.0_@types+better-sqlite3@7.6.13_@types+react@18.3.28_be_bhyfo6jtf7gmzt2fsdpal3g2vq/node_modules/drizzle-orm/logger.js
var drizzle_orm_logger = __webpack_require__(6743);
// EXTERNAL MODULE: ../../node_modules/.pnpm/drizzle-orm@0.36.4_@libsql+client@0.14.0_@types+better-sqlite3@7.6.13_@types+react@18.3.28_be_bhyfo6jtf7gmzt2fsdpal3g2vq/node_modules/drizzle-orm/selection-proxy.js
var selection_proxy = __webpack_require__(8296);
// EXTERNAL MODULE: ../../node_modules/.pnpm/drizzle-orm@0.36.4_@libsql+client@0.14.0_@types+better-sqlite3@7.6.13_@types+react@18.3.28_be_bhyfo6jtf7gmzt2fsdpal3g2vq/node_modules/drizzle-orm/sql/sql.js + 1 modules
var sql = __webpack_require__(183);
// EXTERNAL MODULE: ../../node_modules/.pnpm/drizzle-orm@0.36.4_@libsql+client@0.14.0_@types+better-sqlite3@7.6.13_@types+react@18.3.28_be_bhyfo6jtf7gmzt2fsdpal3g2vq/node_modules/drizzle-orm/subquery.js
var subquery = __webpack_require__(6453);
;// CONCATENATED MODULE: ../../node_modules/.pnpm/drizzle-orm@0.36.4_@libsql+client@0.14.0_@types+better-sqlite3@7.6.13_@types+react@18.3.28_be_bhyfo6jtf7gmzt2fsdpal3g2vq/node_modules/drizzle-orm/mysql-core/query-builders/count.js
class MySqlCountBuilder extends sql/* SQL */.Xs {
constructor(params) {
super(MySqlCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
this.params = params;
this.mapWith(Number);
this.session = params.session;
this.sql = MySqlCountBuilder.buildCount(
params.source,
params.filters
);
}
sql;
static [entity/* entityKind */.i] = "MySqlCountBuilder";
[Symbol.toStringTag] = "MySqlCountBuilder";
session;
static buildEmbeddedCount(source, filters) {
return (0,sql/* sql */.ll)`(select count(*) from ${source}${sql/* sql */.ll.raw(" where ").if(filters)}${filters})`;
}
static buildCount(source, filters) {
return (0,sql/* sql */.ll)`select count(*) as count from ${source}${sql/* sql */.ll.raw(" where ").if(filters)}${filters}`;
}
then(onfulfilled, onrejected) {
return Promise.resolve(this.session.count(this.sql)).then(
onfulfilled,
onrejected
);
}
catch(onRejected) {
return this.then(void 0, onRejected);
}
finally(onFinally) {
return this.then(
(value) => {
onFinally?.();
return value;
},
(reason) => {
onFinally?.();
throw reason;
}
);
}
}
//# sourceMappingURL=count.js.map
// EXTERNAL MODULE: ../../node_modules/.pnpm/drizzle-orm@0.36.4_@libsql+client@0.14.0_@types+better-sqlite3@7.6.13_@types+react@18.3.28_be_bhyfo6jtf7gmzt2fsdpal3g2vq/node_modules/drizzle-orm/alias.js
var alias = __webpack_require__(8575);
// EXTERNAL MODULE: ../../node_modules/.pnpm/drizzle-orm@0.36.4_@libsql+client@0.14.0_@types+better-sqlite3@7.6.13_@types+react@18.3.28_be_bhyfo6jtf7gmzt2fsdpal3g2vq/node_modules/drizzle-orm/casing.js
var casing = __webpack_require__(568);
// EXTERNAL MODULE: ../../node_modules/.pnpm/drizzle-orm@0.36.4_@libsql+client@0.14.0_@types+better-sqlite3@7.6.13_@types+react@18.3.28_be_bhyfo6jtf7gmzt2fsdpal3g2vq/node_modules/drizzle-orm/column.js
var drizzle_orm_column = __webpack_require__(2345);
// EXTERNAL MODULE: ../../node_modules/.pnpm/drizzle-orm@0.36.4_@libsql+client@0.14.0_@types+better-sqlite3@7.6.13_@types+react@18.3.28_be_bhyfo6jtf7gmzt2fsdpal3g2vq/node_modules/drizzle-orm/errors.js
var errors = __webpack_require__(6920);
// EXTERNAL MODULE: ../../node_modules/.pnpm/drizzle-orm@0.36.4_@libsql+client@0.14.0_@types+better-sqlite3@7.6.13_@types+react@18.3.28_be_bhyfo6jtf7gmzt2fsdpal3g2vq/node_modules/drizzle-orm/sql/expressions/conditions.js
var conditions = __webpack_require__(420);
// EXTERNAL MODULE: ../../node_modules/.pnpm/drizzle-orm@0.36.4_@libsql+client@0.14.0_@types+better-sqlite3@7.6.13_@types+react@18.3.28_be_bhyfo6jtf7gmzt2fsdpal3g2vq/node_modules/drizzle-orm/relations.js + 1 modules
var relations = __webpack_require__(4750);
// EXTERNAL MODULE: ../../node_modules/.pnpm/drizzle-orm@0.36.4_@libsql+client@0.14.0_@types+better-sqlite3@7.6.13_@types+react@18.3.28_be_bhyfo6jtf7gmzt2fsdpal3g2vq/node_modules/drizzle-orm/table.js
var drizzle_orm_table = __webpack_require__(8407);
// EXTERNAL MODULE: ../../node_modules/.pnpm/drizzle-orm@0.36.4_@libsql+client@0.14.0_@types+better-sqlite3@7.6.13_@types+react@18.3.28_be_bhyfo6jtf7gmzt2fsdpal3g2vq/node_modules/drizzle-orm/utils.js
var utils = __webpack_require__(3853);
// EXTERNAL MODULE: ../../node_modules/.pnpm/drizzle-orm@0.36.4_@libsql+client@0.14.0_@types+better-sqlite3@7.6.13_@types+react@18.3.28_be_bhyfo6jtf7gmzt2fsdpal3g2vq/node_modules/drizzle-orm/view-common.js
var view_common = __webpack_require__(6146);
// EXTERNAL MODULE: ../../node_modules/.pnpm/drizzle-orm@0.36.4_@libsql+client@0.14.0_@types+better-sqlite3@7.6.13_@types+react@18.3.28_be_bhyfo6jtf7gmzt2fsdpal3g2vq/node_modules/drizzle-orm/mysql-core/columns/common.js + 2 modules
var common = __webpack_require__(9498);
// EXTERNAL MODULE: ../../node_modules/.pnpm/drizzle-orm@0.36.4_@libsql+client@0.14.0_@types+better-sqlite3@7.6.13_@types+react@18.3.28_be_bhyfo6jtf7gmzt2fsdpal3g2vq/node_modules/drizzle-orm/mysql-core/table.js + 19 modules
var mysql_core_table = __webpack_require__(2104);
;// CONCATENATED MODULE: ../../node_modules/.pnpm/drizzle-orm@0.36.4_@libsql+client@0.14.0_@types+better-sqlite3@7.6.13_@types+react@18.3.28_be_bhyfo6jtf7gmzt2fsdpal3g2vq/node_modules/drizzle-orm/mysql-core/view-base.js
class MySqlViewBase extends sql/* View */.Ss {
static [entity/* entityKind */.i] = "MySqlViewBase";
}
//# sourceMappingURL=view-base.js.map
;// CONCATENATED MODULE: ../../node_modules/.pnpm/drizzle-orm@0.36.4_@libsql+client@0.14.0_@types+better-sqlite3@7.6.13_@types+react@18.3.28_be_bhyfo6jtf7gmzt2fsdpal3g2vq/node_modules/drizzle-orm/mysql-core/dialect.js
class MySqlDialect {
static [entity/* entityKind */.i] = "MySqlDialect";
/** @internal */
casing;
constructor(config) {
this.casing = new casing/* CasingCache */.Yn(config?.casing);
}
async migrate(migrations, session, config) {
const migrationsTable = config.migrationsTable ?? "__drizzle_migrations";
const migrationTableCreate = (0,sql/* sql */.ll)`
create table if not exists ${sql/* sql */.ll.identifier(migrationsTable)} (
id serial primary key,
hash text not null,
created_at bigint
)
`;
await session.execute(migrationTableCreate);
const dbMigrations = await session.all(
(0,sql/* sql */.ll)`select id, hash, created_at from ${sql/* sql */.ll.identifier(migrationsTable)} order by created_at desc limit 1`
);
const lastDbMigration = dbMigrations[0];
await session.transaction(async (tx) => {
for (const migration of migrations) {
if (!lastDbMigration || Number(lastDbMigration.created_at) < migration.folderMillis) {
for (const stmt of migration.sql) {
await tx.execute(sql/* sql */.ll.raw(stmt));
}
await tx.execute(
(0,sql/* sql */.ll)`insert into ${sql/* sql */.ll.identifier(migrationsTable)} (\`hash\`, \`created_at\`) values(${migration.hash}, ${migration.folderMillis})`
);
}
}
});
}
escapeName(name) {
return `\`${name}\``;
}
escapeParam(_num) {
return `?`;
}
escapeString(str) {
return `'${str.replace(/'/g, "''")}'`;
}
buildWithCTE(queries) {
if (!queries?.length)
return void 0;
const withSqlChunks = [(0,sql/* sql */.ll)`with `];
for (const [i, w] of queries.entries()) {
withSqlChunks.push((0,sql/* sql */.ll)`${sql/* sql */.ll.identifier(w._.alias)} as (${w._.sql})`);
if (i < queries.length - 1) {
withSqlChunks.push((0,sql/* sql */.ll)`, `);
}
}
withSqlChunks.push((0,sql/* sql */.ll)` `);
return sql/* sql */.ll.join(withSqlChunks);
}
buildDeleteQuery({ table, where, returning, withList, limit, orderBy }) {
const withSql = this.buildWithCTE(withList);
const returningSql = returning ? (0,sql/* sql */.ll)` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
const whereSql = where ? (0,sql/* sql */.ll)` where ${where}` : void 0;
const orderBySql = this.buildOrderBy(orderBy);
const limitSql = this.buildLimit(limit);
return (0,sql/* sql */.ll)`${withSql}delete from ${table}${whereSql}${orderBySql}${limitSql}${returningSql}`;
}
buildUpdateSet(table, set) {
const tableColumns = table[drizzle_orm_table/* Table */.XI.Symbol.Columns];
const columnNames = Object.keys(tableColumns).filter(
(colName) => set[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0
);
const setSize = columnNames.length;
return sql/* sql */.ll.join(columnNames.flatMap((colName, i) => {
const col = tableColumns[colName];
const value = set[colName] ?? sql/* sql */.ll.param(col.onUpdateFn(), col);
const res = (0,sql/* sql */.ll)`${sql/* sql */.ll.identifier(this.casing.getColumnCasing(col))} = ${value}`;
if (i < setSize - 1) {
return [res, sql/* sql */.ll.raw(", ")];
}
return [res];
}));
}
buildUpdateQuery({ table, set, where, returning, withList, limit, orderBy }) {
const withSql = this.buildWithCTE(withList);
const setSql = this.buildUpdateSet(table, set);
const returningSql = returning ? (0,sql/* sql */.ll)` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
const whereSql = where ? (0,sql/* sql */.ll)` where ${where}` : void 0;
const orderBySql = this.buildOrderBy(orderBy);
const limitSql = this.buildLimit(limit);
return (0,sql/* sql */.ll)`${withSql}update ${table} set ${setSql}${whereSql}${orderBySql}${limitSql}${returningSql}`;
}
/**
* Builds selection SQL with provided fields/expressions
*
* Examples:
*
* `select <selection> from`
*
* `insert ... returning <selection>`
*
* If `isSingleTable` is true, then columns won't be prefixed with table name
*/
buildSelection(fields, { isSingleTable = false } = {}) {
const columnsLen = fields.length;
const chunks = fields.flatMap(({ field }, i) => {
const chunk = [];
if ((0,entity.is)(field, sql/* SQL */.Xs.Aliased) && field.isSelectionField) {
chunk.push(sql/* sql */.ll.identifier(field.fieldAlias));
} else if ((0,entity.is)(field, sql/* SQL */.Xs.Aliased) || (0,entity.is)(field, sql/* SQL */.Xs)) {
const query = (0,entity.is)(field, sql/* SQL */.Xs.Aliased) ? field.sql : field;
if (isSingleTable) {
chunk.push(
new sql/* SQL */.Xs(
query.queryChunks.map((c) => {
if ((0,entity.is)(c, common/* MySqlColumn */.rI)) {
return sql/* sql */.ll.identifier(this.casing.getColumnCasing(c));
}
return c;
})
)
);
} else {
chunk.push(query);
}
if ((0,entity.is)(field, sql/* SQL */.Xs.Aliased)) {
chunk.push((0,sql/* sql */.ll)` as ${sql/* sql */.ll.identifier(field.fieldAlias)}`);
}
} else if ((0,entity.is)(field, drizzle_orm_column/* Column */.V)) {
if (isSingleTable) {
chunk.push(sql/* sql */.ll.identifier(this.casing.getColumnCasing(field)));
} else {
chunk.push(field);
}
}
if (i < columnsLen - 1) {
chunk.push((0,sql/* sql */.ll)`, `);
}
return chunk;
});
return sql/* sql */.ll.join(chunks);
}
buildLimit(limit) {
return typeof limit === "object" || typeof limit === "number" && limit >= 0 ? (0,sql/* sql */.ll)` limit ${limit}` : void 0;
}
buildOrderBy(orderBy) {
return orderBy && orderBy.length > 0 ? (0,sql/* sql */.ll)` order by ${sql/* sql */.ll.join(orderBy, (0,sql/* sql */.ll)`, `)}` : void 0;
}
buildSelectQuery({
withList,
fields,
fieldsFlat,
where,
having,
table,
joins,
orderBy,
groupBy,
limit,
offset,
lockingClause,
distinct,
setOperators
}) {
const fieldsList = fieldsFlat ?? (0,utils/* orderSelectedFields */.He)(fields);
for (const f of fieldsList) {
if ((0,entity.is)(f.field, drizzle_orm_column/* Column */.V) && (0,drizzle_orm_table/* getTableName */.Io)(f.field.table) !== ((0,entity.is)(table, subquery/* Subquery */.n) ? table._.alias : (0,entity.is)(table, MySqlViewBase) ? table[view_common/* ViewBaseConfig */.n].name : (0,entity.is)(table, sql/* SQL */.Xs) ? void 0 : (0,drizzle_orm_table/* getTableName */.Io)(table)) && !((table2) => joins?.some(
({ alias }) => alias === (table2[drizzle_orm_table/* Table */.XI.Symbol.IsAlias] ? (0,drizzle_orm_table/* getTableName */.Io)(table2) : table2[drizzle_orm_table/* Table */.XI.Symbol.BaseName])
))(f.field.table)) {
const tableName = (0,drizzle_orm_table/* getTableName */.Io)(f.field.table);
throw new Error(
`Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`
);
}
}
const isSingleTable = !joins || joins.length === 0;
const withSql = this.buildWithCTE(withList);
const distinctSql = distinct ? (0,sql/* sql */.ll)` distinct` : void 0;
const selection = this.buildSelection(fieldsList, { isSingleTable });
const tableSql = (() => {
if ((0,entity.is)(table, drizzle_orm_table/* Table */.XI) && table[drizzle_orm_table/* Table */.XI.Symbol.OriginalName] !== table[drizzle_orm_table/* Table */.XI.Symbol.Name]) {
return (0,sql/* sql */.ll)`${sql/* sql */.ll.identifier(table[drizzle_orm_table/* Table */.XI.Symbol.OriginalName])} ${sql/* sql */.ll.identifier(table[drizzle_orm_table/* Table */.XI.Symbol.Name])}`;
}
return table;
})();
const joinsArray = [];
if (joins) {
for (const [index, joinMeta] of joins.entries()) {
if (index === 0) {
joinsArray.push((0,sql/* sql */.ll)` `);
}
const table2 = joinMeta.table;
const lateralSql = joinMeta.lateral ? (0,sql/* sql */.ll)` lateral` : void 0;
if ((0,entity.is)(table2, mysql_core_table/* MySqlTable */.B$)) {
const tableName = table2[mysql_core_table/* MySqlTable */.B$.Symbol.Name];
const tableSchema = table2[mysql_core_table/* MySqlTable */.B$.Symbol.Schema];
const origTableName = table2[mysql_core_table/* MySqlTable */.B$.Symbol.OriginalName];
const alias = tableName === origTableName ? void 0 : joinMeta.alias;
joinsArray.push(
(0,sql/* sql */.ll)`${sql/* sql */.ll.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? (0,sql/* sql */.ll)`${sql/* sql */.ll.identifier(tableSchema)}.` : void 0}${sql/* sql */.ll.identifier(origTableName)}${alias && (0,sql/* sql */.ll)` ${sql/* sql */.ll.identifier(alias)}`} on ${joinMeta.on}`
);
} else if ((0,entity.is)(table2, sql/* View */.Ss)) {
const viewName = table2[view_common/* ViewBaseConfig */.n].name;
const viewSchema = table2[view_common/* ViewBaseConfig */.n].schema;
const origViewName = table2[view_common/* ViewBaseConfig */.n].originalName;
const alias = viewName === origViewName ? void 0 : joinMeta.alias;
joinsArray.push(
(0,sql/* sql */.ll)`${sql/* sql */.ll.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? (0,sql/* sql */.ll)`${sql/* sql */.ll.identifier(viewSchema)}.` : void 0}${sql/* sql */.ll.identifier(origViewName)}${alias && (0,sql/* sql */.ll)` ${sql/* sql */.ll.identifier(alias)}`} on ${joinMeta.on}`
);
} else {
joinsArray.push(
(0,sql/* sql */.ll)`${sql/* sql */.ll.raw(joinMeta.joinType)} join${lateralSql} ${table2} on ${joinMeta.on}`
);
}
if (index < joins.length - 1) {
joinsArray.push((0,sql/* sql */.ll)` `);
}
}
}
const joinsSql = sql/* sql */.ll.join(joinsArray);
const whereSql = where ? (0,sql/* sql */.ll)` where ${where}` : void 0;
const havingSql = having ? (0,sql/* sql */.ll)` having ${having}` : void 0;
const orderBySql = this.buildOrderBy(orderBy);
const groupBySql = groupBy && groupBy.length > 0 ? (0,sql/* sql */.ll)` group by ${sql/* sql */.ll.join(groupBy, (0,sql/* sql */.ll)`, `)}` : void 0;
const limitSql = this.buildLimit(limit);
const offsetSql = offset ? (0,sql/* sql */.ll)` offset ${offset}` : void 0;
let lockingClausesSql;
if (lockingClause) {
const { config, strength } = lockingClause;
lockingClausesSql = (0,sql/* sql */.ll)` for ${sql/* sql */.ll.raw(strength)}`;
if (config.noWait) {
lockingClausesSql.append((0,sql/* sql */.ll)` no wait`);
} else if (config.skipLocked) {
lockingClausesSql.append((0,sql/* sql */.ll)` skip locked`);
}
}
const finalQuery = (0,sql/* sql */.ll)`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClausesSql}`;
if (setOperators.length > 0) {
return this.buildSetOperations(finalQuery, setOperators);
}
return finalQuery;
}
buildSetOperations(leftSelect, setOperators) {
const [setOperator, ...rest] = setOperators;
if (!setOperator) {
throw new Error("Cannot pass undefined values to any set operator");
}
if (rest.length === 0) {
return this.buildSetOperationQuery({ leftSelect, setOperator });
}
return this.buildSetOperations(
this.buildSetOperationQuery({ leftSelect, setOperator }),
rest
);
}
buildSetOperationQuery({
leftSelect,
setOperator: { type, isAll, rightSelect, limit, orderBy, offset }
}) {
const leftChunk = (0,sql/* sql */.ll)`(${leftSelect.getSQL()}) `;
const rightChunk = (0,sql/* sql */.ll)`(${rightSelect.getSQL()})`;
let orderBySql;
if (orderBy && orderBy.length > 0) {
const orderByValues = [];
for (const orderByUnit of orderBy) {
if ((0,entity.is)(orderByUnit, common/* MySqlColumn */.rI)) {
orderByValues.push(sql/* sql */.ll.identifier(this.casing.getColumnCasing(orderByUnit)));
} else if ((0,entity.is)(orderByUnit, sql/* SQL */.Xs)) {
for (let i = 0; i < orderByUnit.queryChunks.length; i++) {
const chunk = orderByUnit.queryChunks[i];
if ((0,entity.is)(chunk, common/* MySqlColumn */.rI)) {
orderByUnit.queryChunks[i] = sql/* sql */.ll.identifier(this.casing.getColumnCasing(chunk));
}
}
orderByValues.push((0,sql/* sql */.ll)`${orderByUnit}`);
} else {
orderByValues.push((0,sql/* sql */.ll)`${orderByUnit}`);
}
}
orderBySql = (0,sql/* sql */.ll)` order by ${sql/* sql */.ll.join(orderByValues, (0,sql/* sql */.ll)`, `)} `;
}
const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? (0,sql/* sql */.ll)` limit ${limit}` : void 0;
const operatorChunk = sql/* sql */.ll.raw(`${type} ${isAll ? "all " : ""}`);
const offsetSql = offset ? (0,sql/* sql */.ll)` offset ${offset}` : void 0;
return (0,sql/* sql */.ll)`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
}
buildInsertQuery({ table, values: valuesOrSelect, ignore, onConflict, select }) {
const valuesSqlList = [];
const columns = table[drizzle_orm_table/* Table */.XI.Symbol.Columns];
const colEntries = Object.entries(columns).filter(
([_, col]) => !col.shouldDisableInsert()
);
const insertOrder = colEntries.map(([, column]) => sql/* sql */.ll.identifier(this.casing.getColumnCasing(column)));
const generatedIdsResponse = [];
if (select) {
const select2 = valuesOrSelect;
if ((0,entity.is)(select2, sql/* SQL */.Xs)) {
valuesSqlList.push(select2);
} else {
valuesSqlList.push(select2.getSQL());
}
} else {
const values = valuesOrSelect;
valuesSqlList.push(sql/* sql */.ll.raw("values "));
for (const [valueIndex, value] of values.entries()) {
const generatedIds = {};
const valueList = [];
for (const [fieldName, col] of colEntries) {
const colValue = value[fieldName];
if (colValue === void 0 || (0,entity.is)(colValue, sql/* Param */.Iw) && colValue.value === void 0) {
if (col.defaultFn !== void 0) {
const defaultFnResult = col.defaultFn();
generatedIds[fieldName] = defaultFnResult;
const defaultValue = (0,entity.is)(defaultFnResult, sql/* SQL */.Xs) ? defaultFnResult : sql/* sql */.ll.param(defaultFnResult, col);
valueList.push(defaultValue);
} else if (!col.default && col.onUpdateFn !== void 0) {
const onUpdateFnResult = col.onUpdateFn();
const newValue = (0,entity.is)(onUpdateFnResult, sql/* SQL */.Xs) ? onUpdateFnResult : sql/* sql */.ll.param(onUpdateFnResult, col);
valueList.push(newValue);
} else {
valueList.push((0,sql/* sql */.ll)`default`);
}
} else {
if (col.defaultFn && (0,entity.is)(colValue, sql/* Param */.Iw)) {
generatedIds[fieldName] = colValue.value;
}
valueList.push(colValue);
}
}
generatedIdsResponse.push(generatedIds);
valuesSqlList.push(valueList);
if (valueIndex < values.length - 1) {
valuesSqlList.push((0,sql/* sql */.ll)`, `);
}
}
}
const valuesSql = sql/* sql */.ll.join(valuesSqlList);
const ignoreSql = ignore ? (0,sql/* sql */.ll)` ignore` : void 0;
const onConflictSql = onConflict ? (0,sql/* sql */.ll)` on duplicate key ${onConflict}` : void 0;
return {
sql: (0,sql/* sql */.ll)`insert${ignoreSql} into ${table} ${insertOrder} ${valuesSql}${onConflictSql}`,
generatedIds: generatedIdsResponse
};
}
sqlToQuery(sql2, invokeSource) {
return sql2.toQuery({
casing: this.casing,
escapeName: this.escapeName,
escapeParam: this.escapeParam,
escapeString: this.escapeString,
invokeSource
});
}
buildRelationalQuery({
fullSchema,
schema,
tableNamesMap,
table,
tableConfig,
queryConfig: config,
tableAlias,
nestedQueryRelation,
joinOn
}) {
let selection = [];
let limit, offset, orderBy, where;
const joins = [];
if (config === true) {
const selectionEntries = Object.entries(tableConfig.columns);
selection = selectionEntries.map(([key, value]) => ({
dbKey: value.name,
tsKey: key,
field: (0,alias/* aliasedTableColumn */.ug)(value, tableAlias),
relationTableTsKey: void 0,
isJson: false,
selection: []
}));
} else {
const aliasedColumns = Object.fromEntries(
Object.entries(tableConfig.columns).map(([key, value]) => [key, (0,alias/* aliasedTableColumn */.ug)(value, tableAlias)])
);
if (config.where) {
const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, (0,relations/* getOperators */.mm)()) : config.where;
where = whereSql && (0,alias/* mapColumnsInSQLToAlias */.yY)(whereSql, tableAlias);
}
const fieldsSelection = [];
let selectedColumns = [];
if (config.columns) {
let isIncludeMode = false;
for (const [field, value] of Object.entries(config.columns)) {
if (value === void 0) {
continue;
}
if (field in tableConfig.columns) {
if (!isIncludeMode && value === true) {
isIncludeMode = true;
}
selectedColumns.push(field);
}
}
if (selectedColumns.length > 0) {
selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
}
} else {
selectedColumns = Object.keys(tableConfig.columns);
}
for (const field of selectedColumns) {
const column = tableConfig.columns[field];
fieldsSelection.push({ tsKey: field, value: column });
}
let selectedRelations = [];
if (config.with) {
selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
}
let extras;
if (config.extras) {
extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql: sql/* sql */.ll }) : config.extras;
for (const [tsKey, value] of Object.entries(extras)) {
fieldsSelection.push({
tsKey,
value: (0,alias/* mapColumnsInAliasedSQLToAlias */.Hs)(value, tableAlias)
});
}
}
for (const { tsKey, value } of fieldsSelection) {
selection.push({
dbKey: (0,entity.is)(value, sql/* SQL */.Xs.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
tsKey,
field: (0,entity.is)(value, drizzle_orm_column/* Column */.V) ? (0,alias/* aliasedTableColumn */.ug)(value, tableAlias) : value,
relationTableTsKey: void 0,
isJson: false,
selection: []
});
}
let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, (0,relations/* getOrderByOperators */.rl)()) : config.orderBy ?? [];
if (!Array.isArray(orderByOrig)) {
orderByOrig = [orderByOrig];
}
orderBy = orderByOrig.map((orderByValue) => {
if ((0,entity.is)(orderByValue, drizzle_orm_column/* Column */.V)) {
return (0,alias/* aliasedTableColumn */.ug)(orderByValue, tableAlias);
}
return (0,alias/* mapColumnsInSQLToAlias */.yY)(orderByValue, tableAlias);
});
limit = config.limit;
offset = config.offset;
for (const {
tsKey: selectedRelationTsKey,
queryConfig: selectedRelationConfigValue,
relation
} of selectedRelations) {
const normalizedRelation = (0,relations/* normalizeRelation */.W0)(schema, tableNamesMap, relation);
const relationTableName = (0,drizzle_orm_table/* getTableUniqueName */.Lf)(relation.referencedTable);
const relationTableTsName = tableNamesMap[relationTableName];
const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
const joinOn2 = (0,conditions/* and */.Uo)(
...normalizedRelation.fields.map(
(field2, i) => (0,conditions.eq)(
(0,alias/* aliasedTableColumn */.ug)(normalizedRelation.references[i], relationTableAlias),
(0,alias/* aliasedTableColumn */.ug)(field2, tableAlias)
)
)
);
const builtRelation = this.buildRelationalQuery({
fullSchema,
schema,
tableNamesMap,
table: fullSchema[relationTableTsName],
tableConfig: schema[relationTableTsName],
queryConfig: (0,entity.is)(relation, relations/* One */.pD) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
tableAlias: relationTableAlias,
joinOn: joinOn2,
nestedQueryRelation: relation
});
const field = (0,sql/* sql */.ll)`${sql/* sql */.ll.identifier(relationTableAlias)}.${sql/* sql */.ll.identifier("data")}`.as(selectedRelationTsKey);
joins.push({
on: (0,sql/* sql */.ll)`true`,
table: new subquery/* Subquery */.n(builtRelation.sql, {}, relationTableAlias),
alias: relationTableAlias,
joinType: "left",
lateral: true
});
selection.push({
dbKey: selectedRelationTsKey,
tsKey: selectedRelationTsKey,
field,
relationTableTsKey: relationTableTsName,
isJson: true,
selection: builtRelation.selection
});
}
}
if (selection.length === 0) {
throw new errors/* DrizzleError */.n({ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")` });
}
let result;
where = (0,conditions/* and */.Uo)(joinOn, where);
if (nestedQueryRelation) {
let field = (0,sql/* sql */.ll)`json_array(${sql/* sql */.ll.join(
selection.map(
({ field: field2, tsKey, isJson }) => isJson ? (0,sql/* sql */.ll)`${sql/* sql */.ll.identifier(`${tableAlias}_${tsKey}`)}.${sql/* sql */.ll.identifier("data")}` : (0,entity.is)(field2, sql/* SQL */.Xs.Aliased) ? field2.sql : field2
),
(0,sql/* sql */.ll)`, `
)})`;
if ((0,entity.is)(nestedQueryRelation, relations/* Many */.iv)) {
field = (0,sql/* sql */.ll)`coalesce(json_arrayagg(${field}), json_array())`;
}
const nestedSelection = [{
dbKey: "data",
tsKey: "data",
field: field.as("data"),
isJson: true,
relationTableTsKey: tableConfig.tsName,
selection
}];
const needsSubquery = limit !== void 0 || offset !== void 0 || (orderBy?.length ?? 0) > 0;
if (needsSubquery) {
result = this.buildSelectQuery({
table: (0,alias/* aliasedTable */.oG)(table, tableAlias),
fields: {},
fieldsFlat: [
{
path: [],
field: sql/* sql */.ll.raw("*")
},
...((orderBy?.length ?? 0) > 0 ? [{
path: [],
field: (0,sql/* sql */.ll)`row_number() over (order by ${sql/* sql */.ll.join(orderBy, (0,sql/* sql */.ll)`, `)})`
}] : [])
],
where,
limit,
offset,
setOperators: []
});
where = void 0;
limit = void 0;
offset = void 0;
orderBy = void 0;
} else {
result = (0,alias/* aliasedTable */.oG)(table, tableAlias);
}
result = this.buildSelectQuery({
table: (0,entity.is)(result, mysql_core_table/* MySqlTable */.B$) ? result : new subquery/* Subquery */.n(result, {}, tableAlias),
fields: {},
fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
path: [],
field: (0,entity.is)(field2, drizzle_orm_column/* Column */.V) ? (0,alias/* aliasedTableColumn */.ug)(field2, tableAlias) : field2
})),
joins,
where,
limit,
offset,
orderBy,
setOperators: []
});
} else {
result = this.buildSelectQuery({
table: (0,alias/* aliasedTable */.oG)(table, tableAlias),
fields: {},
fieldsFlat: selection.map(({ field }) => ({
path: [],
field: (0,entity.is)(field, drizzle_orm_column/* Column */.V) ? (0,alias/* aliasedTableColumn */.ug)(field, tableAlias) : field
})),
joins,
where,
limit,
offset,
orderBy,
setOperators: []
});
}
return {
tableTsKey: tableConfig.tsName,
sql: result,
selection
};
}
buildRelationalQueryWithoutLateralSubqueries({
fullSchema,
schema,
tableNamesMap,
table,
tableConfig,
queryConfig: config,
tableAlias,
nestedQueryRelation,
joinOn
}) {
let selection = [];
let limit, offset, orderBy = [], where;
if (config === true) {
const selectionEntries = Object.entries(tableConfig.columns);
selection = selectionEntries.map(([key, value]) => ({
dbKey: value.name,
tsKey: key,
field: (0,alias/* aliasedTableColumn */.ug)(value, tableAlias),
relationTableTsKey: void 0,
isJson: false,
selection: []
}));
} else {
const aliasedColumns = Object.fromEntries(
Object.entries(tableConfig.columns).map(([key, value]) => [key, (0,alias/* aliasedTableColumn */.ug)(value, tableAlias)])
);
if (config.where) {
const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, (0,relations/* getOperators */.mm)()) : config.where;
where = whereSql && (0,alias/* mapColumnsInSQLToAlias */.yY)(whereSql, tableAlias);
}
const fieldsSelection = [];
let selectedColumns = [];
if (config.columns) {
let isIncludeMode = false;
for (const [field, value] of Object.entries(config.columns)) {
if (value === void 0) {
continue;
}
if (field in tableConfig.columns) {
if (!isIncludeMode && value === true) {
isIncludeMode = true;
}
selectedColumns.push(field);
}
}
if (selectedColumns.length > 0) {
selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
}
} else {
selectedColumns = Object.keys(tableConfig.columns);
}
for (const field of selectedColumns) {
const column = tableConfig.columns[field];
fieldsSelection.push({ tsKey: field, value: column });
}
let selectedRelations = [];
if (config.with) {
selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
}
let extras;
if (config.extras) {
extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql: sql/* sql */.ll }) : config.extras;
for (const [tsKey, value] of Object.entries(extras)) {
fieldsSelection.push({
tsKey,
value: (0,alias/* mapColumnsInAliasedSQLToAlias */.Hs)(value, tableAlias)
});
}
}
for (const { tsKey, value } of fieldsSelection) {
selection.push({
dbKey: (0,entity.is)(value, sql/* SQL */.Xs.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
tsKey,
field: (0,entity.is)(value, drizzle_orm_column/* Column */.V) ? (0,alias/* aliasedTableColumn */.ug)(value, tableAlias) : value,
relationTableTsKey: void 0,
isJson: false,
selection: []
});
}
let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, (0,relations/* getOrderByOperators */.rl)()) : config.orderBy ?? [];
if (!Array.isArray(orderByOrig)) {
orderByOrig = [orderByOrig];
}
orderBy = orderByOrig.map((orderByValue) => {
if ((0,entity.is)(orderByValue, drizzle_orm_column/* Column */.V)) {
return (0,alias/* aliasedTableColumn */.ug)(orderByValue, tableAlias);
}
return (0,alias/* mapColumnsInSQLToAlias */.yY)(orderByValue, tableAlias);
});
limit = config.limit;
offset = config.offset;
for (const {
tsKey: selectedRelationTsKey,
queryConfig: selectedRelationConfigValue,
relation
} of selectedRelations) {
const normalizedRelation = (0,relations/* normalizeRelation */.W0)(schema, tableNamesMap, relation);
const relationTableName = (0,drizzle_orm_table/* getTableUniqueName */.Lf)(relation.referencedTable);
const relationTableTsName = tableNamesMap[relationTableName];
const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
const joinOn2 = (0,conditions/* and */.Uo)(
...normalizedRelation.fields.map(
(field2, i) => (0,conditions.eq)(
(0,alias/* aliasedTableColumn */.ug)(normalizedRelation.references[i], relationTableAlias),
(0,alias/* aliasedTableColumn */.ug)(field2, tableAlias)
)
)
);
const builtRelation = this.buildRelationalQueryWithoutLateralSubqueries({
fullSchema,
schema,
tableNamesMap,
table: fullSchema[relationTableTsName],
tableConfig: schema[relationTableTsName],
queryConfig: (0,entity.is)(relation, relations/* One */.pD) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
tableAlias: relationTableAlias,
joinOn: joinOn2,
nestedQueryRelation: relation
});
let fieldSql = (0,sql/* sql */.ll)`(${builtRelation.sql})`;
if ((0,entity.is)(relation, relations/* Many */.iv)) {
fieldSql = (0,sql/* sql */.ll)`coalesce(${fieldSql}, json_array())`;
}
const field = fieldSql.as(selectedRelationTsKey);
selection.push({
dbKey: selectedRelationTsKey,
tsKey: selectedRelationTsKey,
field,
relationTableTsKey: relationTableTsName,
isJson: true,
selection: builtRelation.selection
});
}
}
if (selection.length === 0) {
throw new errors/* DrizzleError */.n({
message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`
});
}
let result;
where = (0,conditions/* and */.Uo)(joinOn, where);
if (nestedQueryRelation) {
let field = (0,sql/* sql */.ll)`json_array(${sql/* sql */.ll.join(
selection.map(
({ field: field2 }) => (0,entity.is)(field2, common/* MySqlColumn */.rI) ? sql/* sql */.ll.identifier(this.casing.getColumnCasing(field2)) : (0,entity.is)(field2, sql/* SQL */.Xs.Aliased) ? field2.sql : field2
),
(0,sql/* sql */.ll)`, `
)})`;
if ((0,entity.is)(nestedQueryRelation, relations/* Many */.iv)) {
field = (0,sql/* sql */.ll)`json_arrayagg(${field})`;
}
const nestedSelection = [{
dbKey: "data",
tsKey: "data",
field,
isJson: true,
relationTableTsKey: tableConfig.tsName,
selection
}];
const needsSubquery = limit !== void 0 || offset !== void 0 || orderBy.length > 0;
if (needsSubquery) {
result = this.buildSelectQuery({
table: (0,alias/* aliasedTable */.oG)(table, tableAlias),
fields: {},
fieldsFlat: [
{
path: [],
field: sql/* sql */.ll.raw("*")
},
...(orderBy.length > 0 ? [{
path: [],
field: (0,sql/* sql */.ll)`row_number() over (order by ${sql/* sql */.ll.join(orderBy, (0,sql/* sql */.ll)`, `)})`
}] : [])
],
where,
limit,
offset,
setOperators: []
});
where = void 0;
limit = void 0;
offset = void 0;
orderBy = void 0;
} else {
result = (0,alias/* aliasedTable */.oG)(table, tableAlias);
}
result = this.buildSelectQuery({
table: (0,entity.is)(result, mysql_core_table/* MySqlTable */.B$) ? result : new subquery/* Subquery */.n(result, {}, tableAlias),
fields: {},
fieldsFlat: nestedSelection.map(({ field: field2 })