cormo
Advanced tools
Comparing version 0.19.3 to 1.0.0
@@ -12,3 +12,3 @@ import { ColumnPropertyInternal } from '../model'; | ||
columns: { | ||
[column_name: string]: SchemasColumn; | ||
[column_name: string]: SchemasColumn | undefined; | ||
}; | ||
@@ -22,6 +22,6 @@ description?: string; | ||
tables: { | ||
[table_name: string]: SchemasTable | 'NO SCHEMA'; | ||
[table_name: string]: SchemasTable | 'NO SCHEMA' | undefined; | ||
}; | ||
indexes?: { | ||
[table_name: string]: SchemasIndex; | ||
[table_name: string]: SchemasIndex | undefined; | ||
}; | ||
@@ -28,0 +28,0 @@ foreign_keys?: { |
"use strict"; | ||
/* eslint-disable @typescript-eslint/no-unused-vars */ | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
@@ -84,3 +89,3 @@ if (k2 === undefined) k2 = k; | ||
*/ | ||
getCreateTableQuery(model) { | ||
getCreateTableQuery(model_name) { | ||
return null; | ||
@@ -94,3 +99,3 @@ } | ||
*/ | ||
async createTable(model, verbose = false) { | ||
async createTable(model_name, verbose = false) { | ||
return Promise.resolve(); | ||
@@ -103,3 +108,3 @@ } | ||
*/ | ||
getUpdateTableDescriptionQuery(model) { | ||
getUpdateTableDescriptionQuery(model_name) { | ||
return null; | ||
@@ -113,3 +118,3 @@ } | ||
*/ | ||
async updateTableDescription(model, verbose = false) { | ||
async updateTableDescription(model_name, verbose = false) { | ||
return Promise.resolve(); | ||
@@ -122,3 +127,3 @@ } | ||
*/ | ||
getAddColumnQuery(model, column_property) { | ||
getAddColumnQuery(model_name, column_property) { | ||
return null; | ||
@@ -131,3 +136,3 @@ } | ||
*/ | ||
async addColumn(model, column_property, verbose = false) { | ||
async addColumn(model_name, column_property, verbose = false) { | ||
return Promise.resolve(); | ||
@@ -140,3 +145,3 @@ } | ||
*/ | ||
getUpdateColumnDescriptionQuery(model, column_property) { | ||
getUpdateColumnDescriptionQuery(model_name, column_property) { | ||
return null; | ||
@@ -150,3 +155,3 @@ } | ||
*/ | ||
async updateColumnDescription(model, column_property, verbose = false) { | ||
async updateColumnDescription(model_name, column_property, verbose = false) { | ||
return Promise.resolve(); | ||
@@ -175,3 +180,3 @@ } | ||
*/ | ||
getCreateForeignKeyQuery(model, column, type, references) { | ||
getCreateForeignKeyQuery(model_name, column, type, references) { | ||
return null; | ||
@@ -184,3 +189,3 @@ } | ||
*/ | ||
async createForeignKey(model, column, type, references, verbose = false) { | ||
async createForeignKey(model_name, column, type, references, verbose = false) { | ||
return Promise.resolve(); | ||
@@ -203,3 +208,3 @@ } | ||
*/ | ||
async drop(model) { | ||
async drop(model_name) { | ||
return Promise.reject(new Error('not implemented')); | ||
@@ -278,8 +283,11 @@ } | ||
/** @internal */ | ||
_convertToModelInstance(model, data, options) { | ||
_convertToModelInstance(model_name, data, options) { | ||
if (options.lean) { | ||
model = this._connection.models[model]; | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return null; | ||
} | ||
const instance = {}; | ||
this.setValuesFromDB(instance, data, model._schema, options.select); | ||
model._collapseNestedNulls(instance, options.select_raw, null); | ||
this.setValuesFromDB(instance, data, model_class._schema, options.select); | ||
model_class._collapseNestedNulls(instance, options.select_raw, null); | ||
const id = this._getModelID(data); | ||
@@ -293,4 +301,4 @@ if (id) { | ||
const id = this._getModelID(data); | ||
const modelClass = this._connection.models[model]; | ||
return new modelClass(data, id, options.select, options.select_raw); | ||
const model_class = this._connection.models[model_name]; | ||
return new model_class(data, id, options.select, options.select_raw); | ||
} | ||
@@ -302,5 +310,9 @@ } | ||
if (group_by) { | ||
const schema = this._connection.models[model_name]._schema; | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const schema = model_class._schema; | ||
for (const field of group_by) { | ||
const property = lodash_1.default.find(schema, (item) => item._dbname_us === field); | ||
const property = lodash_1.default.find(schema, (item) => item?._dbname_us === field); | ||
if (property) { | ||
@@ -324,5 +336,5 @@ util.setPropertyOfPath(instance, property._parts, this.valueToModel(data[field], property)); | ||
/** @internal */ | ||
async _createBulkDefault(model, data, options) { | ||
async _createBulkDefault(model_name, data, options) { | ||
return await Promise.all(data.map((item) => { | ||
return this.create(model, item, options); | ||
return this.create(model_name, item, options); | ||
})); | ||
@@ -334,3 +346,3 @@ } | ||
AdapterBase.wrapError = (msg, cause) => { | ||
if (msg === 'unknown error' && cause && cause.message === 'transaction finished') { | ||
if (msg === 'unknown error' && cause.message === 'transaction finished') { | ||
return cause; | ||
@@ -337,0 +349,0 @@ } |
@@ -14,4 +14,4 @@ export interface AdapterSettingsMongoDB { | ||
*/ | ||
collection(model: any): any; | ||
collection(model_name: string): any; | ||
} | ||
export declare function createAdapter(connection: Connection): MongoDBAdapter; |
@@ -5,3 +5,7 @@ "use strict"; | ||
if (k2 === undefined) k2 = k; | ||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
@@ -256,3 +260,3 @@ if (k2 === undefined) k2 = k; | ||
let column = sub_expr.substr(1); | ||
column = (schema[column] && schema[column]._dbname_us) || column; | ||
column = schema[column]?._dbname_us || column; | ||
return { [op]: `$${column}` }; | ||
@@ -338,5 +342,8 @@ } | ||
/** @internal */ | ||
async createTable(model) { | ||
const collection = this._collection(model); | ||
const model_class = this._connection.models[model]; | ||
async createTable(model_name) { | ||
const collection = this._collection(model_name); | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const schema = model_class._schema; | ||
@@ -347,3 +354,3 @@ await this._db.createCollection(_getMongoDBColName(model_class.table_name)); | ||
const property = schema[column]; | ||
if (property.type_class === types.GeoPoint) { | ||
if (property?.type_class === types.GeoPoint) { | ||
indexes.push([lodash_1.default.zipObject([column], ['2d'])]); | ||
@@ -375,4 +382,8 @@ } | ||
/** @internal */ | ||
async drop(model) { | ||
const name = this._connection.models[model].table_name; | ||
async drop(model_name) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const name = model_class.table_name; | ||
delete this._collections[name]; | ||
@@ -410,6 +421,6 @@ try { | ||
/** @internal */ | ||
async create(model, data, options) { | ||
async create(model_name, data, _options) { | ||
let result; | ||
try { | ||
result = await this._collection(model).insertOne(data, { safe: true }); | ||
result = await this._collection(model_name).insertOne(data, { safe: true }); | ||
} | ||
@@ -429,3 +440,3 @@ catch (error) { | ||
/** @internal */ | ||
async createBulk(model, data, options) { | ||
async createBulk(model_name, data, options) { | ||
if (data.length > 1000) { | ||
@@ -440,3 +451,3 @@ const chunks = []; | ||
for (const chunk of chunks) { | ||
[].push.apply(ids_all, await this.createBulk(model, chunk, options)); | ||
[].push.apply(ids_all, await this.createBulk(model_name, chunk, options)); | ||
} | ||
@@ -447,3 +458,3 @@ return ids_all; | ||
try { | ||
result = await this._collection(model).insertMany(data, { safe: true }); | ||
result = await this._collection(model_name).insertMany(data, { safe: true }); | ||
} | ||
@@ -469,7 +480,7 @@ catch (e) { | ||
/** @internal */ | ||
async update(model, data, options) { | ||
async update(model_name, data, _options) { | ||
const id = data.id; | ||
delete data.id; | ||
try { | ||
await this._collection(model).replaceOne({ _id: id }, data, { safe: true }); | ||
await this._collection(model_name).replaceOne({ _id: id }, data, { safe: true }); | ||
} | ||
@@ -481,4 +492,8 @@ catch (error) { | ||
/** @internal */ | ||
async updatePartial(model, data, conditions_arg, options) { | ||
const schema = this._connection.models[model]._schema; | ||
async updatePartial(model_name, data, conditions_arg, _options) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return 0; | ||
} | ||
const schema = model_class._schema; | ||
let conditions = _buildWhere(schema, conditions_arg); | ||
@@ -504,3 +519,3 @@ if (!conditions) { | ||
try { | ||
const result = await this._collection(model).updateMany(conditions, update_ops, { safe: true, multi: true }); | ||
const result = await this._collection(model_name).updateMany(conditions, update_ops, { safe: true, multi: true }); | ||
return result.modifiedCount; | ||
@@ -513,4 +528,8 @@ } | ||
/** @internal */ | ||
async upsert(model, data, conditions_arg, options) { | ||
const schema = this._connection.models[model]._schema; | ||
async upsert(model_name, data, conditions_arg, options) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const schema = model_class._schema; | ||
let conditions = _buildWhere(schema, conditions_arg); | ||
@@ -544,3 +563,3 @@ if (!conditions) { | ||
try { | ||
await this._collection(model).updateMany(conditions, update_ops, { safe: true, upsert: true }); | ||
await this._collection(model_name).updateMany(conditions, update_ops, { safe: true, upsert: true }); | ||
} | ||
@@ -552,3 +571,3 @@ catch (error) { | ||
/** @internal */ | ||
async findById(model, id, options) { | ||
async findById(model_name, id, options) { | ||
const fields = this._buildSelect(options.select); | ||
@@ -567,7 +586,7 @@ try { | ||
client_options.explain = true; | ||
return await this._collection(model).findOne({ _id: id }, client_options); | ||
return await this._collection(model_name).findOne({ _id: id }, client_options); | ||
} | ||
let result; | ||
try { | ||
result = await this._collection(model).findOne({ _id: id }, client_options); | ||
result = await this._collection(model_name).findOne({ _id: id }, client_options); | ||
} | ||
@@ -581,13 +600,13 @@ catch (error) { | ||
} | ||
return this._convertToModelInstance(model, result, options); | ||
return this._convertToModelInstance(model_name, result, options); | ||
} | ||
/** @internal */ | ||
async find(model_name, conditions, options) { | ||
let fields; | ||
let orders; | ||
let client_options; | ||
[conditions, fields, orders, client_options] = this._buildConditionsForFind(model_name, conditions, options); | ||
async find(model_name, conditions_arg, options) { | ||
const [conditions, , orders, client_options] = this._buildConditionsForFind(model_name, conditions_arg, options); | ||
// console.log(JSON.stringify(conditions)); | ||
if (options.group_by || options.group_fields) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
throw new Error('model not found'); | ||
} | ||
const pipeline = []; | ||
@@ -656,8 +675,22 @@ if (conditions) { | ||
/** @internal */ | ||
stream(model, conditions, options) { | ||
let fields; | ||
let orders; | ||
let client_options; | ||
stream(model_name, conditions_arg, options) { | ||
try { | ||
[conditions, fields, orders, client_options] = this._buildConditionsForFind(model, conditions, options); | ||
const [conditions, , , client_options] = this._buildConditionsForFind(model_name, conditions_arg, options); | ||
const transformer = new stream_1.default.Transform({ objectMode: true }); | ||
transformer._transform = (record, encoding, callback) => { | ||
transformer.push(this._convertToModelInstance(model_name, record, options)); | ||
callback(); | ||
}; | ||
try { | ||
const cursor = this._collection(model_name).find(conditions, client_options).stream(); | ||
cursor | ||
.on('error', (e) => { | ||
transformer.emit('error', e); | ||
}) | ||
.pipe(transformer); | ||
} | ||
catch (error) { | ||
transformer.emit('error', MongoDBAdapter.wrapError('unknown error', error)); | ||
} | ||
return transformer; | ||
} | ||
@@ -671,19 +704,2 @@ catch (e) { | ||
} | ||
const transformer = new stream_1.default.Transform({ objectMode: true }); | ||
transformer._transform = (record, encoding, callback) => { | ||
transformer.push(this._convertToModelInstance(model, record, options)); | ||
callback(); | ||
}; | ||
try { | ||
const cursor = this._collection(model).find(conditions, client_options).stream(); | ||
cursor | ||
.on('error', (e) => { | ||
transformer.emit('error', e); | ||
}) | ||
.pipe(transformer); | ||
} | ||
catch (error) { | ||
transformer.emit('error', MongoDBAdapter.wrapError('unknown error', error)); | ||
} | ||
return transformer; | ||
} | ||
@@ -693,2 +709,5 @@ /** @internal */ | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return 0; | ||
} | ||
const conditions = _buildWhere(model_class._schema, conditions_arg); | ||
@@ -732,5 +751,16 @@ // console.log(JSON.stringify(conditions)) | ||
const model_class = this._connection.models[model_name]; | ||
if (options && (options.orders.length > 0 || options.limit || options.skip)) { | ||
const [conditions_find, fields, orders, client_options] = this._buildConditionsForFind(model_name, conditions_arg, Object.assign(Object.assign({}, options), { lean: true, joins: [], conditions_of_group: [] })); | ||
const cursor = await this._collection(model_name).find(conditions_find, Object.assign(Object.assign({}, client_options), { projection: { _id: 1 } })); | ||
if (!model_class) { | ||
return 0; | ||
} | ||
if (options.orders.length > 0 || options.limit || options.skip) { | ||
const [conditions_find, , , client_options] = this._buildConditionsForFind(model_name, conditions_arg, { | ||
...options, | ||
lean: true, | ||
joins: [], | ||
conditions_of_group: [], | ||
}); | ||
const cursor = await this._collection(model_name).find(conditions_find, { | ||
...client_options, | ||
projection: { _id: 1 }, | ||
}); | ||
const records = await cursor.toArray(); | ||
@@ -786,4 +816,4 @@ const ids = records.map(this._getModelID); | ||
*/ | ||
collection(model) { | ||
return this._collection(model); | ||
collection(model_name) { | ||
return this._collection(model_name); | ||
} | ||
@@ -827,4 +857,8 @@ /** @internal */ | ||
/** @internal */ | ||
_collection(model) { | ||
const name = this._connection.models[model].table_name; | ||
_collection(model_name) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const name = model_class.table_name; | ||
if (!this._collections[name]) { | ||
@@ -844,3 +878,3 @@ return (this._collections[name] = this._db.collection(_getMongoDBColName(name))); | ||
/** @internal */ | ||
async _getSchema(table) { | ||
async _getSchema(_table) { | ||
return Promise.resolve('NO SCHEMA'); | ||
@@ -871,3 +905,3 @@ } | ||
if (value.$inc != null) { | ||
if (ignore_on_update === null || ignore_on_update === void 0 ? void 0 : ignore_on_update.includes(column)) { | ||
if (ignore_on_update?.includes(column)) { | ||
update_ops.$setOnInsert[path + column] = value.$inc; | ||
@@ -880,3 +914,3 @@ } | ||
else { | ||
if (ignore_on_update === null || ignore_on_update === void 0 ? void 0 : ignore_on_update.includes(column)) { | ||
if (ignore_on_update?.includes(column)) { | ||
update_ops.$setOnInsert[path + column] = value; | ||
@@ -899,6 +933,10 @@ } | ||
/** @internal */ | ||
_buildConditionsForFind(model, conditions_arg, options) { | ||
_buildConditionsForFind(model_name, conditions_arg, options) { | ||
const fields = this._buildSelect(options.select); | ||
let orders; | ||
let conditions = _buildWhere(this._connection.models[model]._schema, conditions_arg); | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return [undefined, undefined, undefined, {}]; | ||
} | ||
let conditions = _buildWhere(model_class._schema, conditions_arg); | ||
if (options.near != null && Object.keys(options.near)[0]) { | ||
@@ -905,0 +943,0 @@ const field = Object.keys(options.near)[0]; |
/// <reference types="node" /> | ||
/// <reference types="node" /> | ||
import tls = require('tls'); | ||
import { Connection } from '../connection'; | ||
import { Transaction } from '../transaction'; | ||
import { SQLAdapterBase } from './sql_base'; | ||
export interface AdapterSettingsMySQL { | ||
@@ -35,5 +39,2 @@ host?: string; | ||
} | ||
import { Connection } from '../connection'; | ||
import { Transaction } from '../transaction'; | ||
import { SQLAdapterBase } from './sql_base'; | ||
export declare class MySQLAdapter extends SQLAdapterBase { | ||
@@ -40,0 +41,0 @@ /** |
@@ -5,3 +5,7 @@ "use strict"; | ||
if (k2 === undefined) k2 = k; | ||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
@@ -30,2 +34,7 @@ if (k2 === undefined) k2 = k; | ||
let is_mysql2 = false; | ||
const stream_1 = __importDefault(require("stream")); | ||
const util_1 = __importDefault(require("util")); | ||
const lodash_1 = __importDefault(require("lodash")); | ||
const types = __importStar(require("../types")); | ||
const sql_base_1 = require("./sql_base"); | ||
try { | ||
@@ -43,7 +52,2 @@ mysql = require('mysql2'); | ||
} | ||
const stream_1 = __importDefault(require("stream")); | ||
const util_1 = __importDefault(require("util")); | ||
const lodash_1 = __importDefault(require("lodash")); | ||
const types = __importStar(require("../types")); | ||
const sql_base_1 = require("./sql_base"); | ||
function _typeToSQL(property, support_fractional_seconds, major_version) { | ||
@@ -96,3 +100,3 @@ if (property.array) { | ||
try { | ||
client = mysql.createConnection(Object.assign(Object.assign({}, config), { connectTimeout: 2000 })); | ||
client = mysql.createConnection({ ...config, connectTimeout: 2000 }); | ||
client.connectAsync = util_1.default.promisify(client.connect); | ||
@@ -174,4 +178,7 @@ client.queryAsync = util_1.default.promisify(client.query); | ||
/** @internal */ | ||
getCreateTableQuery(model) { | ||
const model_class = this._connection.models[model]; | ||
getCreateTableQuery(model_name) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return ''; | ||
} | ||
const table_name = model_class.table_name; | ||
@@ -181,2 +188,5 @@ const column_sqls = []; | ||
const property = model_class._schema[column]; | ||
if (!property) { | ||
continue; | ||
} | ||
if (property.primary_key) { | ||
@@ -204,4 +214,4 @@ column_sqls.push(`\`${property._dbname_us}\` BIGINT NOT NULL AUTO_INCREMENT UNIQUE PRIMARY KEY`); | ||
/** @internal */ | ||
async createTable(model, verbose = false) { | ||
const query = this.getCreateTableQuery(model); | ||
async createTable(model_name, verbose = false) { | ||
const query = this.getCreateTableQuery(model_name); | ||
if (verbose) { | ||
@@ -218,11 +228,13 @@ console.log(` (${query})`); | ||
/** @internal */ | ||
getUpdateTableDescriptionQuery(model) { | ||
var _a; | ||
const model_class = this._connection.models[model]; | ||
getUpdateTableDescriptionQuery(model_name) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return ''; | ||
} | ||
const table_name = model_class.table_name; | ||
return `ALTER TABLE ${table_name} COMMENT ${mysql.escape((_a = model_class.description) !== null && _a !== void 0 ? _a : '')}`; | ||
return `ALTER TABLE ${table_name} COMMENT ${mysql.escape(model_class.description ?? '')}`; | ||
} | ||
/** @internal */ | ||
async updateTableDescription(model, verbose = false) { | ||
const query = this.getUpdateTableDescriptionQuery(model); | ||
async updateTableDescription(model_name, verbose = false) { | ||
const query = this.getUpdateTableDescriptionQuery(model_name); | ||
if (verbose) { | ||
@@ -239,4 +251,7 @@ console.log(` (${query})`); | ||
/** @internal */ | ||
getAddColumnQuery(model, column_property) { | ||
const model_class = this._connection.models[model]; | ||
getAddColumnQuery(model_name, column_property) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return ''; | ||
} | ||
const table_name = model_class.table_name; | ||
@@ -250,4 +265,4 @@ let column_sql = _propertyToSQL(column_property, this.support_fractional_seconds, this._version.major); | ||
/** @internal */ | ||
async addColumn(model, column_property, verbose = false) { | ||
const query = this.getAddColumnQuery(model, column_property); | ||
async addColumn(model_name, column_property, verbose = false) { | ||
const query = this.getAddColumnQuery(model_name, column_property); | ||
if (verbose) { | ||
@@ -264,4 +279,7 @@ console.log(` (${query})`); | ||
/** @internal */ | ||
getUpdateColumnDescriptionQuery(model, column_property) { | ||
const model_class = this._connection.models[model]; | ||
getUpdateColumnDescriptionQuery(model_name, column_property) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return ''; | ||
} | ||
const table_name = model_class.table_name; | ||
@@ -275,4 +293,4 @@ let column_sql = _propertyToSQL(column_property, this.support_fractional_seconds, this._version.major); | ||
/** @internal */ | ||
async updateColumnDescription(model, column_property, verbose = false) { | ||
const query = this.getUpdateColumnDescriptionQuery(model, column_property); | ||
async updateColumnDescription(model_name, column_property, verbose = false) { | ||
const query = this.getUpdateColumnDescriptionQuery(model_name, column_property); | ||
if (verbose) { | ||
@@ -291,2 +309,5 @@ console.log(` (${query})`); | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return ''; | ||
} | ||
const schema = model_class._schema; | ||
@@ -297,3 +318,3 @@ const table_name = model_class.table_name; | ||
const order = index.columns[column]; | ||
columns.push(`\`${(schema[column] && schema[column]._dbname_us) || column}\` ${order === -1 ? 'DESC' : 'ASC'}`); | ||
columns.push(`\`${schema[column]?._dbname_us || column}\` ${order === -1 ? 'DESC' : 'ASC'}`); | ||
} | ||
@@ -317,4 +338,7 @@ const unique = index.options.unique ? 'UNIQUE ' : ''; | ||
/** @internal */ | ||
getCreateForeignKeyQuery(model, column, type, references) { | ||
const model_class = this._connection.models[model]; | ||
getCreateForeignKeyQuery(model_name, column, type, references) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return ''; | ||
} | ||
const table_name = model_class.table_name; | ||
@@ -337,4 +361,4 @@ let action = ''; | ||
/** @internal */ | ||
async createForeignKey(model, column, type, references, verbose = false) { | ||
const query = this.getCreateForeignKeyQuery(model, column, type, references); | ||
async createForeignKey(model_name, column, type, references, verbose = false) { | ||
const query = this.getCreateForeignKeyQuery(model_name, column, type, references); | ||
if (verbose) { | ||
@@ -352,4 +376,8 @@ console.log(` (${query})`); | ||
async deleteAllIgnoringConstraint(model_list) { | ||
await Promise.all(model_list.map(async (model) => { | ||
const table_name = this._connection.models[model].table_name; | ||
await Promise.all(model_list.map(async (model_name) => { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const table_name = model_class.table_name; | ||
const connection = await this.getConnection(); | ||
@@ -373,4 +401,8 @@ try { | ||
/** @internal */ | ||
async drop(model) { | ||
const table_name = this._connection.models[model].table_name; | ||
async drop(model_name) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const table_name = model_class.table_name; | ||
try { | ||
@@ -388,6 +420,10 @@ await this._client.queryAsync(`DROP TABLE IF EXISTS \`${table_name}\``); | ||
/** @internal */ | ||
async create(model, data, options) { | ||
const table_name = this._connection.models[model].table_name; | ||
async create(model_name, data, options) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
throw new Error('model not found'); | ||
} | ||
const table_name = model_class.table_name; | ||
const values = []; | ||
const [fields, places] = this._buildUpdateSet(model, data, values, true); | ||
const [fields, places] = this._buildUpdateSet(model_name, data, values, true); | ||
const sql = `INSERT INTO \`${table_name}\` (${fields}) VALUES (${places})`; | ||
@@ -410,4 +446,8 @@ let result; | ||
/** @internal */ | ||
async createBulk(model, data, options) { | ||
const table_name = this._connection.models[model].table_name; | ||
async createBulk(model_name, data, options) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
throw new Error('model not found'); | ||
} | ||
const table_name = model_class.table_name; | ||
const values = []; | ||
@@ -418,3 +458,3 @@ let fields; | ||
let places_sub; | ||
[fields, places_sub] = this._buildUpdateSet(model, item, values, true); | ||
[fields, places_sub] = this._buildUpdateSet(model_name, item, values, true); | ||
places.push('(' + places_sub + ')'); | ||
@@ -439,6 +479,10 @@ }); | ||
/** @internal */ | ||
async update(model, data, options) { | ||
const table_name = this._connection.models[model].table_name; | ||
async update(model_name, data, options) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const table_name = model_class.table_name; | ||
const values = []; | ||
const [fields] = this._buildUpdateSet(model, data, values); | ||
const [fields] = this._buildUpdateSet(model_name, data, values); | ||
values.push(data.id); | ||
@@ -454,9 +498,13 @@ const sql = `UPDATE \`${table_name}\` SET ${fields} WHERE id=?`; | ||
/** @internal */ | ||
async updatePartial(model, data, conditions, options) { | ||
const table_name = this._connection.models[model].table_name; | ||
async updatePartial(model_name, data, conditions, options) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return 0; | ||
} | ||
const table_name = model_class.table_name; | ||
const values = []; | ||
const [fields] = this._buildPartialUpdateSet(model, data, values); | ||
const [fields] = this._buildPartialUpdateSet(model_name, data, values); | ||
let sql = `UPDATE \`${table_name}\` SET ${fields}`; | ||
if (conditions.length > 0) { | ||
sql += ' WHERE ' + this._buildWhere(this._connection.models[model]._schema, '', {}, conditions, values); | ||
sql += ' WHERE ' + this._buildWhere(model_class._schema, '', {}, conditions, values); | ||
} | ||
@@ -476,5 +524,8 @@ let result; | ||
/** @internal */ | ||
async upsert(model, data, conditions, options) { | ||
var _a; | ||
const table_name = this._connection.models[model].table_name; | ||
async upsert(model_name, data, conditions, options) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const table_name = model_class.table_name; | ||
const insert_data = {}; | ||
@@ -490,3 +541,3 @@ const update_data = {}; | ||
} | ||
if (!((_a = options.ignore_on_update) === null || _a === void 0 ? void 0 : _a.includes(key))) { | ||
if (!options.ignore_on_update?.includes(key)) { | ||
update_data[key] = value; | ||
@@ -506,9 +557,9 @@ } | ||
if (Object.keys(update_data).length === 0) { | ||
[fields, places] = this._buildUpdateSet(model, insert_data, values, true); | ||
[fields, places] = this._buildUpdateSet(model_name, insert_data, values, true); | ||
sql = `INSERT IGNORE \`${table_name}\` (${fields}) VALUES (${places})`; | ||
} | ||
else { | ||
[fields, places] = this._buildUpdateSet(model, insert_data, values, true); | ||
[fields, places] = this._buildUpdateSet(model_name, insert_data, values, true); | ||
sql = `INSERT INTO \`${table_name}\` (${fields}) VALUES (${places})`; | ||
[fields] = this._buildPartialUpdateSet(model, update_data, values); | ||
[fields] = this._buildPartialUpdateSet(model_name, update_data, values); | ||
sql += ` ON DUPLICATE KEY UPDATE ${fields}`; | ||
@@ -524,6 +575,10 @@ } | ||
/** @internal */ | ||
async findById(model, id, options) { | ||
async findById(model_name, id, options) { | ||
id = this._convertValueType(id, this.key_type); | ||
const select = this._buildSelect(this._connection.models[model], options.select); | ||
const table_name = this._connection.models[model].table_name; | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
throw new Error('model not found'); | ||
} | ||
const select = this._buildSelect(model_class, options.select); | ||
const table_name = model_class.table_name; | ||
const sql = `SELECT ${select} FROM \`${table_name}\` AS _Base WHERE id=? LIMIT 1`; | ||
@@ -541,3 +596,3 @@ if (options.explain) { | ||
if (result && result.length === 1) { | ||
return this._convertToModelInstance(model, result[0], options); | ||
return this._convertToModelInstance(model_name, result[0], options); | ||
} | ||
@@ -552,4 +607,4 @@ else if (result && result.length > 1) { | ||
/** @internal */ | ||
async find(model, conditions, options) { | ||
const [sql, params] = this._buildSqlForFind(model, conditions, options); | ||
async find(model_name, conditions, options) { | ||
const [sql, params] = this._buildSqlForFind(model_name, conditions, options); | ||
if (options.explain) { | ||
@@ -567,3 +622,3 @@ return await this.query(`EXPLAIN ${sql}`, params, { transaction: options.transaction, node: options.node }); | ||
return result.map((record) => { | ||
return this._convertToGroupInstance(model, record, options.group_by, options.group_fields); | ||
return this._convertToGroupInstance(model_name, record, options.group_by, options.group_fields); | ||
}); | ||
@@ -573,3 +628,3 @@ } | ||
return result.map((record) => { | ||
return this._convertToModelInstance(model, record, options); | ||
return this._convertToModelInstance(model_name, record, options); | ||
}); | ||
@@ -579,7 +634,7 @@ } | ||
/** @internal */ | ||
stream(model, conditions, options) { | ||
stream(model_name, conditions, options) { | ||
let sql; | ||
let params; | ||
try { | ||
[sql, params] = this._buildSqlForFind(model, conditions, options); | ||
[sql, params] = this._buildSqlForFind(model_name, conditions, options); | ||
} | ||
@@ -593,3 +648,3 @@ catch (error) { | ||
transformer._transform = (record, encoding, callback) => { | ||
transformer.push(this._convertToModelInstance(model, record, options)); | ||
transformer.push(this._convertToModelInstance(model_name, record, options)); | ||
callback(); | ||
@@ -610,2 +665,5 @@ }; | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return 0; | ||
} | ||
const select = options.select ? this._buildSelect(model_class, options.select) : '*'; | ||
@@ -624,5 +682,9 @@ const params = []; | ||
for (const join of options.joins) { | ||
sql += ` ${join.type} ${this._connection.models[join.model_name].table_name} AS _${join.alias}`; | ||
const join_model_class = this._connection.models[join.model_name]; | ||
if (!join_model_class) { | ||
continue; | ||
} | ||
sql += ` ${join.type} ${join_model_class.table_name} AS _${join.alias}`; | ||
sql += ` ON _Base.${escape_ch}${join.base_column}${escape_ch} = _${join.alias}.${escape_ch}${join.join_column}${escape_ch}`; | ||
join_schemas[join.alias] = this._connection.models[join.model_name]._schema; | ||
join_schemas[join.alias] = join_model_class._schema; | ||
} | ||
@@ -659,2 +721,5 @@ } | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return 0; | ||
} | ||
const params = []; | ||
@@ -666,3 +731,3 @@ const table_name = model_class.table_name; | ||
} | ||
if (options && options.orders.length > 0) { | ||
if (options.orders.length > 0) { | ||
const schema = model_class._schema; | ||
@@ -679,3 +744,3 @@ const orders = options.orders.map((order) => { | ||
} | ||
column = (schema[column] && schema[column]._dbname_us) || column; | ||
column = schema[column]?._dbname_us || column; | ||
return `\`${column}\` ${order}`; | ||
@@ -685,9 +750,9 @@ }); | ||
} | ||
if (options && options.limit) { | ||
if (options.limit) { | ||
sql += ' LIMIT ' + options.limit; | ||
if (options && options.skip) { | ||
if (options.skip) { | ||
sql += ' OFFSET ' + options.skip; | ||
} | ||
} | ||
else if (options && options.skip) { | ||
else if (options.skip) { | ||
sql += ' LIMIT 2147483647 OFFSET ' + options.skip; | ||
@@ -831,3 +896,2 @@ } | ||
async query(text, values, options) { | ||
var _a; | ||
if (!this._client) { | ||
@@ -859,3 +923,3 @@ await this._connection._promise_connection; | ||
catch (error) { | ||
if (((_a = this._settings) === null || _a === void 0 ? void 0 : _a.reconnect_if_read_only) && error.message.includes('read-only')) { | ||
if (this._settings?.reconnect_if_read_only && error.message.includes('read-only')) { | ||
// if failover occurred, connections will be reconnected. | ||
@@ -940,3 +1004,3 @@ // But if connection is reconnected before DNS is changed (DNS cache can affect this), | ||
let column = sub_expr.substr(1); | ||
column = (schema[column] && schema[column]._dbname_us) || column; | ||
column = schema[column]?._dbname_us || column; | ||
return `ANY_VALUE(${column})`; | ||
@@ -1048,4 +1112,8 @@ } | ||
/** @internal */ | ||
_buildUpdateSet(model, data, values, insert = false) { | ||
const schema = this._connection.models[model]._schema; | ||
_buildUpdateSet(model_name, data, values, insert = false) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return ['', '']; | ||
} | ||
const schema = model_class._schema; | ||
const fields = []; | ||
@@ -1055,3 +1123,3 @@ const places = []; | ||
const property = schema[column]; | ||
if (property.primary_key) { | ||
if (property?.primary_key) { | ||
continue; | ||
@@ -1064,9 +1132,12 @@ } | ||
/** @internal */ | ||
_buildPartialUpdateSet(model, data, values) { | ||
const schema = this._connection.models[model]._schema; | ||
_buildPartialUpdateSet(model_name, data, values) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return ['', '']; | ||
} | ||
const schema = model_class._schema; | ||
const fields = []; | ||
const places = []; | ||
for (const column in data) { | ||
const value = data[column]; | ||
const property = lodash_1.default.find(schema, (item) => item._dbname_us === column); | ||
const property = lodash_1.default.find(schema, (item) => item?._dbname_us === column); | ||
if (!property || property.primary_key) { | ||
@@ -1082,2 +1153,5 @@ continue; | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return ['', []]; | ||
} | ||
let select; | ||
@@ -1107,5 +1181,9 @@ if (options.group_by || options.group_fields) { | ||
for (const join of options.joins) { | ||
sql += ` ${join.type} ${this._connection.models[join.model_name].table_name} AS _${join.alias}`; | ||
const join_model_class = this._connection.models[join.model_name]; | ||
if (!join_model_class) { | ||
continue; | ||
} | ||
sql += ` ${join.type} ${join_model_class.table_name} AS _${join.alias}`; | ||
sql += ` ON _Base.${escape_ch}${join.base_column}${escape_ch} = _${join.alias}.${escape_ch}${join.join_column}${escape_ch}`; | ||
join_schemas[join.alias] = this._connection.models[join.model_name]._schema; | ||
join_schemas[join.alias] = join_model_class._schema; | ||
} | ||
@@ -1123,3 +1201,3 @@ } | ||
} | ||
if ((options && options.orders.length > 0) || order_by) { | ||
if (options.orders.length > 0 || order_by) { | ||
const schema = model_class._schema; | ||
@@ -1136,3 +1214,3 @@ const orders = options.orders.map((order) => { | ||
} | ||
column = (schema[column] && schema[column]._dbname_us) || column; | ||
column = schema[column]?._dbname_us || column; | ||
return `\`${column}\` ${order}`; | ||
@@ -1145,9 +1223,9 @@ }); | ||
} | ||
if (options && options.limit) { | ||
if (options.limit) { | ||
sql += ' LIMIT ' + options.limit; | ||
if (options && options.skip) { | ||
if (options.skip) { | ||
sql += ' OFFSET ' + options.skip; | ||
} | ||
} | ||
else if (options && options.skip) { | ||
else if (options.skip) { | ||
sql += ' LIMIT 2147483647 OFFSET ' + options.skip; | ||
@@ -1230,4 +1308,3 @@ } | ||
_wrapError(msg, cause) { | ||
var _a; | ||
if (!((_a = this._settings) === null || _a === void 0 ? void 0 : _a.hide_unknown_error) && msg === 'unknown error' && cause) { | ||
if (!this._settings?.hide_unknown_error && msg === 'unknown error' && cause) { | ||
return cause; | ||
@@ -1234,0 +1311,0 @@ } |
@@ -5,3 +5,7 @@ "use strict"; | ||
if (k2 === undefined) k2 = k; | ||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
@@ -150,4 +154,7 @@ if (k2 === undefined) k2 = k; | ||
/** @internal */ | ||
async createTable(model) { | ||
const model_class = this._connection.models[model]; | ||
async createTable(model_name) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const table_name = model_class.table_name; | ||
@@ -157,2 +164,5 @@ const column_sqls = []; | ||
const property = model_class._schema[column]; | ||
if (!property) { | ||
continue; | ||
} | ||
if (property.primary_key) { | ||
@@ -177,4 +187,7 @@ column_sqls.push(`"${property._dbname_us}" SERIAL PRIMARY KEY`); | ||
/** @internal */ | ||
async addColumn(model, column_property) { | ||
const model_class = this._connection.models[model]; | ||
async addColumn(model_name, column_property) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const table_name = model_class.table_name; | ||
@@ -193,2 +206,5 @@ const column_name = column_property._dbname_us; | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const schema = model_class._schema; | ||
@@ -199,3 +215,3 @@ const table_name = model_class.table_name; | ||
const order = index.columns[column]; | ||
columns.push(`"${(schema[column] && schema[column]._dbname_us) || column}" ${order === -1 ? 'DESC' : 'ASC'}`); | ||
columns.push(`"${schema[column]?._dbname_us || column}" ${order === -1 ? 'DESC' : 'ASC'}`); | ||
} | ||
@@ -212,4 +228,7 @@ const unique = index.options.unique ? 'UNIQUE ' : ''; | ||
/** @internal */ | ||
async createForeignKey(model, column, type, references) { | ||
const model_class = this._connection.models[model]; | ||
async createForeignKey(model_name, column, type, references) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const table_name = model_class.table_name; | ||
@@ -239,4 +258,8 @@ let action = ''; | ||
async deleteAllIgnoringConstraint(model_list) { | ||
await Promise.all(model_list.map(async (model) => { | ||
const table_name = this._connection.models[model].table_name; | ||
await Promise.all(model_list.map(async (model_name) => { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const table_name = model_class.table_name; | ||
await this.query(`ALTER TABLE "${table_name}" DISABLE TRIGGER ALL`); | ||
@@ -248,4 +271,8 @@ await this.query(`DELETE FROM "${table_name}"`); | ||
/** @internal */ | ||
async drop(model) { | ||
const table_name = this._connection.models[model].table_name; | ||
async drop(model_name) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const table_name = model_class.table_name; | ||
try { | ||
@@ -263,6 +290,10 @@ await this._pool.query(`DROP TABLE IF EXISTS "${table_name}"`); | ||
/** @internal */ | ||
async create(model, data, options) { | ||
const table_name = this._connection.models[model].table_name; | ||
async create(model_name, data, options) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
throw new Error('model not found'); | ||
} | ||
const table_name = model_class.table_name; | ||
const values = []; | ||
const [fields, places] = this._buildUpdateSet(model, data, values, true); | ||
const [fields, places] = this._buildUpdateSet(model_name, data, values, true); | ||
const sql = `INSERT INTO "${table_name}" (${fields}) VALUES (${places}) RETURNING id`; | ||
@@ -285,4 +316,8 @@ let result; | ||
/** @internal */ | ||
async createBulk(model, data, options) { | ||
const table_name = this._connection.models[model].table_name; | ||
async createBulk(model_name, data, options) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
throw new Error('model not found'); | ||
} | ||
const table_name = model_class.table_name; | ||
const values = []; | ||
@@ -293,3 +328,3 @@ let fields; | ||
let places_sub; | ||
[fields, places_sub] = this._buildUpdateSet(model, item, values, true); | ||
[fields, places_sub] = this._buildUpdateSet(model_name, item, values, true); | ||
places.push('(' + places_sub + ')'); | ||
@@ -314,6 +349,10 @@ }); | ||
/** @internal */ | ||
async update(model, data, options) { | ||
const table_name = this._connection.models[model].table_name; | ||
async update(model_name, data, options) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const table_name = model_class.table_name; | ||
const values = []; | ||
const [fields] = this._buildUpdateSet(model, data, values); | ||
const [fields] = this._buildUpdateSet(model_name, data, values); | ||
values.push(data.id); | ||
@@ -329,9 +368,13 @@ const sql = `UPDATE "${table_name}" SET ${fields} WHERE id=$${values.length}`; | ||
/** @internal */ | ||
async updatePartial(model, data, conditions, options) { | ||
const table_name = this._connection.models[model].table_name; | ||
async updatePartial(model_name, data, conditions, options) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return 0; | ||
} | ||
const table_name = model_class.table_name; | ||
const values = []; | ||
const [fields] = this._buildPartialUpdateSet(model, data, values); | ||
const [fields] = this._buildPartialUpdateSet(model_name, data, values); | ||
let sql = `UPDATE "${table_name}" SET ${fields}`; | ||
if (conditions.length > 0) { | ||
sql += ' WHERE ' + this._buildWhere(this._connection.models[model]._schema, '', {}, conditions, values); | ||
sql += ' WHERE ' + this._buildWhere(model_class._schema, '', {}, conditions, values); | ||
} | ||
@@ -348,5 +391,9 @@ let result; | ||
/** @internal */ | ||
async findById(model, id, options) { | ||
const select = this._buildSelect(this._connection.models[model], options.select); | ||
const table_name = this._connection.models[model].table_name; | ||
async findById(model_name, id, options) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
throw new Error('model not found'); | ||
} | ||
const select = this._buildSelect(model_class, options.select); | ||
const table_name = model_class.table_name; | ||
const sql = `SELECT ${select} FROM "${table_name}" AS _Base WHERE id=$1 LIMIT 1`; | ||
@@ -365,3 +412,3 @@ if (options.explain) { | ||
if (rows && rows.length === 1) { | ||
return this._convertToModelInstance(model, rows[0], options); | ||
return this._convertToModelInstance(model_name, rows[0], options); | ||
} | ||
@@ -376,4 +423,4 @@ else if (rows && rows.length > 1) { | ||
/** @internal */ | ||
async find(model, conditions, options) { | ||
const [sql, params] = this._buildSqlForFind(model, conditions, options); | ||
async find(model_name, conditions, options) { | ||
const [sql, params] = this._buildSqlForFind(model_name, conditions, options); | ||
if (options.explain) { | ||
@@ -392,3 +439,3 @@ return await this.query(`EXPLAIN ${sql}`, params, options.transaction); | ||
return rows.map((record) => { | ||
return this._convertToGroupInstance(model, record, options.group_by, options.group_fields); | ||
return this._convertToGroupInstance(model_name, record, options.group_by, options.group_fields); | ||
}); | ||
@@ -398,3 +445,3 @@ } | ||
return rows.map((record) => { | ||
return this._convertToModelInstance(model, record, options); | ||
return this._convertToModelInstance(model_name, record, options); | ||
}); | ||
@@ -404,3 +451,3 @@ } | ||
/** @internal */ | ||
stream(model, conditions, options) { | ||
stream(model_name, conditions, options) { | ||
if (!QueryStream) { | ||
@@ -413,3 +460,3 @@ console.log('Install pg-query-stream module to use stream'); | ||
try { | ||
[sql, params] = this._buildSqlForFind(model, conditions, options); | ||
[sql, params] = this._buildSqlForFind(model_name, conditions, options); | ||
} | ||
@@ -423,3 +470,3 @@ catch (error) { | ||
transformer._transform = (record, encoding, callback) => { | ||
transformer.push(this._convertToModelInstance(model, record, options)); | ||
transformer.push(this._convertToModelInstance(model_name, record, options)); | ||
callback(); | ||
@@ -443,2 +490,5 @@ }; | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return 0; | ||
} | ||
const select = options.select ? this._buildSelect(model_class, options.select) : '*'; | ||
@@ -454,5 +504,9 @@ const params = []; | ||
for (const join of options.joins) { | ||
sql += ` ${join.type} ${this._connection.models[join.model_name].table_name} AS _${join.alias}`; | ||
const join_model_class = this._connection.models[join.model_name]; | ||
if (!join_model_class) { | ||
continue; | ||
} | ||
sql += ` ${join.type} ${join_model_class.table_name} AS _${join.alias}`; | ||
sql += ` ON _Base.${escape_ch}${join.base_column}${escape_ch} = _${join.alias}.${escape_ch}${join.join_column}${escape_ch}`; | ||
join_schemas[join.alias] = this._connection.models[join.model_name]._schema; | ||
join_schemas[join.alias] = join_model_class._schema; | ||
} | ||
@@ -490,3 +544,6 @@ } | ||
const model_class = this._connection.models[model_name]; | ||
const nested = options && (options.orders.length > 0 || options.limit || options.skip); | ||
if (!model_class) { | ||
return 0; | ||
} | ||
const nested = options.orders.length > 0 || options.limit || options.skip; | ||
const params = []; | ||
@@ -501,3 +558,3 @@ const table_name = model_class.table_name; | ||
} | ||
if (options && options.orders.length > 0) { | ||
if (options.orders.length > 0) { | ||
const schema = model_class._schema; | ||
@@ -514,3 +571,3 @@ const orders = options.orders.map((order) => { | ||
} | ||
column = (schema[column] && schema[column]._dbname_us) || column; | ||
column = schema[column]?._dbname_us || column; | ||
return `"${column}" ${order}`; | ||
@@ -520,9 +577,9 @@ }); | ||
} | ||
if (options && options.limit) { | ||
if (options.limit) { | ||
sql += ' LIMIT ' + options.limit; | ||
if (options && options.skip) { | ||
if (options.skip) { | ||
sql += ' OFFSET ' + options.skip; | ||
} | ||
} | ||
else if (options && options.skip) { | ||
else if (options.skip) { | ||
sql += ' LIMIT ALL OFFSET ' + options.skip; | ||
@@ -664,3 +721,3 @@ } | ||
let column = sub_expr.substr(1); | ||
column = (schema[column] && schema[column]._dbname_us) || column; | ||
column = schema[column]?._dbname_us || column; | ||
return `(ARRAY_AGG(${column}))[1]`; | ||
@@ -786,4 +843,8 @@ } | ||
/** @internal */ | ||
_buildUpdateSet(model, data, values, insert = false) { | ||
const schema = this._connection.models[model]._schema; | ||
_buildUpdateSet(model_name, data, values, insert = false) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return ['', '']; | ||
} | ||
const schema = model_class._schema; | ||
const fields = []; | ||
@@ -793,3 +854,3 @@ const places = []; | ||
const property = schema[column]; | ||
if (property.primary_key) { | ||
if (property?.primary_key) { | ||
continue; | ||
@@ -802,9 +863,12 @@ } | ||
/** @internal */ | ||
_buildPartialUpdateSet(model, data, values) { | ||
const schema = this._connection.models[model]._schema; | ||
_buildPartialUpdateSet(model_name, data, values) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return ['', '']; | ||
} | ||
const schema = model_class._schema; | ||
const fields = []; | ||
const places = []; | ||
for (const column in data) { | ||
const value = data[column]; | ||
const property = lodash_1.default.find(schema, (item) => item._dbname_us === column); | ||
const property = lodash_1.default.find(schema, (item) => item?._dbname_us === column); | ||
if (!property || property.primary_key) { | ||
@@ -820,2 +884,5 @@ continue; | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return ['', []]; | ||
} | ||
let select; | ||
@@ -842,5 +909,9 @@ if (options.group_by || options.group_fields) { | ||
for (const join of options.joins) { | ||
sql += ` ${join.type} ${this._connection.models[join.model_name].table_name} AS _${join.alias}`; | ||
const join_model_class = this._connection.models[join.model_name]; | ||
if (!join_model_class) { | ||
continue; | ||
} | ||
sql += ` ${join.type} ${join_model_class.table_name} AS _${join.alias}`; | ||
sql += ` ON _Base.${escape_ch}${join.base_column}${escape_ch} = _${join.alias}.${escape_ch}${join.join_column}${escape_ch}`; | ||
join_schemas[join.alias] = this._connection.models[join.model_name]._schema; | ||
join_schemas[join.alias] = join_model_class._schema; | ||
} | ||
@@ -858,3 +929,3 @@ } | ||
} | ||
if ((options && options.orders.length > 0) || order_by) { | ||
if (options.orders.length > 0 || order_by) { | ||
const schema = model_class._schema; | ||
@@ -871,3 +942,3 @@ const orders = options.orders.map((order) => { | ||
} | ||
column = (schema[column] && schema[column]._dbname_us) || column; | ||
column = schema[column]?._dbname_us || column; | ||
return `"${column}" ${order}`; | ||
@@ -880,9 +951,9 @@ }); | ||
} | ||
if (options && options.limit) { | ||
if (options.limit) { | ||
sql += ' LIMIT ' + options.limit; | ||
if (options && options.skip) { | ||
if (options.skip) { | ||
sql += ' OFFSET ' + options.skip; | ||
} | ||
} | ||
else if (options && options.skip) { | ||
else if (options.skip) { | ||
sql += ' LIMIT ALL OFFSET ' + options.skip; | ||
@@ -889,0 +960,0 @@ } |
"use strict"; | ||
/* eslint-disable @typescript-eslint/no-unused-vars */ | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
@@ -28,3 +33,3 @@ if (k2 === undefined) k2 = k; | ||
try { | ||
redis = require('redis'); | ||
redis = require('ioredis'); | ||
} | ||
@@ -34,3 +39,2 @@ catch (error) { | ||
} | ||
const util_1 = __importDefault(require("util")); | ||
const lodash_1 = __importDefault(require("lodash")); | ||
@@ -54,4 +58,4 @@ const types = __importStar(require("../types")); | ||
/** @internal */ | ||
async drop(model) { | ||
await this.delete(model, [], { orders: [] }); | ||
async drop(model_name) { | ||
await this.delete(model_name, [], { orders: [] }); | ||
} | ||
@@ -84,7 +88,7 @@ /** @internal */ | ||
/** @internal */ | ||
async create(model, data, options) { | ||
async create(model_name, data, options) { | ||
data.$_$ = ''; // ensure that there is one argument(one field) at least | ||
let id; | ||
try { | ||
id = await this._client.incrAsync(`${(0, inflector_1.tableize)(model)}:_lastid`); | ||
id = await this._client.incr(`${(0, inflector_1.tableize)(model_name)}:_lastid`); | ||
} | ||
@@ -95,3 +99,3 @@ catch (error) { | ||
try { | ||
await this._client.hmsetAsync(`${(0, inflector_1.tableize)(model)}:${id}`, data); | ||
await this._client.hmset(`${(0, inflector_1.tableize)(model_name)}:${id}`, data); | ||
} | ||
@@ -104,8 +108,8 @@ catch (error) { | ||
/** @internal */ | ||
async createBulk(model, data, options) { | ||
return await this._createBulkDefault(model, data, options); | ||
async createBulk(model_name, data, options) { | ||
return await this._createBulkDefault(model_name, data, options); | ||
} | ||
/** @internal */ | ||
async update(model, data, options) { | ||
const key = `${(0, inflector_1.tableize)(model)}:${data.id}`; | ||
async update(model_name, data, options) { | ||
const key = `${(0, inflector_1.tableize)(model_name)}:${data.id}`; | ||
delete data.id; | ||
@@ -115,3 +119,3 @@ data.$_$ = ''; // ensure that there is one argument(one field) at least | ||
try { | ||
exists = await this._client.existsAsync(key); | ||
exists = await this._client.exists(key); | ||
} | ||
@@ -125,3 +129,3 @@ catch (error) { | ||
try { | ||
await this._client.delAsync(key); | ||
await this._client.del(key); | ||
} | ||
@@ -132,3 +136,3 @@ catch (error) { | ||
try { | ||
await this._client.hmsetAsync(key, data); | ||
await this._client.hmset(key, data); | ||
} | ||
@@ -140,3 +144,3 @@ catch (error) { | ||
/** @internal */ | ||
async updatePartial(model, data, conditions, options) { | ||
async updatePartial(model_name, data, conditions, options) { | ||
const fields_to_del = Object.keys(data).filter((key) => data[key] == null); | ||
@@ -147,3 +151,3 @@ fields_to_del.forEach((key) => { | ||
fields_to_del.push('$_$'); // ensure that there is one argument at least | ||
const table = (0, inflector_1.tableize)(model); | ||
const table = (0, inflector_1.tableize)(model_name); | ||
data.$_$ = ''; // ensure that there is one argument(one field) at least | ||
@@ -155,3 +159,3 @@ const keys = await this._getKeys(table, conditions); | ||
try { | ||
await this._client.hdelAsync(args); | ||
await this._client.hdel(args); | ||
} | ||
@@ -162,3 +166,3 @@ catch (error) { | ||
try { | ||
await this._client.hmsetAsync(key, data); | ||
await this._client.hmset(key, data); | ||
} | ||
@@ -172,10 +176,13 @@ catch (error) { | ||
/** @internal */ | ||
async upsert(model, data, conditions, options) { | ||
async upsert(model_name, data, conditions, options) { | ||
return Promise.reject(new Error('not implemented')); | ||
} | ||
/** @internal */ | ||
async findById(model, id, options) { | ||
async findById(model_name, id, options) { | ||
let result; | ||
try { | ||
result = await this._client.hgetallAsync(`${(0, inflector_1.tableize)(model)}:${id}`); | ||
const key = `${(0, inflector_1.tableize)(model_name)}:${id}`; | ||
if (await this._client.exists(key)) { | ||
result = await this._client.hgetall(key); | ||
} | ||
} | ||
@@ -187,3 +194,3 @@ catch (error) { | ||
result.id = id; | ||
return this._convertToModelInstance(model, result, options); | ||
return this._convertToModelInstance(model_name, result, options); | ||
} | ||
@@ -195,7 +202,7 @@ else { | ||
/** @internal */ | ||
async find(model, conditions, options) { | ||
const table = (0, inflector_1.tableize)(model); | ||
async find(model_name, conditions, options) { | ||
const table = (0, inflector_1.tableize)(model_name); | ||
const keys = await this._getKeys(table, conditions); | ||
let records = await Promise.all(keys.map(async (key) => { | ||
const result = await this._client.hgetallAsync(key); | ||
const result = (await this._client.exists(key)) ? await this._client.hgetall(key) : undefined; | ||
if (result) { | ||
@@ -208,16 +215,16 @@ result.id = Number(key.substr(table.length + 1)); | ||
return records.map((record) => { | ||
return this._convertToModelInstance(model, record, options); | ||
return this._convertToModelInstance(model_name, record, options); | ||
}); | ||
} | ||
/** @internal */ | ||
stream(model, conditions, options) { | ||
stream(model_name, conditions, options) { | ||
throw new Error('not implemented'); | ||
} | ||
/** @internal */ | ||
async count(model, conditions, options) { | ||
async count(model_name, conditions, options) { | ||
return Promise.reject(new Error('not implemented')); | ||
} | ||
/** @internal */ | ||
async delete(model, conditions, options) { | ||
const keys = await this._getKeys((0, inflector_1.tableize)(model), conditions); | ||
async delete(model_name, conditions, options) { | ||
const keys = await this._getKeys((0, inflector_1.tableize)(model_name), conditions); | ||
if (keys.length === 0) { | ||
@@ -228,3 +235,3 @@ return 0; | ||
try { | ||
count = await this._client.delAsync(keys); | ||
count = await this._client.del(keys); | ||
} | ||
@@ -247,6 +254,3 @@ catch (error) { | ||
this._client = redis.createClient(settings.port || 6379, settings.host || '127.0.0.1'); | ||
for (const method of methods) { | ||
this._client[method + 'Async'] = util_1.default.promisify(this._client[method]); | ||
} | ||
return await this._client.selectAsync(settings.database || 0); | ||
return await this._client.select(settings.database || 0); | ||
} | ||
@@ -273,3 +277,3 @@ /** @internal */ | ||
if (conditions.length === 0) { | ||
return await this._client.keysAsync(`${table}:*`); | ||
return await this._client.keys(`${table}:*`); | ||
} | ||
@@ -276,0 +280,0 @@ const all_keys = []; |
@@ -5,3 +5,7 @@ "use strict"; | ||
if (k2 === undefined) k2 = k; | ||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
@@ -48,4 +52,3 @@ if (k2 === undefined) k2 = k; | ||
/** @internal */ | ||
async upsert(model, data, conditions, options) { | ||
var _a; | ||
async upsert(model_name, data, conditions, options) { | ||
const insert_data = {}; | ||
@@ -61,3 +64,3 @@ const update_data = {}; | ||
} | ||
if (!((_a = options.ignore_on_update) === null || _a === void 0 ? void 0 : _a.includes(key))) { | ||
if (!options.ignore_on_update?.includes(key)) { | ||
update_data[key] = value; | ||
@@ -74,3 +77,3 @@ } | ||
try { | ||
return await this.create(model, insert_data, {}); | ||
return await this.create(model_name, insert_data, {}); | ||
} | ||
@@ -84,3 +87,3 @@ catch (error) { | ||
else { | ||
const count = await this.updatePartial(model, update_data, conditions, options); | ||
const count = await this.updatePartial(model_name, update_data, conditions, options); | ||
if (count > 0) { | ||
@@ -90,3 +93,3 @@ return; | ||
try { | ||
return await this.create(model, insert_data, {}); | ||
return await this.create(model_name, insert_data, {}); | ||
} | ||
@@ -97,3 +100,3 @@ catch (error) { | ||
} | ||
return await this.updatePartial(model, update_data, conditions, options); | ||
return await this.updatePartial(model_name, update_data, conditions, options); | ||
} | ||
@@ -103,3 +106,3 @@ } | ||
/** @internal */ | ||
_param_place_holder(pos) { | ||
_param_place_holder(_pos) { | ||
return '?'; | ||
@@ -213,3 +216,3 @@ } | ||
let compare_column = sub_expr.substr(1); | ||
compare_column = (schema[compare_column] && schema[compare_column]._dbname_us) || compare_column; | ||
compare_column = schema[compare_column]?._dbname_us || compare_column; | ||
op = | ||
@@ -278,7 +281,7 @@ sub_key === '$cgt' | ||
const model = key.split('.', 1)[0]; | ||
if (join_schemas[model]) { | ||
const join_model_class = join_schemas[model]; | ||
if (join_model_class) { | ||
// if key is 'JoinModel.column' | ||
const model_class = join_schemas[model]; | ||
const property = model_class[key.substring(model.length + 1)]; | ||
return this._buildWhereSingle(model_class, property, key, `_${model}.`, value, params); | ||
const property = join_model_class[key.substring(model.length + 1)]; | ||
return this._buildWhereSingle(join_model_class, property, key, `_${model}.`, value, params); | ||
} | ||
@@ -344,3 +347,3 @@ return this._buildWhereSingle(schema, schema[key], key, base_alias ? base_alias + '.' : '', value, params); | ||
let column = sub_expr.substr(1); | ||
column = (schema[column] && schema[column]._dbname_us) || column; | ||
column = schema[column]?._dbname_us || column; | ||
return `SUM(${this._escape_ch}${column}${this._escape_ch})`; | ||
@@ -356,3 +359,3 @@ } | ||
let column = sub_expr.substr(1); | ||
column = (schema[column] && schema[column]._dbname_us) || column; | ||
column = schema[column]?._dbname_us || column; | ||
return `MIN(${this._escape_ch}${column}${this._escape_ch})`; | ||
@@ -368,3 +371,3 @@ } | ||
let column = sub_expr.substr(1); | ||
column = (schema[column] && schema[column]._dbname_us) || column; | ||
column = schema[column]?._dbname_us || column; | ||
return `MAX(${this._escape_ch}${column}${this._escape_ch})`; | ||
@@ -380,3 +383,3 @@ } | ||
let column = sub_expr.substr(1); | ||
column = (schema[column] && schema[column]._dbname_us) || column; | ||
column = schema[column]?._dbname_us || column; | ||
return `AVG(${this._escape_ch}${column}${this._escape_ch})`; | ||
@@ -392,3 +395,3 @@ } | ||
let column = sub_expr.substr(1); | ||
column = (schema[column] && schema[column]._dbname_us) || column; | ||
column = schema[column]?._dbname_us || column; | ||
return `${this._escape_ch}${column}${this._escape_ch}`; | ||
@@ -424,3 +427,3 @@ } | ||
const escape_ch = this._escape_ch; | ||
select = select.map((column) => `_Base.${escape_ch}${schema[column]._dbname_us}${escape_ch}`); | ||
select = select.map((column) => `_Base.${escape_ch}${schema[column]?._dbname_us}${escape_ch}`); | ||
return select.join(','); | ||
@@ -427,0 +430,0 @@ } |
@@ -5,3 +5,7 @@ "use strict"; | ||
if (k2 === undefined) k2 = k; | ||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
@@ -128,4 +132,7 @@ if (k2 === undefined) k2 = k; | ||
/** @internal */ | ||
async createTable(model) { | ||
const model_class = this._connection.models[model]; | ||
async createTable(model_name) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const table_name = model_class.table_name; | ||
@@ -135,2 +142,5 @@ const column_sqls = []; | ||
const property = model_class._schema[column]; | ||
if (!property) { | ||
continue; | ||
} | ||
if (property.primary_key) { | ||
@@ -167,4 +177,7 @@ column_sqls.push(`"${property._dbname_us}" INTEGER PRIMARY KEY AUTOINCREMENT`); | ||
/** @internal */ | ||
async addColumn(model, column_property) { | ||
const model_class = this._connection.models[model]; | ||
async addColumn(model_name, column_property) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const table_name = model_class.table_name; | ||
@@ -183,2 +196,5 @@ const column_name = column_property._dbname_us; | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const schema = model_class._schema; | ||
@@ -189,3 +205,3 @@ const table_name = model_class.table_name; | ||
const order = index.columns[column]; | ||
columns.push(`"${(schema[column] && schema[column]._dbname_us) || column}" ${order === -1 ? 'DESC' : 'ASC'}`); | ||
columns.push(`"${schema[column]?._dbname_us || column}" ${order === -1 ? 'DESC' : 'ASC'}`); | ||
} | ||
@@ -204,4 +220,8 @@ const unique = index.options.unique ? 'UNIQUE ' : ''; | ||
await this._client.runAsync('PRAGMA foreign_keys=OFF'); | ||
await Promise.all(model_list.map(async (model) => { | ||
const table_name = this._connection.models[model].table_name; | ||
await Promise.all(model_list.map(async (model_name) => { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const table_name = model_class.table_name; | ||
await this._client.runAsync(`DELETE FROM \`${table_name}\``); | ||
@@ -212,4 +232,8 @@ })); | ||
/** @internal */ | ||
async drop(model) { | ||
const table_name = this._connection.models[model].table_name; | ||
async drop(model_name) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const table_name = model_class.table_name; | ||
try { | ||
@@ -227,6 +251,10 @@ await this._client.runAsync(`DROP TABLE IF EXISTS "${table_name}"`); | ||
/** @internal */ | ||
async create(model, data, options) { | ||
const table_name = this._connection.models[model].table_name; | ||
async create(model_name, data, options) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const table_name = model_class.table_name; | ||
const values = []; | ||
const [fields, places] = this._buildUpdateSet(model, data, values, true); | ||
const [fields, places] = this._buildUpdateSet(model_name, data, values, true); | ||
const sql = `INSERT INTO "${table_name}" (${fields}) VALUES (${places})`; | ||
@@ -267,4 +295,8 @@ let id; | ||
/** @internal */ | ||
async createBulk(model, data, options) { | ||
const table_name = this._connection.models[model].table_name; | ||
async createBulk(model_name, data, _options) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
throw new Error('model not found'); | ||
} | ||
const table_name = model_class.table_name; | ||
const values = []; | ||
@@ -275,3 +307,3 @@ let fields; | ||
let places_sub; | ||
[fields, places_sub] = this._buildUpdateSet(model, item, values, true); | ||
[fields, places_sub] = this._buildUpdateSet(model_name, item, values, true); | ||
return places.push('(' + places_sub + ')'); | ||
@@ -305,6 +337,10 @@ }); | ||
/** @internal */ | ||
async update(model, data, options) { | ||
const table_name = this._connection.models[model].table_name; | ||
async update(model_name, data, _options) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const table_name = model_class.table_name; | ||
const values = []; | ||
const [fields] = this._buildUpdateSet(model, data, values); | ||
const [fields] = this._buildUpdateSet(model_name, data, values); | ||
values.push(data.id); | ||
@@ -320,9 +356,13 @@ const sql = `UPDATE "${table_name}" SET ${fields} WHERE id=?`; | ||
/** @internal */ | ||
async updatePartial(model, data, conditions, options) { | ||
const table_name = this._connection.models[model].table_name; | ||
async updatePartial(model_name, data, conditions, _options) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return 0; | ||
} | ||
const table_name = model_class.table_name; | ||
const values = []; | ||
const [fields] = this._buildPartialUpdateSet(model, data, values); | ||
const [fields] = this._buildPartialUpdateSet(model_name, data, values); | ||
let sql = `UPDATE "${table_name}" SET ${fields}`; | ||
if (conditions.length > 0) { | ||
sql += ' WHERE ' + this._buildWhere(this._connection.models[model]._schema, '', {}, conditions, values); | ||
sql += ' WHERE ' + this._buildWhere(model_class._schema, '', {}, conditions, values); | ||
} | ||
@@ -346,5 +386,9 @@ try { | ||
/** @internal */ | ||
async findById(model, id, options) { | ||
const select = this._buildSelect(this._connection.models[model], options.select); | ||
const table_name = this._connection.models[model].table_name; | ||
async findById(model_name, id, options) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
throw new Error('model not found'); | ||
} | ||
const select = this._buildSelect(model_class, options.select); | ||
const table_name = model_class.table_name; | ||
const sql = `SELECT ${select} FROM "${table_name}" AS _Base WHERE id=? LIMIT 1`; | ||
@@ -362,3 +406,3 @@ if (options.explain) { | ||
if (result && result.length === 1) { | ||
return this._convertToModelInstance(model, result[0], options); | ||
return this._convertToModelInstance(model_name, result[0], options); | ||
} | ||
@@ -373,4 +417,4 @@ else if (result && result.length > 1) { | ||
/** @internal */ | ||
async find(model, conditions, options) { | ||
const [sql, params] = this._buildSqlForFind(model, conditions, options); | ||
async find(model_name, conditions, options) { | ||
const [sql, params] = this._buildSqlForFind(model_name, conditions, options); | ||
if (options.explain) { | ||
@@ -388,3 +432,3 @@ return await this._client.allAsync(`EXPLAIN QUERY PLAN ${sql}`, params); | ||
return result.map((record) => { | ||
return this._convertToGroupInstance(model, record, options.group_by, options.group_fields); | ||
return this._convertToGroupInstance(model_name, record, options.group_by, options.group_fields); | ||
}); | ||
@@ -394,3 +438,3 @@ } | ||
return result.map((record) => { | ||
return this._convertToModelInstance(model, record, options); | ||
return this._convertToModelInstance(model_name, record, options); | ||
}); | ||
@@ -400,7 +444,7 @@ } | ||
/** @internal */ | ||
stream(model, conditions, options) { | ||
stream(model_name, conditions, options) { | ||
let sql; | ||
let params; | ||
try { | ||
[sql, params] = this._buildSqlForFind(model, conditions, options); | ||
[sql, params] = this._buildSqlForFind(model_name, conditions, options); | ||
} | ||
@@ -421,3 +465,3 @@ catch (error) { | ||
} | ||
readable.push(this._convertToModelInstance(model, record, options)); | ||
readable.push(this._convertToModelInstance(model_name, record, options)); | ||
}, () => { | ||
@@ -431,2 +475,5 @@ readable.push(null); | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return 0; | ||
} | ||
const select = options.select ? this._buildSelect(model_class, options.select) : '*'; | ||
@@ -442,5 +489,9 @@ const params = []; | ||
for (const join of options.joins) { | ||
sql += ` ${join.type} ${this._connection.models[join.model_name].table_name} AS _${join.alias}`; | ||
const join_model_class = this._connection.models[join.model_name]; | ||
if (!join_model_class) { | ||
continue; | ||
} | ||
sql += ` ${join.type} ${join_model_class.table_name} AS _${join.alias}`; | ||
sql += ` ON _Base.${escape_ch}${join.base_column}${escape_ch} = _${join.alias}.${escape_ch}${join.join_column}${escape_ch}`; | ||
join_schemas[join.alias] = this._connection.models[join.model_name]._schema; | ||
join_schemas[join.alias] = join_model_class._schema; | ||
} | ||
@@ -477,3 +528,6 @@ } | ||
const model_class = this._connection.models[model_name]; | ||
const nested = options && (options.orders.length > 0 || options.limit || options.skip); | ||
if (!model_class) { | ||
return 0; | ||
} | ||
const nested = options.orders.length > 0 || options.limit || options.skip; | ||
const params = []; | ||
@@ -488,3 +542,3 @@ const table_name = model_class.table_name; | ||
} | ||
if (options && options.orders.length > 0) { | ||
if (options.orders.length > 0) { | ||
const schema = model_class._schema; | ||
@@ -501,3 +555,3 @@ const orders = options.orders.map((order) => { | ||
} | ||
column = (schema[column] && schema[column]._dbname_us) || column; | ||
column = schema[column]?._dbname_us || column; | ||
return `"${column}" ${order}`; | ||
@@ -507,9 +561,9 @@ }); | ||
} | ||
if (options && options.limit) { | ||
if (options.limit) { | ||
sql += ' LIMIT ' + options.limit; | ||
if (options && options.skip) { | ||
if (options.skip) { | ||
sql += ' OFFSET ' + options.skip; | ||
} | ||
} | ||
else if (options && options.skip) { | ||
else if (options.skip) { | ||
sql += ' LIMIT 2147483647 OFFSET ' + options.skip; | ||
@@ -571,3 +625,3 @@ } | ||
/** @internal */ | ||
async startTransaction(adapter_connection, isolation_level) { | ||
async startTransaction(adapter_connection, _isolation_level) { | ||
await adapter_connection.allAsync('BEGIN TRANSACTION'); | ||
@@ -677,8 +731,9 @@ } | ||
for (const row of rows) { | ||
if (!indexes[row.name]) { | ||
indexes[row.name] = {}; | ||
let index = indexes[row.name]; | ||
if (!index) { | ||
index = indexes[row.name] = {}; | ||
} | ||
const columns = await this._client.allAsync(`PRAGMA index_info(\`${row.name}\`)`); | ||
for (const column of columns) { | ||
indexes[row.name][column.name] = 1; | ||
index[column.name] = 1; | ||
} | ||
@@ -722,4 +777,8 @@ } | ||
/** @internal */ | ||
_buildUpdateSet(model, data, values, insert = false) { | ||
const schema = this._connection.models[model]._schema; | ||
_buildUpdateSet(model_name, data, values, insert = false) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return ['', '']; | ||
} | ||
const schema = model_class._schema; | ||
const fields = []; | ||
@@ -729,3 +788,3 @@ const places = []; | ||
const property = schema[column]; | ||
if (property.primary_key) { | ||
if (property?.primary_key) { | ||
continue; | ||
@@ -738,9 +797,12 @@ } | ||
/** @internal */ | ||
_buildPartialUpdateSet(model, data, values) { | ||
const schema = this._connection.models[model]._schema; | ||
_buildPartialUpdateSet(model_name, data, values) { | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return ['', '']; | ||
} | ||
const schema = model_class._schema; | ||
const fields = []; | ||
const places = []; | ||
for (const column in data) { | ||
const value = data[column]; | ||
const property = lodash_1.default.find(schema, (item) => item._dbname_us === column); | ||
const property = lodash_1.default.find(schema, (item) => item?._dbname_us === column); | ||
if (!property || property.primary_key) { | ||
@@ -756,2 +818,5 @@ continue; | ||
const model_class = this._connection.models[model_name]; | ||
if (!model_class) { | ||
return ['', []]; | ||
} | ||
let select; | ||
@@ -771,5 +836,9 @@ if (options.group_by || options.group_fields) { | ||
for (const join of options.joins) { | ||
sql += ` ${join.type} ${this._connection.models[join.model_name].table_name} AS _${join.alias}`; | ||
const join_model_class = this._connection.models[join.model_name]; | ||
if (!join_model_class) { | ||
continue; | ||
} | ||
sql += ` ${join.type} ${join_model_class.table_name} AS _${join.alias}`; | ||
sql += ` ON _Base.${escape_ch}${join.base_column}${escape_ch} = _${join.alias}.${escape_ch}${join.join_column}${escape_ch}`; | ||
join_schemas[join.alias] = this._connection.models[join.model_name]._schema; | ||
join_schemas[join.alias] = join_model_class._schema; | ||
} | ||
@@ -787,3 +856,3 @@ } | ||
} | ||
if (options && options.orders.length > 0) { | ||
if (options.orders.length > 0) { | ||
const schema = model_class._schema; | ||
@@ -800,3 +869,3 @@ const orders = options.orders.map((order) => { | ||
} | ||
column = (schema[column] && schema[column]._dbname_us) || column; | ||
column = schema[column]?._dbname_us || column; | ||
return `"${column}" ${order}`; | ||
@@ -806,9 +875,9 @@ }); | ||
} | ||
if (options && options.limit) { | ||
if (options.limit) { | ||
sql += ' LIMIT ' + options.limit; | ||
if (options && options.skip) { | ||
if (options.skip) { | ||
sql += ' OFFSET ' + options.skip; | ||
} | ||
} | ||
else if (options && options.skip) { | ||
else if (options.skip) { | ||
sql += ' LIMIT 2147483647 OFFSET ' + options.skip; | ||
@@ -815,0 +884,0 @@ } |
@@ -10,3 +10,2 @@ "use strict"; | ||
constructor(argv) { | ||
var _a; | ||
const args = yargs_1.default | ||
@@ -22,3 +21,3 @@ .option('r', { | ||
.parseSync(argv); | ||
this.modules_to_load = (_a = args.require) !== null && _a !== void 0 ? _a : []; | ||
this.modules_to_load = args.require ?? []; | ||
} | ||
@@ -25,0 +24,0 @@ async run() { |
/// <reference types="node" /> | ||
/// <reference types="node" /> | ||
import { EventEmitter } from 'events'; | ||
@@ -14,3 +15,3 @@ import { inspect } from 'util'; | ||
import * as types from '../types'; | ||
declare type ManipulateCommand = string | { | ||
type ManipulateCommand = string | { | ||
[key: string]: any; | ||
@@ -39,3 +40,3 @@ }; | ||
} | ||
declare type AssociationIntegrityType = 'ignore' | 'nullify' | 'restrict' | 'delete'; | ||
type AssociationIntegrityType = 'ignore' | 'nullify' | 'restrict' | 'delete'; | ||
export interface AssociationHasManyOptions { | ||
@@ -117,5 +118,5 @@ connection?: Connection; | ||
*/ | ||
models: { | ||
models: Partial<{ | ||
[name: string]: typeof BaseModel; | ||
}; | ||
}>; | ||
[name: string]: any; | ||
@@ -169,3 +170,3 @@ /** | ||
*/ | ||
log(model: string, type: string, data: object): void; | ||
log(model_name: string, type: string, data: object): void; | ||
[inspect.custom](): string; | ||
@@ -172,0 +173,0 @@ /** |
"use strict"; | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
@@ -42,3 +46,3 @@ if (k2 === undefined) k2 = k; | ||
try { | ||
redis = require('redis'); | ||
redis = require('ioredis'); | ||
} | ||
@@ -52,4 +56,6 @@ catch (error) { | ||
class Connection extends events_1.EventEmitter { | ||
get adapter() { | ||
return this._adapter; | ||
} | ||
constructor(adapter, settings) { | ||
var _a, _b; | ||
super(); | ||
@@ -69,4 +75,4 @@ /** @internal */ | ||
} | ||
this._implicit_apply_schemas = (_a = settings.implicit_apply_schemas) !== null && _a !== void 0 ? _a : false; | ||
this._connection_retry_count = (_b = settings.connection_retry_count) !== null && _b !== void 0 ? _b : 99999; | ||
this._implicit_apply_schemas = settings.implicit_apply_schemas ?? false; | ||
this._connection_retry_count = settings.connection_retry_count ?? 99999; | ||
const redis_cache = settings.redis_cache || {}; | ||
@@ -86,5 +92,2 @@ this._redis_cache_settings = redis_cache; | ||
} | ||
get adapter() { | ||
return this._adapter; | ||
} | ||
/** | ||
@@ -148,17 +151,22 @@ * Set logger | ||
this._promise_schema_applied = this._promise_connection.then(async () => { | ||
var _a, _b, _c, _d, _e, _f, _g; | ||
try { | ||
const current = await this._adapter.getSchemas(); | ||
for (const model in this.models) { | ||
const modelClass = this.models[model]; | ||
const current_table = current.tables && current.tables[modelClass.table_name]; | ||
const model_class = this.models[model]; | ||
if (!model_class) { | ||
continue; | ||
} | ||
const current_table = current.tables[model_class.table_name]; | ||
if (!current_table || current_table === 'NO SCHEMA') { | ||
continue; | ||
} | ||
for (const column in modelClass._schema) { | ||
const property = modelClass._schema[column]; | ||
for (const column in model_class._schema) { | ||
const property = model_class._schema[column]; | ||
if (!property) { | ||
continue; | ||
} | ||
const current_column = current_table.columns[property._dbname_us]; | ||
if (!current_column) { | ||
if (options.verbose) { | ||
console.log(`Adding column ${property._dbname_us} to ${modelClass.table_name}`); | ||
console.log(`Adding column ${property._dbname_us} to ${model_class.table_name}`); | ||
} | ||
@@ -182,7 +190,7 @@ await this._adapter.addColumn(model, property, options.verbose); | ||
} | ||
if (((_a = current_column.description) !== null && _a !== void 0 ? _a : '') !== ((_b = property.description) !== null && _b !== void 0 ? _b : '')) { | ||
if ((current_column.description ?? '') !== (property.description ?? '')) { | ||
if (!type_changed) { | ||
if (options.apply_description_change) { | ||
if (options.verbose) { | ||
console.log(`Changing ${modelClass.table_name}.${column}'s description to '${property.description}'`); | ||
console.log(`Changing ${model_class.table_name}.${column}'s description to '${property.description}'`); | ||
} | ||
@@ -199,7 +207,10 @@ await this._adapter.updateColumnDescription(model, property, options.verbose); | ||
for (const model in this.models) { | ||
const modelClass = this.models[model]; | ||
const current_table = current.tables[modelClass.table_name]; | ||
const model_class = this.models[model]; | ||
if (!model_class) { | ||
continue; | ||
} | ||
const current_table = current.tables[model_class.table_name]; | ||
if (!current_table) { | ||
if (options.verbose) { | ||
console.log(`Creating table ${modelClass.table_name}`); | ||
console.log(`Creating table ${model_class.table_name}`); | ||
} | ||
@@ -209,6 +220,6 @@ await this._adapter.createTable(model, options.verbose); | ||
else if (current_table !== 'NO SCHEMA' && | ||
((_c = current_table.description) !== null && _c !== void 0 ? _c : '') !== ((_d = modelClass.description) !== null && _d !== void 0 ? _d : '')) { | ||
(current_table.description ?? '') !== (model_class.description ?? '')) { | ||
if (options.apply_description_change) { | ||
if (options.verbose) { | ||
console.log(`Changing table ${modelClass.table_name}'s description to '${modelClass.description}'`); | ||
console.log(`Changing table ${model_class.table_name}'s description to '${model_class.description}'`); | ||
} | ||
@@ -220,7 +231,10 @@ await this._adapter.updateTableDescription(model, options.verbose); | ||
for (const model_name in this.models) { | ||
const modelClass = this.models[model_name]; | ||
for (const index of modelClass._indexes) { | ||
if (!((_f = (_e = current.indexes) === null || _e === void 0 ? void 0 : _e[modelClass.table_name]) === null || _f === void 0 ? void 0 : _f[(_g = index.options.name) !== null && _g !== void 0 ? _g : ''])) { | ||
const model_class = this.models[model_name]; | ||
if (!model_class) { | ||
continue; | ||
} | ||
for (const index of model_class._indexes) { | ||
if (!current.indexes?.[model_class.table_name]?.[index.options.name ?? '']) { | ||
if (options.verbose) { | ||
console.log(`Creating index on ${modelClass.table_name} ${Object.keys(index.columns)}`); | ||
console.log(`Creating index on ${model_class.table_name} ${Object.keys(index.columns)}`); | ||
} | ||
@@ -232,4 +246,7 @@ await this._adapter.createIndex(model_name, index, options.verbose); | ||
for (const model in this.models) { | ||
const modelClass = this.models[model]; | ||
for (const integrity of modelClass._integrities) { | ||
const model_class = this.models[model]; | ||
if (!model_class) { | ||
continue; | ||
} | ||
for (const integrity of model_class._integrities) { | ||
let type = ''; | ||
@@ -247,7 +264,7 @@ if (integrity.type === 'child_nullify') { | ||
const current_foreign_key = current.foreign_keys && | ||
current.foreign_keys[modelClass.table_name] && | ||
current.foreign_keys[modelClass.table_name][integrity.column]; | ||
current.foreign_keys[model_class.table_name] && | ||
current.foreign_keys[model_class.table_name][integrity.column]; | ||
if (!(current_foreign_key && current_foreign_key === integrity.parent.table_name)) { | ||
if (options.verbose) { | ||
const table_name = modelClass.table_name; | ||
const table_name = model_class.table_name; | ||
const parent_table_name = integrity.parent.table_name; | ||
@@ -281,3 +298,2 @@ console.log(`Adding foreign key ${table_name}.${integrity.column} to ${parent_table_name}`); | ||
async getSchemaChanges() { | ||
var _a, _b, _c, _d, _e, _f, _g, _h; | ||
this._initializeModels(); | ||
@@ -290,12 +306,18 @@ this.applyAssociations(); | ||
for (const model in this.models) { | ||
const modelClass = this.models[model]; | ||
const current_table = current.tables && current.tables[modelClass.table_name]; | ||
const model_class = this.models[model]; | ||
if (!model_class) { | ||
continue; | ||
} | ||
const current_table = current.tables[model_class.table_name]; | ||
if (!current_table || current_table === 'NO SCHEMA') { | ||
continue; | ||
} | ||
for (const column in modelClass._schema) { | ||
const property = modelClass._schema[column]; | ||
for (const column in model_class._schema) { | ||
const property = model_class._schema[column]; | ||
if (!property) { | ||
continue; | ||
} | ||
const current_column = current_table.columns[property._dbname_us]; | ||
if (!current_column) { | ||
changes.push({ message: `Add column ${property._dbname_us} to ${modelClass.table_name}` }); | ||
changes.push({ message: `Add column ${property._dbname_us} to ${model_class.table_name}` }); | ||
const query = this._adapter.getAddColumnQuery(model, property); | ||
@@ -312,3 +334,3 @@ if (query) { | ||
changes.push({ | ||
message: `Change ${modelClass.table_name}.${property._dbname_us} to required`, | ||
message: `Change ${model_class.table_name}.${property._dbname_us} to required`, | ||
ignorable: true, | ||
@@ -319,3 +341,3 @@ }); | ||
type_changed = true; | ||
changes.push({ message: `Change ${modelClass.table_name}.${column} to optional`, ignorable: true }); | ||
changes.push({ message: `Change ${model_class.table_name}.${column} to optional`, ignorable: true }); | ||
} | ||
@@ -328,10 +350,10 @@ } | ||
changes.push({ | ||
message: `Type different ${modelClass.table_name}.${column}: expected=${expected_type}, real=${real_type}`, | ||
message: `Type different ${model_class.table_name}.${column}: expected=${expected_type}, real=${real_type}`, | ||
ignorable: true, | ||
}); | ||
} | ||
if (((_a = current_column.description) !== null && _a !== void 0 ? _a : '') !== ((_b = property.description) !== null && _b !== void 0 ? _b : '')) { | ||
if ((current_column.description ?? '') !== (property.description ?? '')) { | ||
if (!type_changed) { | ||
changes.push({ | ||
message: `Change ${modelClass.table_name}.${column}'s description to '${property.description}'`, | ||
message: `Change ${model_class.table_name}.${column}'s description to '${property.description}'`, | ||
ignorable: true, | ||
@@ -346,3 +368,3 @@ }); | ||
changes.push({ | ||
message: `(Skip) Change ${modelClass.table_name}.${column}'s description to '${property.description}'`, | ||
message: `(Skip) Change ${model_class.table_name}.${column}'s description to '${property.description}'`, | ||
ignorable: true, | ||
@@ -354,4 +376,4 @@ }); | ||
for (const column in current_table.columns) { | ||
if (!lodash_1.default.find(modelClass._schema, { _dbname_us: column })) { | ||
changes.push({ message: `Remove column ${column} from ${modelClass.table_name}`, ignorable: true }); | ||
if (!lodash_1.default.find(model_class._schema, { _dbname_us: column })) { | ||
changes.push({ message: `Remove column ${column} from ${model_class.table_name}`, ignorable: true }); | ||
} | ||
@@ -361,6 +383,9 @@ } | ||
for (const model in this.models) { | ||
const modelClass = this.models[model]; | ||
const current_table = current.tables[modelClass.table_name]; | ||
const model_class = this.models[model]; | ||
if (!model_class) { | ||
continue; | ||
} | ||
const current_table = current.tables[model_class.table_name]; | ||
if (!current_table) { | ||
changes.push({ message: `Add table ${modelClass.table_name}` }); | ||
changes.push({ message: `Add table ${model_class.table_name}` }); | ||
const query = this._adapter.getCreateTableQuery(model); | ||
@@ -372,5 +397,5 @@ if (query) { | ||
else if (current_table !== 'NO SCHEMA' && | ||
((_c = current_table.description) !== null && _c !== void 0 ? _c : '') !== ((_d = modelClass.description) !== null && _d !== void 0 ? _d : '')) { | ||
(current_table.description ?? '') !== (model_class.description ?? '')) { | ||
changes.push({ | ||
message: `Change table ${modelClass.table_name}'s description to '${modelClass.description}'`, | ||
message: `Change table ${model_class.table_name}'s description to '${model_class.description}'`, | ||
ignorable: true, | ||
@@ -390,6 +415,9 @@ }); | ||
for (const model_name in this.models) { | ||
const modelClass = this.models[model_name]; | ||
for (const index of modelClass._indexes) { | ||
if (!((_f = (_e = current.indexes) === null || _e === void 0 ? void 0 : _e[modelClass.table_name]) === null || _f === void 0 ? void 0 : _f[(_g = index.options.name) !== null && _g !== void 0 ? _g : ''])) { | ||
changes.push({ message: `Add index on ${modelClass.table_name} ${Object.keys(index.columns)}` }); | ||
const model_class = this.models[model_name]; | ||
if (!model_class) { | ||
continue; | ||
} | ||
for (const index of model_class._indexes) { | ||
if (!current.indexes?.[model_class.table_name]?.[index.options.name ?? '']) { | ||
changes.push({ message: `Add index on ${model_class.table_name} ${Object.keys(index.columns)}` }); | ||
const query = this._adapter.getCreateIndexQuery(model_name, index); | ||
@@ -401,7 +429,7 @@ if (query) { | ||
} | ||
for (const index in (_h = current.indexes) === null || _h === void 0 ? void 0 : _h[modelClass.table_name]) { | ||
for (const index in current.indexes?.[model_class.table_name]) { | ||
// MySQL add index for foreign key, so does not need to remove if the index is defined in integrities | ||
if (!lodash_1.default.find(modelClass._indexes, (item) => item.options.name === index) && | ||
!lodash_1.default.find(modelClass._integrities, (item) => item.column === index)) { | ||
changes.push({ message: `Remove index on ${modelClass.table_name} ${index}`, ignorable: true }); | ||
if (!lodash_1.default.find(model_class._indexes, (item) => item.options.name === index) && | ||
!lodash_1.default.find(model_class._integrities, (item) => item.column === index)) { | ||
changes.push({ message: `Remove index on ${model_class.table_name} ${index}`, ignorable: true }); | ||
} | ||
@@ -411,4 +439,7 @@ } | ||
for (const model in this.models) { | ||
const modelClass = this.models[model]; | ||
for (const integrity of modelClass._integrities) { | ||
const model_class = this.models[model]; | ||
if (!model_class) { | ||
continue; | ||
} | ||
for (const integrity of model_class._integrities) { | ||
let type = ''; | ||
@@ -426,7 +457,7 @@ if (integrity.type === 'child_nullify') { | ||
const current_foreign_key = current.foreign_keys && | ||
current.foreign_keys[modelClass.table_name] && | ||
current.foreign_keys[modelClass.table_name][integrity.column]; | ||
current.foreign_keys[model_class.table_name] && | ||
current.foreign_keys[model_class.table_name][integrity.column]; | ||
if (!(current_foreign_key && current_foreign_key === integrity.parent.table_name) && | ||
this._adapter.native_integrity) { | ||
const table_name = modelClass.table_name; | ||
const table_name = model_class.table_name; | ||
const parent_table_name = integrity.parent.table_name; | ||
@@ -448,4 +479,4 @@ changes.push({ message: `Add foreign key ${table_name}.${integrity.column} to ${parent_table_name}` }); | ||
async dropAllModels() { | ||
for (const model of this._getModelNamesByAssociationOrder()) { | ||
await this.models[model].drop(); | ||
for (const model_name of this._getModelNamesByAssociationOrder()) { | ||
await this.models[model_name]?.drop(); | ||
} | ||
@@ -456,3 +487,4 @@ } | ||
*/ | ||
log(model, type, data) { | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
log(model_name, type, data) { | ||
/**/ | ||
@@ -493,7 +525,7 @@ } | ||
else if (key.substr(0, 7) === 'create_') { | ||
const model = key.substr(7); | ||
const model_name = key.substr(7); | ||
const id = data.id; | ||
delete data.id; | ||
this._manipulateConvertIds(id_to_record_map, model, data); | ||
const record = await this._manipulateCreate(model, data); | ||
this._manipulateConvertIds(id_to_record_map, model_name, data); | ||
const record = await this._manipulateCreate(model_name, data); | ||
if (id) { | ||
@@ -504,4 +536,4 @@ id_to_record_map[id] = record; | ||
else if (key.substr(0, 7) === 'delete_') { | ||
const model = key.substr(7); | ||
await this._manipulateDelete(model, data); | ||
const model_name = key.substr(7); | ||
await this._manipulateDelete(model_name, data); | ||
} | ||
@@ -512,4 +544,4 @@ else if (key === 'deleteAll') { | ||
else if (key.substr(0, 5) === 'drop_') { | ||
const model = key.substr(5); | ||
await this._manipulateDropModel(model); | ||
const model_name = key.substr(5); | ||
await this._manipulateDropModel(model_name); | ||
} | ||
@@ -520,3 +552,3 @@ else if (key === 'dropAll') { | ||
else if (key.substr(0, 5) === 'find_') { | ||
const model = key.substr(5); | ||
const model_name = key.substr(5); | ||
const id = data.id; | ||
@@ -527,3 +559,3 @@ delete data.id; | ||
} | ||
const records = await this._manipulateFind(model, data); | ||
const records = await this._manipulateFind(model_name, data); | ||
id_to_record_map[id] = records; | ||
@@ -552,7 +584,10 @@ } | ||
const result = {}; | ||
const promises = Object.keys(this.models).map(async (model) => { | ||
const modelClass = this.models[model]; | ||
const integrities = modelClass._integrities.filter((integrity) => integrity.type.substr(0, 7) === 'parent_'); | ||
const promises = Object.keys(this.models).map(async (model_name) => { | ||
const model_class = this.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
const integrities = model_class._integrities.filter((integrity) => integrity.type.substr(0, 7) === 'parent_'); | ||
if (integrities.length > 0) { | ||
let records = await modelClass.select('').exec(); | ||
let records = await model_class.select('').exec(); | ||
const ids = records.map((record) => record.id); | ||
@@ -563,3 +598,3 @@ const sub_promises = integrities.map(async (integrity) => { | ||
const property = integrity.child._schema[integrity.column]; | ||
if (!property.required) { | ||
if (!property?.required) { | ||
query.where(lodash_1.default.zipObject([integrity.column], [{ $not: null }])); | ||
@@ -598,3 +633,3 @@ } | ||
if (options.model) { | ||
association = options.model._associations && options.model._associations[column]; | ||
association = options.model._associations[column]; | ||
} | ||
@@ -645,6 +680,7 @@ else { | ||
} | ||
if (!models[target_model_name]) { | ||
const model = models[target_model_name]; | ||
if (!model) { | ||
throw new Error(`model ${target_model_name} does not exist`); | ||
} | ||
target_model = models[target_model_name]; | ||
target_model = model; | ||
} | ||
@@ -674,3 +710,3 @@ else { | ||
const transaction = new transaction_1.Transaction(this); | ||
await transaction.setup(options && options.isolation_level); | ||
await transaction.setup(options.isolation_level); | ||
try { | ||
@@ -765,5 +801,2 @@ const args = (options.models || []).map((model) => { | ||
async _connect(settings, count = 0) { | ||
if (!this._adapter) { | ||
return; | ||
} | ||
try { | ||
@@ -786,18 +819,24 @@ await this._adapter.connect(settings); | ||
_initializeModels() { | ||
for (const model in this.models) { | ||
const modelClass = this.models[model]; | ||
if (modelClass.initialize && !modelClass._initialize_called) { | ||
modelClass.initialize(); | ||
modelClass._initialize_called = true; | ||
for (const model_name in this.models) { | ||
const model_class = this.models[model_name]; | ||
if (!model_class) { | ||
continue; | ||
} | ||
modelClass._completeSchema(); | ||
if (!model_class._initialize_called) { | ||
model_class.initialize(); | ||
model_class._initialize_called = true; | ||
} | ||
model_class._completeSchema(); | ||
} | ||
} | ||
_checkArchive() { | ||
for (const model in this.models) { | ||
const modelClass = this.models[model]; | ||
if (modelClass.archive && !Object.prototype.hasOwnProperty.call(modelClass._connection.models, '_Archive')) { | ||
for (const model_name in this.models) { | ||
const model_class = this.models[model_name]; | ||
if (!model_class) { | ||
continue; | ||
} | ||
if (model_class.archive && !Object.prototype.hasOwnProperty.call(model_class._connection.models, '_Archive')) { | ||
const _Archive = class extends model_1.BaseModel { | ||
}; | ||
_Archive.connection(modelClass._connection); | ||
_Archive.connection(model_class._connection); | ||
_Archive.archive = false; | ||
@@ -811,7 +850,10 @@ _Archive.column('model', String); | ||
const t = new Toposort(); | ||
for (const model in this.models) { | ||
const modelClass = this.models[model]; | ||
t.add(model, []); | ||
for (const name in modelClass._associations) { | ||
const association = modelClass._associations[name]; | ||
for (const model_name in this.models) { | ||
const model_class = this.models[model_name]; | ||
if (!model_class) { | ||
continue; | ||
} | ||
t.add(model_name, []); | ||
for (const name in model_class._associations) { | ||
const association = model_class._associations[name]; | ||
// ignore association with models of other connection | ||
@@ -822,3 +864,3 @@ if (association.target_model._connection !== this) { | ||
// ignore self association | ||
if (association.target_model === modelClass) { | ||
if (association.target_model === model_class) { | ||
continue; | ||
@@ -828,6 +870,6 @@ } | ||
if (type === 'hasMany' || type === 'hasOne') { | ||
t.add(association.target_model._name, model); | ||
t.add(association.target_model._name, model_name); | ||
} | ||
else if (type === 'belongsTo') { | ||
t.add(model, association.target_model._name); | ||
t.add(model_name, association.target_model._name); | ||
} | ||
@@ -838,15 +880,17 @@ } | ||
} | ||
async _manipulateCreate(model, data) { | ||
model = inflector.camelize(model); | ||
if (!this.models[model]) { | ||
throw new Error(`model ${model} does not exist`); | ||
async _manipulateCreate(model_name, data) { | ||
model_name = inflector.camelize(model_name); | ||
const model_class = this.models[model_name]; | ||
if (!model_class) { | ||
throw new Error(`model ${model_name} does not exist`); | ||
} | ||
return await this.models[model].create(data, { skip_log: true }); | ||
return await model_class.create(data, { skip_log: true }); | ||
} | ||
async _manipulateDelete(model, data) { | ||
model = inflector.camelize(model); | ||
if (!this.models[model]) { | ||
throw new Error(`model ${model} does not exist`); | ||
async _manipulateDelete(model_name, data) { | ||
model_name = inflector.camelize(model_name); | ||
const model_class = this.models[model_name]; | ||
if (!model_class) { | ||
throw new Error(`model ${model_name} does not exist`); | ||
} | ||
await this.models[model].where(data).delete({ skip_log: true }); | ||
await model_class.where(data).delete({ skip_log: true }); | ||
} | ||
@@ -860,3 +904,3 @@ async _manipulateDeleteAllModels() { | ||
if (error.message === 'not implemented') { | ||
await Promise.all(model_list.map((model) => this.models[model].where().delete({ skip_log: true }))); | ||
await Promise.all(model_list.map((model_name) => this.models[model_name]?.where().delete({ skip_log: true }))); | ||
return; | ||
@@ -867,8 +911,9 @@ } | ||
} | ||
async _manipulateDropModel(model) { | ||
model = inflector.camelize(model); | ||
if (!this.models[model]) { | ||
throw new Error(`model ${model} does not exist`); | ||
async _manipulateDropModel(model_name) { | ||
model_name = inflector.camelize(model_name); | ||
const model_class = this.models[model_name]; | ||
if (!model_class) { | ||
throw new Error(`model ${model_name} does not exist`); | ||
} | ||
await this.models[model].drop(); | ||
await model_class.drop(); | ||
} | ||
@@ -878,17 +923,19 @@ async _manipulateDropAllModels() { | ||
} | ||
async _manipulateFind(model, data) { | ||
model = inflector.camelize(inflector.singularize(model)); | ||
if (!this.models[model]) { | ||
throw new Error(`model ${model} does not exist`); | ||
async _manipulateFind(model_name, data) { | ||
model_name = inflector.camelize(inflector.singularize(model_name)); | ||
const model_class = this.models[model_name]; | ||
if (!model_class) { | ||
throw new Error(`model ${model_name} does not exist`); | ||
} | ||
return await this.models[model].where(data).exec({ skip_log: true }); | ||
return await model_class.where(data).exec({ skip_log: true }); | ||
} | ||
_manipulateConvertIds(id_to_record_map, model, data) { | ||
model = inflector.camelize(model); | ||
if (!this.models[model]) { | ||
_manipulateConvertIds(id_to_record_map, model_name, data) { | ||
model_name = inflector.camelize(model_name); | ||
const model_class = this.models[model_name]; | ||
if (!model_class) { | ||
return; | ||
} | ||
for (const column in this.models[model]._schema) { | ||
const property = this.models[model]._schema[column]; | ||
if (property.record_id && Object.prototype.hasOwnProperty.call(data, column)) { | ||
for (const column in model_class._schema) { | ||
const property = model_class._schema[column]; | ||
if (property && property.record_id && Object.prototype.hasOwnProperty.call(data, column)) { | ||
if (property.array && Array.isArray(data[column])) { | ||
@@ -895,0 +942,0 @@ data[column] = data[column].map((value) => { |
@@ -102,2 +102,5 @@ "use strict"; | ||
else { | ||
if (!ctor._property_decorators) { | ||
ctor._property_decorators = []; | ||
} | ||
ctor._property_decorators.push({ type: 'index', columns, options }); | ||
@@ -104,0 +107,0 @@ } |
@@ -8,3 +8,7 @@ "use strict"; | ||
if (k2 === undefined) k2 = k; | ||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
@@ -11,0 +15,0 @@ if (k2 === undefined) k2 = k; |
import { Logger } from './Logger'; | ||
export declare class EmptyLogger implements Logger { | ||
logQuery(text: string, values?: any[]): void; | ||
logQuery(_text: string, _values?: any[]): void; | ||
} |
@@ -5,3 +5,3 @@ "use strict"; | ||
class EmptyLogger { | ||
logQuery(text, values) { | ||
logQuery(_text, _values) { | ||
// | ||
@@ -8,0 +8,0 @@ } |
"use strict"; | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
@@ -6,0 +10,0 @@ if (k2 === undefined) k2 = k; |
@@ -8,7 +8,7 @@ /// <reference types="node" /> | ||
import * as types from '../types'; | ||
declare type ModelCallbackMethod = () => void | 'string'; | ||
export declare type ModelColumnNames<M> = Exclude<keyof M, keyof BaseModel>; | ||
export declare type ModelColumnNamesWithId<M> = Exclude<keyof M, Exclude<keyof BaseModel, 'id'>>; | ||
export declare type ModelValueObject<M> = Pick<M, ModelColumnNames<M>>; | ||
export declare type ModelValueObjectWithId<M> = Pick<M, ModelColumnNamesWithId<M>>; | ||
type ModelCallbackMethod = () => void | 'string'; | ||
export type ModelColumnNames<M> = Exclude<keyof M, keyof BaseModel>; | ||
export type ModelColumnNamesWithId<M> = Exclude<keyof M, Exclude<keyof BaseModel, 'id'>>; | ||
export type ModelValueObject<M> = Pick<M, ModelColumnNames<M>>; | ||
export type ModelValueObjectWithId<M> = Pick<M, ModelColumnNamesWithId<M>>; | ||
export interface ColumnProperty { | ||
@@ -41,3 +41,3 @@ type: types.ColumnType | types.ColumnType[]; | ||
export interface ModelSchemaInternal { | ||
[path: string]: ColumnPropertyInternal; | ||
[path: string]: ColumnPropertyInternal | undefined; | ||
} | ||
@@ -72,3 +72,3 @@ /** | ||
static _schema: ModelSchemaInternal; | ||
static _object_column_classes: Array<{ | ||
static _object_column_classes?: Array<{ | ||
column: string; | ||
@@ -88,3 +88,3 @@ klass: any; | ||
static _intermediate_paths: any; | ||
static _property_decorators: any[]; | ||
static _property_decorators?: any[]; | ||
static initialize(): void; | ||
@@ -125,3 +125,3 @@ /** | ||
*/ | ||
static build<M extends BaseModel>(this: new (data?: any) => M, data?: ModelValueObject<M>): M; | ||
static build<M extends BaseModel>(this: new (data_arg?: any) => M, data?: ModelValueObject<M>): M; | ||
/** | ||
@@ -143,3 +143,3 @@ * Deletes all records from the database | ||
static belongsTo(target_model_or_column: string | typeof BaseModel, options?: AssociationBelongsToOptions): void; | ||
static [inspect.custom](depth: number): string; | ||
static [inspect.custom](_depth: number): string; | ||
static _getKeyType(target_connection?: Connection<AdapterBase>): any; | ||
@@ -205,3 +205,3 @@ /** | ||
*/ | ||
static create<M extends BaseModel>(this: (new (data?: any) => M) & typeof BaseModel, data?: ModelValueObject<M>, options?: { | ||
static create<M extends BaseModel>(this: (new (data_arg?: any) => M) & typeof BaseModel, data?: ModelValueObject<M>, options?: { | ||
transaction?: Transaction; | ||
@@ -213,3 +213,3 @@ skip_log?: boolean; | ||
*/ | ||
static createBulk<M extends BaseModel>(this: (new (data?: any) => M) & typeof BaseModel, data?: Array<ModelValueObject<M>>, options?: { | ||
static createBulk<M extends BaseModel>(this: (new (data_arg?: any) => M) & typeof BaseModel, data?: Array<ModelValueObject<M>>, options?: { | ||
transaction?: Transaction; | ||
@@ -307,3 +307,3 @@ }): Promise<M[]>; | ||
private static _validators; | ||
private static _callbacks_map; | ||
private static _callbacks_map?; | ||
/** | ||
@@ -310,0 +310,0 @@ * Adds a callback |
"use strict"; | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
@@ -56,84 +60,2 @@ if (k2 === undefined) k2 = k; | ||
class BaseModel { | ||
/** | ||
* Creates a record | ||
*/ | ||
constructor(data) { | ||
data = data || {}; | ||
const ctor = this.constructor; | ||
const schema = ctor._schema; | ||
const adapter = ctor._adapter; | ||
Object.defineProperty(this, '_prev_attributes', { writable: true, value: {} }); | ||
if (ctor.dirty_tracking) { | ||
Object.defineProperty(this, '_attributes', { value: {} }); | ||
Object.defineProperty(this, '_intermediates', { value: {} }); | ||
for (const path of Object.keys(ctor._intermediate_paths).sort()) { | ||
const [obj, last] = util.getLeafOfPath(this, path); | ||
this._intermediates[path] = {}; | ||
this._defineProperty(obj, last, path, false); | ||
} | ||
for (const column in schema) { | ||
const property = schema[column]; | ||
if (property.primary_key) { | ||
continue; | ||
} | ||
const [obj, last] = util.getLeafOfPath(this, property._parts); | ||
this._defineProperty(obj, last, column, false); | ||
} | ||
} | ||
else { | ||
Object.defineProperty(this, 'isDirty', { value: _pf_isDirty }); | ||
Object.defineProperty(this, 'getChanged', { value: _pf_getChanged }); | ||
Object.defineProperty(this, 'get', { value: _pf_get }); | ||
Object.defineProperty(this, 'getPrevious', { value: _pf_getPrevious }); | ||
Object.defineProperty(this, 'set', { value: _pf_set }); | ||
Object.defineProperty(this, 'reset', { value: _pf_reset }); | ||
} | ||
if (ctor._object_column_classes) { | ||
for (const { column, klass } of ctor._object_column_classes) { | ||
this[column] = new klass(); | ||
} | ||
} | ||
if (arguments.length === 4) { | ||
// if this has 4 arguments, this is called from adapter with database record data | ||
// eslint-disable-next-line prefer-rest-params | ||
const [id, selected_columns, selected_columns_raw] = [arguments[1], arguments[2], arguments[3]]; | ||
adapter.setValuesFromDB(this, data, schema, selected_columns); | ||
ctor._collapseNestedNulls(this, selected_columns_raw, ctor.dirty_tracking ? this._intermediates : undefined); | ||
Object.defineProperty(this, 'id', { | ||
configurable: false, | ||
enumerable: true, | ||
value: id, | ||
writable: false, | ||
}); | ||
Object.defineProperty(this, '_is_persisted', { | ||
configurable: false, | ||
enumerable: false, | ||
value: true, | ||
writable: false, | ||
}); | ||
this._runCallbacks('find', 'after'); | ||
} | ||
else { | ||
for (const column in schema) { | ||
const property = schema[column]; | ||
if (property.primary_key) { | ||
continue; | ||
} | ||
const parts = property._parts; | ||
let value = util.getPropertyOfPath(data, parts); | ||
if (value === undefined) { | ||
value = null; | ||
} | ||
util.setPropertyOfPath(this, parts, value); | ||
} | ||
ctor._collapseNestedNulls(this, null, ctor.dirty_tracking ? this._intermediates : undefined); | ||
Object.defineProperty(this, 'id', { | ||
configurable: true, | ||
enumerable: true, | ||
value: null, | ||
writable: false, | ||
}); | ||
} | ||
this._runCallbacks('initialize', 'after'); | ||
} | ||
static initialize() { | ||
@@ -209,4 +131,5 @@ /**/ | ||
// overwrite some properties if given later | ||
if (type_or_property && type_or_property.required) { | ||
this._schema[path].required = type_or_property.required; | ||
const column = this._schema[path]; | ||
if (column && type_or_property && type_or_property.required) { | ||
column.required = type_or_property.required; | ||
} | ||
@@ -318,6 +241,6 @@ return; | ||
} | ||
static [util_1.inspect.custom](depth) { | ||
const schema = Object.keys(this._schema || {}) | ||
static [util_1.inspect.custom](_depth) { | ||
const schema = Object.keys(this._schema) | ||
.sort() | ||
.map((column) => `${column}: ${this._schema[column].type}`) | ||
.map((column) => `${column}: ${this._schema[column]?.type}`) | ||
.join(', '); | ||
@@ -660,3 +583,3 @@ return '\u001b[36m' + `[Model: ${this.name}(` + '\u001b[90m' + schema + '\u001b[36m' + ')]' + '\u001b[39m'; | ||
const column_names = Object.keys(index.columns).map((column_name) => { | ||
return (this._schema[column_name] && this._schema[column_name]._dbname_us) || column_name; | ||
return this._schema[column_name]?._dbname_us || column_name; | ||
}); | ||
@@ -672,5 +595,2 @@ index.options.name = column_names.join('_'); | ||
this._checkConnection(); | ||
if (!(type === 'before' || type === 'after') || !name) { | ||
return; | ||
} | ||
const callbacks_map = this._callbacks_map || (this._callbacks_map = {}); | ||
@@ -749,2 +669,84 @@ const callbacks = callbacks_map[name] || (callbacks_map[name] = []); | ||
/** | ||
* Creates a record | ||
*/ | ||
constructor(data) { | ||
data = data || {}; | ||
const ctor = this.constructor; | ||
const schema = ctor._schema; | ||
const adapter = ctor._adapter; | ||
Object.defineProperty(this, '_prev_attributes', { writable: true, value: {} }); | ||
if (ctor.dirty_tracking) { | ||
Object.defineProperty(this, '_attributes', { value: {} }); | ||
Object.defineProperty(this, '_intermediates', { value: {} }); | ||
for (const path of Object.keys(ctor._intermediate_paths).sort()) { | ||
const [obj, last] = util.getLeafOfPath(this, path); | ||
this._intermediates[path] = {}; | ||
this._defineProperty(obj, last, path, false); | ||
} | ||
for (const column in schema) { | ||
const property = schema[column]; | ||
if (!property || property.primary_key) { | ||
continue; | ||
} | ||
const [obj, last] = util.getLeafOfPath(this, property._parts); | ||
this._defineProperty(obj, last, column, false); | ||
} | ||
} | ||
else { | ||
Object.defineProperty(this, 'isDirty', { value: _pf_isDirty }); | ||
Object.defineProperty(this, 'getChanged', { value: _pf_getChanged }); | ||
Object.defineProperty(this, 'get', { value: _pf_get }); | ||
Object.defineProperty(this, 'getPrevious', { value: _pf_getPrevious }); | ||
Object.defineProperty(this, 'set', { value: _pf_set }); | ||
Object.defineProperty(this, 'reset', { value: _pf_reset }); | ||
} | ||
if (ctor._object_column_classes) { | ||
for (const { column, klass } of ctor._object_column_classes) { | ||
this[column] = new klass(); | ||
} | ||
} | ||
if (arguments.length === 4) { | ||
// if this has 4 arguments, this is called from adapter with database record data | ||
// eslint-disable-next-line prefer-rest-params | ||
const [id, selected_columns, selected_columns_raw] = [arguments[1], arguments[2], arguments[3]]; | ||
adapter.setValuesFromDB(this, data, schema, selected_columns); | ||
ctor._collapseNestedNulls(this, selected_columns_raw, ctor.dirty_tracking ? this._intermediates : undefined); | ||
Object.defineProperty(this, 'id', { | ||
configurable: false, | ||
enumerable: true, | ||
value: id, | ||
writable: false, | ||
}); | ||
Object.defineProperty(this, '_is_persisted', { | ||
configurable: false, | ||
enumerable: false, | ||
value: true, | ||
writable: false, | ||
}); | ||
this._runCallbacks('find', 'after'); | ||
} | ||
else { | ||
for (const column in schema) { | ||
const property = schema[column]; | ||
if (!property || property.primary_key) { | ||
continue; | ||
} | ||
const parts = property._parts; | ||
let value = util.getPropertyOfPath(data, parts); | ||
if (value === undefined) { | ||
value = null; | ||
} | ||
util.setPropertyOfPath(this, parts, value); | ||
} | ||
ctor._collapseNestedNulls(this, null, ctor.dirty_tracking ? this._intermediates : undefined); | ||
Object.defineProperty(this, 'id', { | ||
configurable: true, | ||
enumerable: true, | ||
value: null, | ||
writable: false, | ||
}); | ||
} | ||
this._runCallbacks('initialize', 'after'); | ||
} | ||
/** | ||
* Returns true if there is some changed columns | ||
@@ -858,3 +860,3 @@ */ | ||
this.validate(); | ||
return await this.save(Object.assign(Object.assign({}, options), { validate: false })); | ||
return await this.save({ ...options, validate: false }); | ||
} | ||
@@ -894,3 +896,3 @@ this._runCallbacks('save', 'before'); | ||
const property = schema[column]; | ||
if (property.primary_key) { | ||
if (!property || property.primary_key) { | ||
continue; | ||
@@ -954,3 +956,3 @@ } | ||
const property = schema[column]; | ||
if (property.primary_key) { | ||
if (!property || property.primary_key) { | ||
continue; | ||
@@ -968,3 +970,3 @@ } | ||
const ctor = this.constructor; | ||
if (!(options && options.skip_log)) { | ||
if (!options.skip_log) { | ||
ctor._connection.log(ctor._name, 'create', data); | ||
@@ -1013,5 +1015,8 @@ } | ||
for (const path in this._prev_attributes) { | ||
ctor._buildSaveDataColumn(data, this._attributes, path, schema[path], true); | ||
const property = schema[path]; | ||
if (property) { | ||
ctor._buildSaveDataColumn(data, this._attributes, path, property, true); | ||
} | ||
} | ||
if (!(options && options.skip_log)) { | ||
if (!options.skip_log) { | ||
ctor._connection.log(ctor._name, 'update', data); | ||
@@ -1025,3 +1030,3 @@ } | ||
const data = this._buildSaveData(); | ||
if (!(options && options.skip_log)) { | ||
if (!options.skip_log) { | ||
ctor._connection.log(ctor._name, 'update', data); | ||
@@ -1037,3 +1042,3 @@ } | ||
const property = this._schema[column]; | ||
if (property.primary_key || property.default_value == null) { | ||
if (!property || property.primary_key || property.default_value == null) { | ||
continue; | ||
@@ -1040,0 +1045,0 @@ } |
@@ -158,5 +158,5 @@ "use strict"; | ||
type: 'INNER JOIN', | ||
alias: options === null || options === void 0 ? void 0 : options.alias, | ||
base_column: options === null || options === void 0 ? void 0 : options.base_column, | ||
join_column: options === null || options === void 0 ? void 0 : options.join_column, | ||
alias: options?.alias, | ||
base_column: options?.base_column, | ||
join_column: options?.join_column, | ||
}); | ||
@@ -175,5 +175,5 @@ return this; | ||
type: 'LEFT OUTER JOIN', | ||
alias: options === null || options === void 0 ? void 0 : options.alias, | ||
base_column: options === null || options === void 0 ? void 0 : options.base_column, | ||
join_column: options === null || options === void 0 ? void 0 : options.join_column, | ||
alias: options?.alias, | ||
base_column: options?.base_column, | ||
join_column: options?.join_column, | ||
}); | ||
@@ -392,3 +392,2 @@ return this; | ||
async upsert(updates, options) { | ||
var _a; | ||
this._setUsed(); | ||
@@ -407,3 +406,6 @@ await this._model._checkReady(); | ||
const default_applied_columns = this._model.applyDefaultValues(data); | ||
options = Object.assign(Object.assign({}, this._options), { ignore_on_update: ((_a = options === null || options === void 0 ? void 0 : options.ignore_on_update) !== null && _a !== void 0 ? _a : []).concat(default_applied_columns) }); | ||
options = { | ||
...this._options, | ||
ignore_on_update: (options?.ignore_on_update ?? []).concat(default_applied_columns), | ||
}; | ||
this._connection.log(this._name, 'upsert', { data, conditions: this._conditions, options }); | ||
@@ -521,7 +523,5 @@ return await this._adapter.upsert(this._name, data, this._conditions, options); | ||
if (this._options.group_by) { | ||
group_by = this._options.group_by | ||
.map((column) => { | ||
return this._model._schema[column]._dbname_us; | ||
}) | ||
.filter((column) => column != null); | ||
group_by = lodash_1.default.compact(this._options.group_by.map((column) => { | ||
return this._model._schema[column]?._dbname_us; | ||
})); | ||
} | ||
@@ -591,3 +591,19 @@ const orders = []; | ||
} | ||
return Object.assign({ conditions_of_group: this._options.conditions_of_group, explain: this._options.explain, group_by, group_fields: this._options.group_fields, joins, lean: this._options.lean, limit: this._options.limit, near: this._options.near, node: this._options.node, index_hint: this._options.index_hint, orders, skip: this._options.skip, transaction: this._options.transaction, distinct: this._options.distinct }, (select_raw.length > 0 && { select, select_raw })); | ||
return { | ||
conditions_of_group: this._options.conditions_of_group, | ||
explain: this._options.explain, | ||
group_by, | ||
group_fields: this._options.group_fields, | ||
joins, | ||
lean: this._options.lean, | ||
limit: this._options.limit, | ||
near: this._options.near, | ||
node: this._options.node, | ||
index_hint: this._options.index_hint, | ||
orders, | ||
skip: this._options.skip, | ||
transaction: this._options.transaction, | ||
distinct: this._options.distinct, | ||
...(select_raw.length > 0 && { select, select_raw }), | ||
}; | ||
} | ||
@@ -710,3 +726,3 @@ _getAdapterDeleteOptions() { | ||
}); | ||
await this._connection.models._Archive.createBulk(archive_records); | ||
await this._connection.models._Archive?.createBulk(archive_records); | ||
} | ||
@@ -713,0 +729,0 @@ if (!need_integrity) { |
@@ -142,7 +142,7 @@ /** | ||
declare const CormoTypesText: CormoTypesTextConstructor; | ||
export declare type ColumnTypeInternal = CormoTypesString | CormoTypesNumber | CormoTypesBoolean | CormoTypesDate | CormoTypesObject | CormoTypesInteger | CormoTypesBigInteger | CormoTypesGeoPoint | CormoTypesRecordID | CormoTypesText; | ||
export declare type ColumnTypeInternalConstructor = CormoTypesStringConstructor | CormoTypesNumberConstructor | CormoTypesBooleanConstructor | CormoTypesDateConstructor | CormoTypesObjectConstructor | CormoTypesIntegerConstructor | CormoTypesBigIntegerConstructor | CormoTypesGeoPointConstructor | CormoTypesRecordIDConstructor | CormoTypesTextConstructor; | ||
declare type ColumnTypeNativeConstructor = StringConstructor | NumberConstructor | BooleanConstructor | DateConstructor | ObjectConstructor; | ||
declare type ColumnTypeString = 'string' | 'number' | 'boolean' | 'date' | 'object' | 'integer' | 'biginteger' | 'geopoint' | 'recordid' | 'text'; | ||
export declare type ColumnType = ColumnTypeInternal | ColumnTypeInternalConstructor | ColumnTypeNativeConstructor | ColumnTypeString; | ||
export type ColumnTypeInternal = CormoTypesString | CormoTypesNumber | CormoTypesBoolean | CormoTypesDate | CormoTypesObject | CormoTypesInteger | CormoTypesBigInteger | CormoTypesGeoPoint | CormoTypesRecordID | CormoTypesText; | ||
export type ColumnTypeInternalConstructor = CormoTypesStringConstructor | CormoTypesNumberConstructor | CormoTypesBooleanConstructor | CormoTypesDateConstructor | CormoTypesObjectConstructor | CormoTypesIntegerConstructor | CormoTypesBigIntegerConstructor | CormoTypesGeoPointConstructor | CormoTypesRecordIDConstructor | CormoTypesTextConstructor; | ||
type ColumnTypeNativeConstructor = StringConstructor | NumberConstructor | BooleanConstructor | DateConstructor | ObjectConstructor; | ||
type ColumnTypeString = 'string' | 'number' | 'boolean' | 'date' | 'object' | 'integer' | 'biginteger' | 'geopoint' | 'recordid' | 'text'; | ||
export type ColumnType = ColumnTypeInternal | ColumnTypeInternalConstructor | ColumnTypeNativeConstructor | ColumnTypeString; | ||
/** | ||
@@ -163,3 +163,3 @@ * Converts JavaScript built-in class to CORMO type | ||
*/ | ||
export declare type RecordID = string | number; | ||
export type RecordID = string | number; | ||
/** | ||
@@ -169,3 +169,3 @@ * A pseudo type represents an integer | ||
*/ | ||
export declare type Integer = number; | ||
export type Integer = number; | ||
/** | ||
@@ -175,3 +175,3 @@ * A pseudo type represents an big integer | ||
*/ | ||
export declare type BigInteger = number; | ||
export type BigInteger = number; | ||
/** | ||
@@ -181,2 +181,2 @@ * A pseudo type represents a two - dimensional point | ||
*/ | ||
export declare type GeoPoint = [number, number]; | ||
export type GeoPoint = [number, number]; |
@@ -12,3 +12,3 @@ /** | ||
*/ | ||
export declare function getLeafOfPath(obj: object, path: string | string[], create_object?: boolean): [object | undefined, string | undefined]; | ||
export declare function getLeafOfPath(obj: object | undefined, path: string | string[], create_object?: boolean): [object | undefined, string | undefined]; | ||
/** | ||
@@ -15,0 +15,0 @@ * Gets a value of object by path |
"use strict"; | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
@@ -6,0 +10,0 @@ if (k2 === undefined) k2 = k; |
{ | ||
"name": "cormo", | ||
"description": "ORM framework for Node.js", | ||
"version": "0.19.3", | ||
"version": "1.0.0", | ||
"keywords": [ | ||
@@ -40,2 +40,3 @@ "orm", | ||
"inflected": "^2.1.0", | ||
"ioredis": "^5.2.4", | ||
"lodash": "^4.17.21", | ||
@@ -46,27 +47,26 @@ "toposort-class": "^1.0.1", | ||
"devDependencies": { | ||
"@types/chai": "^4.3.0", | ||
"@types/chai": "^4.3.4", | ||
"@types/inflected": "^1.1.29", | ||
"@types/lodash": "^4.14.178", | ||
"@types/mocha": "^9.1.0", | ||
"@types/node": "^16.11.22", | ||
"@types/sinon": "^10.0.11", | ||
"@types/yargs": "^17.0.8", | ||
"@types/lodash": "^4.14.191", | ||
"@types/mocha": "^10.0.1", | ||
"@types/node": "^18.11.11", | ||
"@types/sinon": "^10.0.13", | ||
"@types/yargs": "^17.0.17", | ||
"benchmark": "^2.1.4", | ||
"chai": "^4.3.6", | ||
"chai": "^4.3.7", | ||
"coffee-coverage": "^3.0.1", | ||
"coffeescript": "^2.6.1", | ||
"mocha": "^9.2.0", | ||
"mongodb": "^4.1.4", | ||
"coffeescript": "^2.7.0", | ||
"mocha": "^10.1.0", | ||
"mongodb": "^4.3.1", | ||
"mysql": "^2.18.1", | ||
"mysql2": "^2.3.3", | ||
"pg": "^8.7.3", | ||
"pg-query-stream": "^4.2.3", | ||
"redis": "^3.1.2", | ||
"pg": "^8.8.0", | ||
"pg-query-stream": "^4.2.4", | ||
"rimraf": "^3.0.2", | ||
"sinon": "^13.0.1", | ||
"sqlite3": "^4.2.0", | ||
"ts-node": "^10.5.0", | ||
"typescript": "^4.5.5" | ||
"sinon": "^15.0.0", | ||
"sqlite3": "^5.1.2", | ||
"ts-node": "^10.9.1", | ||
"typescript": "^4.9.3" | ||
}, | ||
"gitHead": "0fc2a531808c22432a502dd536eae5cd8eaf0a40" | ||
"gitHead": "012c58745515c8b36ffdb14b772348705b8b7ab7" | ||
} |
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
380841
22
10435
1
6
7
+ Addedioredis@^5.2.4
+ Added@ioredis/commands@1.2.0(transitive)
+ Addedcluster-key-slot@1.1.2(transitive)
+ Addeddebug@4.3.4(transitive)
+ Addeddenque@2.1.0(transitive)
+ Addedioredis@5.4.1(transitive)
+ Addedlodash.defaults@4.2.0(transitive)
+ Addedlodash.isarguments@3.1.0(transitive)
+ Addedms@2.1.2(transitive)
+ Addedredis-errors@1.2.0(transitive)
+ Addedredis-parser@3.0.0(transitive)
+ Addedstandard-as-callback@2.1.0(transitive)