New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More →
Socket
Sign inDemoInstall
Socket

@spinajs/orm

Package Overview
Dependencies
Maintainers
1
Versions
375
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@spinajs/orm - npm Package Compare versions

Comparing version 2.0.46 to 2.0.48

lib/builders.d.ts.map

17

lib/builders.d.ts
import { Container, Constructor, IContainer } from '@spinajs/di';
import { ColumnType, QueryMethod, SordOrder, WhereBoolean, SqlOperator } from './enums';
import { IColumnsBuilder, ICompilerOutput, ILimitBuilder, IOrderByBuilder, IQueryBuilder, IQueryLimit, ISort, IWhereBuilder, QueryContext, IJoinBuilder, IBuilderMiddleware, IWithRecursiveBuilder, ReferentialAction, IGroupByBuilder, IUpdateResult, DefaultValueBuilder, ColumnAlterationType, QueryMiddleware } from './interfaces';
import { ColumnStatement, IQueryStatement, RawQueryStatement, Wrap } from './statements';
import { PartialModel, PickRelations, WhereFunction } from './types';
import { OrmDriver } from './driver';
import { ModelBase } from './model';
import { OrmRelation, IOrmRelation } from './relations';
import { ColumnType, QueryMethod, SordOrder, WhereBoolean, SqlOperator } from './enums.js';
import { IColumnsBuilder, ICompilerOutput, ILimitBuilder, IOrderByBuilder, IQueryBuilder, IQueryLimit, ISort, IWhereBuilder, QueryContext, IJoinBuilder, IBuilderMiddleware, IWithRecursiveBuilder, ReferentialAction, IGroupByBuilder, IUpdateResult, DefaultValueBuilder, ColumnAlterationType, QueryMiddleware } from './interfaces.js';
import { ColumnStatement, IQueryStatement, RawQueryStatement, Wrap } from './statements.js';
import { PartialModel, PickRelations, WhereFunction } from './types.js';
import { OrmDriver } from './driver.js';
import { ModelBase } from './model.js';
import { OrmRelation, IOrmRelation } from './relations.js';
import { DateTime } from 'luxon';

@@ -558,3 +558,3 @@ /**

*/
deepClone(srcTable: string, newTable: string, filter?: (query: SelectQueryBuilder) => void): Promise<any>;
deepClone(srcTable: string, newTable: string, filter?: (query: SelectQueryBuilder) => void): Promise<this>;
toDB(): ICompilerOutput[];

@@ -640,1 +640,2 @@ }

}
//# sourceMappingURL=builders.d.ts.map

@@ -1,18 +0,1 @@

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = 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) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {

@@ -24,32 +7,32 @@ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;

};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var RawQuery_1, WhereBuilder_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SchemaQueryBuilder = exports.ScheduleQueryBuilder = exports.DropEventQueryBuilder = exports.EventQueryBuilder = exports.EventIntervalDesc = exports.CloneTableQueryBuilder = exports.TruncateTableQueryBuilder = exports.TableQueryBuilder = exports.AlterTableQueryBuilder = exports.DropTableQueryBuilder = exports.TableExistsQueryBuilder = exports.AlterColumnQueryBuilder = exports.ColumnQueryBuilder = exports.ForeignKeyBuilder = exports.IndexQueryBuilder = exports.InsertQueryBuilder = exports.UpdateQueryBuilder = exports.OnDuplicateQueryBuilder = exports.DeleteQueryBuilder = exports.SelectQueryBuilderC = exports.SelectQueryBuilder = exports.WhereBuilder = exports.WithRecursiveBuilder = exports.JoinBuilder = exports.GroupByBuilder = exports.RawQuery = exports.ColumnsBuilder = exports.OrderByBuilder = exports.LimitBuilder = exports.QueryBuilder = exports.Builder = void 0;
var RawQuery_1, WhereBuilder_1, SelectQueryBuilder_1;
/* eslint-disable prettier/prettier */
const di_1 = require("@spinajs/di");
const exceptions_1 = require("@spinajs/exceptions");
const exceptions_2 = require("./exceptions");
const _ = __importStar(require("lodash"));
const typescript_mix_1 = require("typescript-mix");
const enums_1 = require("./enums");
const interfaces_1 = require("./interfaces");
const statements_1 = require("./statements");
const driver_1 = require("./driver");
const model_1 = require("./model");
const relations_1 = require("./relations");
const orm_1 = require("./orm");
import { Container, Inject, NewInstance, DI, Injectable } from '@spinajs/di';
import { InvalidArgument, MethodNotImplemented, InvalidOperation } from '../../exceptions/lib/index.js';
import { OrmException } from './exceptions.js';
import _ from 'lodash';
import { use } from 'typescript-mix';
import { ColumnMethods, ColumnType, QueryMethod, SordOrder, WhereBoolean, SqlOperator, JoinMethod } from './enums.js';
import { DeleteQueryCompiler, InsertQueryCompiler, SelectQueryCompiler, TruncateTableQueryCompiler, TableQueryCompiler, AlterTableQueryCompiler, UpdateQueryCompiler, QueryContext, IndexQueryCompiler, RelationType, ReferentialAction, DefaultValueBuilder, ColumnAlterationType, TableExistsCompiler, DropTableCompiler, TableCloneQueryCompiler, QueryMiddleware, DropEventQueryCompiler, EventQueryCompiler } from './interfaces.js';
import { BetweenStatement, ColumnMethodStatement, ColumnStatement, ExistsQueryStatement, InSetStatement, InStatement, RawQueryStatement, WhereQueryStatement, WhereStatement, ColumnRawStatement, JoinStatement, WithRecursiveStatement, GroupByStatement, Wrap } from './statements.js';
import { OrmDriver } from './driver.js';
import { extractModelDescriptor } from './model.js';
import { BelongsToRelation, OneToManyRelation, ManyToManyRelation, BelongsToRecursiveRelation } from './relations.js';
import { Orm } from './orm.js';
function isWhereOperator(val) {
return _.isString(val) && Object.values(enums_1.SqlOperator).includes(val.toLowerCase());
return _.isString(val) && Object.values(SqlOperator).includes(val.toLowerCase());
}
let Builder = class Builder {
get Driver() {
return this._driver;
}
get Container() {
return this._container;
}
get Model() {
return this._model;
}
constructor(container, driver, model) {

@@ -63,13 +46,4 @@ this._middlewares = [];

this._asRaw = false;
this._queryMiddlewares = di_1.DI.resolve(Array.ofType(interfaces_1.QueryMiddleware));
this._queryMiddlewares = DI.resolve(Array.ofType(QueryMiddleware));
}
get Driver() {
return this._driver;
}
get Container() {
return this._container;
}
get Model() {
return this._model;
}
then(onfulfilled, onrejected) {

@@ -149,11 +123,11 @@ const execute = (compiled) => {

toDB() {
throw new exceptions_1.MethodNotImplemented();
throw new MethodNotImplemented();
}
};
Builder = __decorate([
(0, di_1.NewInstance)(),
(0, di_1.Inject)(di_1.Container),
__metadata("design:paramtypes", [Object, driver_1.OrmDriver, Object])
NewInstance(),
Inject(Container),
__metadata("design:paramtypes", [Object, OrmDriver, Object])
], Builder);
exports.Builder = Builder;
export { Builder };
/**

@@ -198,3 +172,3 @@ * Base class for queires. Implements basic query functionality

if (!database) {
throw new exceptions_1.InvalidArgument(`schema argument cannot be null or empty`);
throw new InvalidArgument(`schema argument cannot be null or empty`);
}

@@ -217,3 +191,3 @@ this._database = database;

if (!table.trim()) {
throw new exceptions_1.InvalidArgument('table name is empty');
throw new InvalidArgument('table name is empty');
}

@@ -238,7 +212,7 @@ this._table = table;

QueryBuilder = __decorate([
(0, di_1.NewInstance)(),
(0, di_1.Inject)(di_1.Container),
__metadata("design:paramtypes", [Object, driver_1.OrmDriver, Object])
NewInstance(),
Inject(Container),
__metadata("design:paramtypes", [Object, OrmDriver, Object])
], QueryBuilder);
exports.QueryBuilder = QueryBuilder;
export { QueryBuilder };
let LimitBuilder = class LimitBuilder {

@@ -254,3 +228,3 @@ constructor() {

if (count <= 0) {
throw new exceptions_1.InvalidArgument(`take count cannot be negative number`);
throw new InvalidArgument(`take count cannot be negative number`);
}

@@ -262,3 +236,3 @@ this._limit.limit = count;

if (count < 0) {
throw new exceptions_1.InvalidArgument(`skip count cannot be negative number`);
throw new InvalidArgument(`skip count cannot be negative number`);
}

@@ -274,3 +248,3 @@ this._limit.offset = count;

async firstOrFail() {
return this.firstOrThrow(new exceptions_2.OrmException('not found'));
return this.firstOrThrow(new OrmException('not found'));
}

@@ -296,6 +270,6 @@ async orThrow(error) {

LimitBuilder = __decorate([
(0, di_1.NewInstance)(),
NewInstance(),
__metadata("design:paramtypes", [])
], LimitBuilder);
exports.LimitBuilder = LimitBuilder;
export { LimitBuilder };
let OrderByBuilder = class OrderByBuilder {

@@ -305,3 +279,3 @@ constructor() {

column: '',
order: enums_1.SordOrder.ASC,
order: SordOrder.ASC,
};

@@ -319,3 +293,3 @@ }

column,
order: enums_1.SordOrder.ASC,
order: SordOrder.ASC,
};

@@ -327,3 +301,3 @@ return this;

column,
order: enums_1.SordOrder.DESC,
order: SordOrder.DESC,
};

@@ -337,6 +311,6 @@ return this;

OrderByBuilder = __decorate([
(0, di_1.NewInstance)(),
NewInstance(),
__metadata("design:paramtypes", [])
], OrderByBuilder);
exports.OrderByBuilder = OrderByBuilder;
export { OrderByBuilder };
let ColumnsBuilder = class ColumnsBuilder {

@@ -359,5 +333,5 @@ constructor() {

columns(names) {
const descriptor = (0, model_1.extractModelDescriptor)(this._model);
const descriptor = extractModelDescriptor(this._model);
this._columns = names.map((n) => {
return this._container.resolve(statements_1.ColumnStatement, [n, null, this._tableAlias, descriptor === null || descriptor === void 0 ? void 0 : descriptor.Columns.find((c) => c.Name === n)]);
return this._container.resolve(ColumnStatement, [n, null, this._tableAlias, descriptor?.Columns.find((c) => c.Name === n)]);
});

@@ -367,13 +341,13 @@ return this;

select(column, alias) {
const descriptor = (0, model_1.extractModelDescriptor)(this._model);
const descriptor = extractModelDescriptor(this._model);
if (column instanceof Map) {
column.forEach((alias, colName) => {
this._columns.push(this._container.resolve(statements_1.ColumnStatement, [colName, alias, this._tableAlias, descriptor === null || descriptor === void 0 ? void 0 : descriptor.Columns.find((c) => c.Name === colName)]));
this._columns.push(this._container.resolve(ColumnStatement, [colName, alias, this._tableAlias, descriptor?.Columns.find((c) => c.Name === colName)]));
});
}
if (column instanceof RawQuery) {
this._columns.push(this._container.resolve(statements_1.ColumnRawStatement, [column, null, this._tableAlias]));
this._columns.push(this._container.resolve(ColumnRawStatement, [column, null, this._tableAlias]));
}
else {
this._columns.push(this._container.resolve(statements_1.ColumnStatement, [column, alias, this._tableAlias, descriptor === null || descriptor === void 0 ? void 0 : descriptor.Columns.find((c) => c.Name === column)]));
this._columns.push(this._container.resolve(ColumnStatement, [column, alias, this._tableAlias, descriptor?.Columns.find((c) => c.Name === column)]));
}

@@ -387,13 +361,7 @@ return this;

ColumnsBuilder = __decorate([
(0, di_1.NewInstance)(),
NewInstance(),
__metadata("design:paramtypes", [])
], ColumnsBuilder);
exports.ColumnsBuilder = ColumnsBuilder;
export { ColumnsBuilder };
let RawQuery = RawQuery_1 = class RawQuery {
constructor(query, bindings) {
this._query = '';
this._bindings = [];
this._query = query;
this._bindings = bindings;
}
get Query() {

@@ -408,9 +376,15 @@ return this._query;

}
constructor(query, bindings) {
this._query = '';
this._bindings = [];
this._query = query;
this._bindings = bindings;
}
};
RawQuery = RawQuery_1 = __decorate([
(0, di_1.NewInstance)(),
NewInstance(),
__metadata("design:paramtypes", [String, Array])
], RawQuery);
exports.RawQuery = RawQuery;
class GroupByBuilder {
export { RawQuery };
export class GroupByBuilder {
constructor() {

@@ -427,8 +401,10 @@ this._groupStatements = [];

groupBy(expression) {
this._groupStatements.push(this._container.resolve(statements_1.GroupByStatement, [expression]));
this._groupStatements.push(this._container.resolve(GroupByStatement, [expression]));
return this;
}
}
exports.GroupByBuilder = GroupByBuilder;
class JoinBuilder {
export class JoinBuilder {
get JoinStatements() {
return this._joinStatements;
}
constructor(container) {

@@ -439,5 +415,2 @@ this._joinStatements = [];

}
get JoinStatements() {
return this._joinStatements;
}
clearJoins() {

@@ -448,27 +421,27 @@ this._joinStatements = [];

innerJoin(_table, _AliasOrForeignKey, _fkOrPkKey, _primaryKey) {
this.addJoinStatement.call(this, enums_1.JoinMethod.INNER, ...arguments);
this.addJoinStatement.call(this, JoinMethod.INNER, ...arguments);
return this;
}
leftJoin(_table, _AliasOrForeignKey, _fkOrPkKey, _primaryKey) {
this.addJoinStatement.call(this, enums_1.JoinMethod.LEFT, ...arguments);
this.addJoinStatement.call(this, JoinMethod.LEFT, ...arguments);
return this;
}
leftOuterJoin(_table, _AliasOrForeignKey, _fkOrPkKey, _primaryKey) {
this.addJoinStatement.call(this, enums_1.JoinMethod.LEFT_OUTER, ...arguments);
this.addJoinStatement.call(this, JoinMethod.LEFT_OUTER, ...arguments);
return this;
}
rightJoin(_table, _AliasOrForeignKey, _fkOrPkKey, _primaryKey) {
this.addJoinStatement.call(this, enums_1.JoinMethod.RIGHT, ...arguments);
this.addJoinStatement.call(this, JoinMethod.RIGHT, ...arguments);
return this;
}
rightOuterJoin(_table, _AliasOrForeignKey, _fkOrPkKey, _primaryKey) {
this.addJoinStatement.call(this, enums_1.JoinMethod.RIGHT_OUTER, ...arguments);
this.addJoinStatement.call(this, JoinMethod.RIGHT_OUTER, ...arguments);
return this;
}
fullOuterJoin(_table, _AliasOrForeignKey, _fkOrPkKey, _primaryKey) {
this.addJoinStatement.call(this, enums_1.JoinMethod.FULL_OUTER, ...arguments);
this.addJoinStatement.call(this, JoinMethod.FULL_OUTER, ...arguments);
return this;
}
crossJoin(_table, _AliasOrForeignKey, _fkOrPkKey, _primaryKey) {
this.addJoinStatement.call(this, enums_1.JoinMethod.CROSS, ...arguments);
this.addJoinStatement.call(this, JoinMethod.CROSS, ...arguments);
return this;

@@ -479,12 +452,12 @@ }

if (arguments.length === 3) {
stmt = this._container.resolve(statements_1.JoinStatement, [this, this._model, table, method, AliasOrForeignKey]);
stmt = this._container.resolve(JoinStatement, [this, this._model, table, method, AliasOrForeignKey]);
}
else if (arguments.length === 4) {
stmt = this._container.resolve(statements_1.JoinStatement, [this, this._model, table, method, AliasOrForeignKey, fkOrPkKey, null, this._tableAlias]);
stmt = this._container.resolve(JoinStatement, [this, this._model, table, method, AliasOrForeignKey, fkOrPkKey, null, this._tableAlias]);
}
else if (arguments.length === 5) {
stmt = this._container.resolve(statements_1.JoinStatement, [this, this._model, table, method, fkOrPkKey, primaryKey, AliasOrForeignKey, this._tableAlias]);
stmt = this._container.resolve(JoinStatement, [this, this._model, table, method, fkOrPkKey, primaryKey, AliasOrForeignKey, this._tableAlias]);
}
else {
stmt = this._container.resolve(statements_1.JoinStatement, [this, this._model, table, method]);
stmt = this._container.resolve(JoinStatement, [this, this._model, table, method]);
}

@@ -494,3 +467,2 @@ this.JoinStatements.push(stmt);

}
exports.JoinBuilder = JoinBuilder;
let WithRecursiveBuilder = class WithRecursiveBuilder {

@@ -501,3 +473,3 @@ get CteRecursive() {

withRecursive(rcKeyName, pkName) {
this._cteStatement = this._container.resolve(statements_1.WithRecursiveStatement, ['cte', this, rcKeyName, pkName]);
this._cteStatement = this._container.resolve(WithRecursiveStatement, ['cte', this, rcKeyName, pkName]);
return this;

@@ -507,20 +479,20 @@ }

WithRecursiveBuilder = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], WithRecursiveBuilder);
exports.WithRecursiveBuilder = WithRecursiveBuilder;
export { WithRecursiveBuilder };
let WhereBuilder = WhereBuilder_1 = class WhereBuilder {
get Statements() {
return this._statements;
}
get Op() {
return this._boolean;
}
constructor(container, tableAlias) {
this._statements = [];
this._boolean = enums_1.WhereBoolean.AND;
this._boolean = WhereBoolean.AND;
this._container = container;
this._boolean = enums_1.WhereBoolean.AND;
this._boolean = WhereBoolean.AND;
this._statements = [];
this._tableAlias = tableAlias;
}
get Statements() {
return this._statements;
}
get Op() {
return this._boolean;
}
where(column, operator, value) {

@@ -533,3 +505,3 @@ const self = this;

if (column instanceof RawQuery) {
this.Statements.push(this._container.resolve(statements_1.RawQueryStatement, [column.Query, column.Bindings, self._tableAlias]));
this.Statements.push(this._container.resolve(RawQueryStatement, [column.Query, column.Bindings, self._tableAlias]));
return this;

@@ -541,7 +513,7 @@ }

column.call(builder);
self.Statements.push(this._container.resolve(statements_1.WhereQueryStatement, [builder, self._tableAlias]));
self.Statements.push(this._container.resolve(WhereQueryStatement, [builder, self._tableAlias]));
return this;
}
// handle simple key = object[key] AND ....
if (_.isObject(column) && !(column instanceof statements_1.Wrap)) {
if (_.isObject(column) && !(column instanceof Wrap)) {
return this.whereObject(column);

@@ -560,6 +532,6 @@ }

if (sVal === undefined) {
throw new exceptions_1.InvalidArgument(`value cannot be undefined`);
throw new InvalidArgument(`value cannot be undefined`);
}
if (!_.isString(c) && !(c instanceof statements_1.Wrap)) {
throw new exceptions_1.InvalidArgument(`column is not of type string or wrapped.`);
if (!_.isString(c) && !(c instanceof Wrap)) {
throw new InvalidArgument(`column is not of type string or wrapped.`);
}

@@ -569,3 +541,3 @@ if (sVal === null) {

}
self._statements.push(self._container.resolve(statements_1.WhereStatement, [c, enums_1.SqlOperator.EQ, sVal, self._tableAlias, this._container, self._model]));
self._statements.push(self._container.resolve(WhereStatement, [c, SqlOperator.EQ, sVal, self._tableAlias, this._container, self._model]));
return self;

@@ -580,6 +552,6 @@ }

if (!isWhereOperator(o)) {
throw new exceptions_1.InvalidArgument(`operator ${o} is invalid`);
throw new InvalidArgument(`operator ${o} is invalid`);
}
if (!_.isString(c) && !(c instanceof statements_1.Wrap)) {
throw new exceptions_1.InvalidArgument(`column is not of type string or wrapped.`);
if (!_.isString(c) && !(c instanceof Wrap)) {
throw new InvalidArgument(`column is not of type string or wrapped.`);
}

@@ -590,5 +562,5 @@ if (sVal === null) {

if (sVal === null) {
return o === enums_1.SqlOperator.NOT_NULL ? this.whereNotNull(c) : this.whereNull(c);
return o === SqlOperator.NOT_NULL ? this.whereNotNull(c) : this.whereNull(c);
}
self._statements.push(self._container.resolve(statements_1.WhereStatement, [c, o, sVal, self._tableAlias, this._container, self._model]));
self._statements.push(self._container.resolve(WhereStatement, [c, o, sVal, self._tableAlias, this._container, self._model]));
return this;

@@ -598,7 +570,7 @@ }

orWhere(column, ..._args) {
this._boolean = enums_1.WhereBoolean.OR;
this._boolean = WhereBoolean.OR;
return this.where(column, ...Array.from(arguments).slice(1));
}
andWhere(column, ..._args) {
this._boolean = enums_1.WhereBoolean.AND;
this._boolean = WhereBoolean.AND;
return this.where(column, ...Array.from(arguments).slice(1));

@@ -608,3 +580,3 @@ }

for (const key of Object.keys(obj)) {
this.andWhere(key, enums_1.SqlOperator.EQ, obj[key]);
this.andWhere(key, SqlOperator.EQ, obj[key]);
}

@@ -614,42 +586,42 @@ return this;

whereNotNull(column) {
this._statements.push(this._container.resolve(statements_1.WhereStatement, [column, enums_1.SqlOperator.NOT_NULL, null, this._tableAlias, this._container]));
this._statements.push(this._container.resolve(WhereStatement, [column, SqlOperator.NOT_NULL, null, this._tableAlias, this._container]));
return this;
}
whereNull(column) {
this._statements.push(this._container.resolve(statements_1.WhereStatement, [column, enums_1.SqlOperator.NULL, null, this._tableAlias, this._container]));
this._statements.push(this._container.resolve(WhereStatement, [column, SqlOperator.NULL, null, this._tableAlias, this._container]));
return this;
}
whereNot(column, val) {
return this.where(column, enums_1.SqlOperator.NOT, val);
return this.where(column, SqlOperator.NOT, val);
}
whereIn(column, val) {
this._statements.push(this._container.resolve(statements_1.InStatement, [column, val, false, this._tableAlias, this._container]));
this._statements.push(this._container.resolve(InStatement, [column, val, false, this._tableAlias, this._container]));
return this;
}
whereNotIn(column, val) {
this._statements.push(this._container.resolve(statements_1.InStatement, [column, val, true, this._tableAlias, this._container]));
this._statements.push(this._container.resolve(InStatement, [column, val, true, this._tableAlias, this._container]));
return this;
}
whereExist(query) {
this._statements.push(this._container.resolve(statements_1.ExistsQueryStatement, [query, false]));
this._statements.push(this._container.resolve(ExistsQueryStatement, [query, false]));
return this;
}
whereNotExists(query) {
this._statements.push(this._container.resolve(statements_1.ExistsQueryStatement, [query, true]));
this._statements.push(this._container.resolve(ExistsQueryStatement, [query, true]));
return this;
}
whereBetween(column, val) {
this._statements.push(this._container.resolve(statements_1.BetweenStatement, [column, val, false, this._tableAlias]));
this._statements.push(this._container.resolve(BetweenStatement, [column, val, false, this._tableAlias]));
return this;
}
whereNotBetween(column, val) {
this._statements.push(this._container.resolve(statements_1.BetweenStatement, [column, val, true, this._tableAlias]));
this._statements.push(this._container.resolve(BetweenStatement, [column, val, true, this._tableAlias]));
return this;
}
whereInSet(column, val) {
this._statements.push(this._container.resolve(statements_1.InSetStatement, [column, val, false, this._tableAlias]));
this._statements.push(this._container.resolve(InSetStatement, [column, val, false, this._tableAlias]));
return this;
}
whereNotInSet(column, val) {
this._statements.push(this._container.resolve(statements_1.InSetStatement, [column, val, true, this._tableAlias]));
this._statements.push(this._container.resolve(InSetStatement, [column, val, true, this._tableAlias]));
return this;

@@ -663,7 +635,16 @@ }

WhereBuilder = WhereBuilder_1 = __decorate([
(0, di_1.NewInstance)(),
__metadata("design:paramtypes", [di_1.Container, String])
NewInstance(),
__metadata("design:paramtypes", [Container, String])
], WhereBuilder);
exports.WhereBuilder = WhereBuilder;
class SelectQueryBuilder extends QueryBuilder {
export { WhereBuilder };
let SelectQueryBuilder = SelectQueryBuilder_1 = class SelectQueryBuilder extends QueryBuilder {
get Owner() {
return this._owner;
}
get IsDistinct() {
return this._distinct;
}
get Relations() {
return this._relations;
}
constructor(container, driver, model, owner) {

@@ -681,7 +662,7 @@ super(container, driver, model);

this._distinct = false;
this._method = enums_1.QueryMethod.SELECT;
this._boolean = enums_1.WhereBoolean.AND;
this._method = QueryMethod.SELECT;
this._boolean = WhereBoolean.AND;
this._sort = {
column: '',
order: enums_1.SordOrder.ASC,
order: SordOrder.ASC,
};

@@ -694,14 +675,5 @@ this._first = false;

this._nonSelect = false;
this.QueryContext = interfaces_1.QueryContext.Select;
this.QueryContext = QueryContext.Select;
this._queryMiddlewares.forEach((x) => x.afterQueryCreation(this));
}
get Owner() {
return this._owner;
}
get IsDistinct() {
return this._distinct;
}
get Relations() {
return this._relations;
}
async asRaw() {

@@ -719,8 +691,8 @@ this._asRaw = true;

clone() {
const builder = new SelectQueryBuilder(this._container, this._driver, this._model, this._owner);
const builder = new SelectQueryBuilder_1(this._container, this._driver, this._model, this._owner);
builder._columns = this._columns.slice(0);
builder._joinStatements = this._joinStatements.slice(0);
builder._statements = this._statements.slice(0);
builder._limit = Object.assign({}, this._limit);
builder._sort = Object.assign({}, this._sort);
builder._limit = { ...this._limit };
builder._sort = { ...this._sort };
builder._boolean = this._boolean;

@@ -733,3 +705,2 @@ builder._distinct = this._distinct;

populate(relation, callback) {
var _a;
// if relation was already populated, just call callback on it

@@ -742,23 +713,23 @@ const fRelation = this._relations.find((r) => r.Name === relation);

let relInstance = null;
const descriptor = (0, model_1.extractModelDescriptor)(this._model);
const descriptor = extractModelDescriptor(this._model);
if (!descriptor.Relations.has(relation)) {
throw new exceptions_1.InvalidArgument(`Relation ${relation} not exists in model ${(_a = this._model) === null || _a === void 0 ? void 0 : _a.constructor.name}`);
throw new InvalidArgument(`Relation ${relation} not exists in model ${this._model?.constructor.name}`);
}
const relDescription = descriptor.Relations.get(relation);
if (relDescription.Type === interfaces_1.RelationType.One && relDescription.Recursive) {
relInstance = this._container.resolve(relations_1.BelongsToRecursiveRelation, [this._container.get(orm_1.Orm), this, relDescription, this._owner]);
if (relDescription.Type === RelationType.One && relDescription.Recursive) {
relInstance = this._container.resolve(BelongsToRecursiveRelation, [this._container.get(Orm), this, relDescription, this._owner]);
}
else {
if (relDescription.Recursive) {
throw new exceptions_1.InvalidOperation(`cannot mark relation as recursive with non one-to-one relation type`);
throw new InvalidOperation(`cannot mark relation as recursive with non one-to-one relation type`);
}
switch (relDescription.Type) {
case interfaces_1.RelationType.One:
relInstance = this._container.resolve(relations_1.BelongsToRelation, [this._container.get(orm_1.Orm), this, relDescription, this._owner]);
case RelationType.One:
relInstance = this._container.resolve(BelongsToRelation, [this._container.get(Orm), this, relDescription, this._owner]);
break;
case interfaces_1.RelationType.Many:
relInstance = this._container.resolve(relations_1.OneToManyRelation, [this._container.get(orm_1.Orm), this, relDescription, this._owner]);
case RelationType.Many:
relInstance = this._container.resolve(OneToManyRelation, [this._container.get(Orm), this, relDescription, this._owner]);
break;
case interfaces_1.RelationType.ManyToMany:
relInstance = this._container.resolve(relations_1.ManyToManyRelation, [this._container.get(orm_1.Orm), this, relDescription, null]);
case RelationType.ManyToMany:
relInstance = this._container.resolve(ManyToManyRelation, [this._container.get(Orm), this, relDescription, null]);
break;

@@ -780,19 +751,19 @@ }

min(column, as) {
this._columns.push(this._container.resolve(statements_1.ColumnMethodStatement, [column, enums_1.ColumnMethods.MIN, as, this._tableAlias]));
this._columns.push(this._container.resolve(ColumnMethodStatement, [column, ColumnMethods.MIN, as, this._tableAlias]));
return this;
}
max(column, as) {
this._columns.push(this._container.resolve(statements_1.ColumnMethodStatement, [column, enums_1.ColumnMethods.MAX, as, this._tableAlias]));
this._columns.push(this._container.resolve(ColumnMethodStatement, [column, ColumnMethods.MAX, as, this._tableAlias]));
return this;
}
count(column, as) {
this._columns.push(this._container.resolve(statements_1.ColumnMethodStatement, [column, enums_1.ColumnMethods.COUNT, as, this._tableAlias]));
this._columns.push(this._container.resolve(ColumnMethodStatement, [column, ColumnMethods.COUNT, as, this._tableAlias]));
return this;
}
sum(column, as) {
this._columns.push(this._container.resolve(statements_1.ColumnMethodStatement, [column, enums_1.ColumnMethods.SUM, as, this._tableAlias]));
this._columns.push(this._container.resolve(ColumnMethodStatement, [column, ColumnMethods.SUM, as, this._tableAlias]));
return this;
}
avg(column, as) {
this._columns.push(this._container.resolve(statements_1.ColumnMethodStatement, [column, enums_1.ColumnMethods.AVG, as, this._tableAlias]));
this._columns.push(this._container.resolve(ColumnMethodStatement, [column, ColumnMethods.AVG, as, this._tableAlias]));
return this;

@@ -802,3 +773,3 @@ }

if (this._columns.length === 0 || this._columns[0].IsWildcard) {
throw new exceptions_1.InvalidOperation('Cannot force DISTINCT on unknown column');
throw new InvalidOperation('Cannot force DISTINCT on unknown column');
}

@@ -809,3 +780,3 @@ this._distinct = true;

toDB() {
const compiler = this._container.resolve(interfaces_1.SelectQueryCompiler, [this]);
const compiler = this._container.resolve(SelectQueryCompiler, [this]);
return compiler.compile();

@@ -836,17 +807,20 @@ }

}
}
};
__decorate([
(0, typescript_mix_1.use)(WhereBuilder, LimitBuilder, OrderByBuilder, ColumnsBuilder, JoinBuilder, WithRecursiveBuilder, GroupByBuilder),
use(WhereBuilder, LimitBuilder, OrderByBuilder, ColumnsBuilder, JoinBuilder, WithRecursiveBuilder, GroupByBuilder),
__metadata("design:type", Object)
], SelectQueryBuilder.prototype, "this", void 0);
exports.SelectQueryBuilder = SelectQueryBuilder;
class SelectQueryBuilderC extends SelectQueryBuilder {
SelectQueryBuilder = SelectQueryBuilder_1 = __decorate([
Injectable(SelectQueryBuilder_1),
__metadata("design:paramtypes", [Object, OrmDriver, Object, Object])
], SelectQueryBuilder);
export { SelectQueryBuilder };
export class SelectQueryBuilderC extends SelectQueryBuilder {
}
exports.SelectQueryBuilderC = SelectQueryBuilderC;
class DeleteQueryBuilder extends QueryBuilder {
export class DeleteQueryBuilder extends QueryBuilder {
constructor(container, driver, model) {
super(container, driver, model);
this._method = enums_1.QueryMethod.DELETE;
this._method = QueryMethod.DELETE;
this._statements = [];
this._boolean = enums_1.WhereBoolean.AND;
this._boolean = WhereBoolean.AND;
this._limit = {

@@ -856,14 +830,15 @@ limit: -1,

};
this.QueryContext = interfaces_1.QueryContext.Delete;
this.QueryContext = QueryContext.Delete;
}
toDB() {
return this._container.resolve(interfaces_1.DeleteQueryCompiler, [this]).compile();
return this._container.resolve(DeleteQueryCompiler, [this]).compile();
}
}
__decorate([
(0, typescript_mix_1.use)(WhereBuilder, LimitBuilder),
use(WhereBuilder, LimitBuilder)
/// @ts-ignore
,
__metadata("design:type", Object)
], DeleteQueryBuilder.prototype, "this", void 0);
exports.DeleteQueryBuilder = DeleteQueryBuilder;
class OnDuplicateQueryBuilder {
export class OnDuplicateQueryBuilder {
constructor(container, insertQueryBuilder, column) {

@@ -894,15 +869,14 @@ this._parent = insertQueryBuilder;

}
exports.OnDuplicateQueryBuilder = OnDuplicateQueryBuilder;
class UpdateQueryBuilder extends QueryBuilder {
export class UpdateQueryBuilder extends QueryBuilder {
get Value() {
return this._value;
}
constructor(container, driver, model) {
super(container, driver, model);
this._value = {};
this._method = enums_1.QueryMethod.UPDATE;
this._boolean = enums_1.WhereBoolean.AND;
this._method = QueryMethod.UPDATE;
this._boolean = WhereBoolean.AND;
this._statements = [];
this.QueryContext = interfaces_1.QueryContext.Update;
this.QueryContext = QueryContext.Update;
}
get Value() {
return this._value;
}
in(name) {

@@ -917,18 +891,10 @@ this.setTable(name);

toDB() {
return this._container.resolve(interfaces_1.UpdateQueryCompiler, [this]).compile();
return this._container.resolve(UpdateQueryCompiler, [this]).compile();
}
}
__decorate([
(0, typescript_mix_1.use)(WhereBuilder),
use(WhereBuilder),
__metadata("design:type", Object)
], UpdateQueryBuilder.prototype, "this", void 0);
exports.UpdateQueryBuilder = UpdateQueryBuilder;
class InsertQueryBuilder extends QueryBuilder {
constructor(container, driver, model) {
super(container, driver, model);
this._method = enums_1.QueryMethod.INSERT;
this._columns = [];
this._values = [];
this.QueryContext = interfaces_1.QueryContext.Insert;
}
export class InsertQueryBuilder extends QueryBuilder {
get Values() {

@@ -946,2 +912,9 @@ return this._values;

}
constructor(container, driver, model) {
super(container, driver, model);
this._method = QueryMethod.INSERT;
this._columns = [];
this._values = [];
this.QueryContext = QueryContext.Insert;
}
/**

@@ -991,3 +964,3 @@ * Sets insert to ignore on duplicate

if (!columnToCheck && this._model) {
const dsc = (0, model_1.extractModelDescriptor)(this._model);
const dsc = extractModelDescriptor(this._model);
columnToCheck = dsc.Columns.filter((c) => c.Unique).map((c) => c.Name);

@@ -1000,14 +973,13 @@ }

toDB() {
return this._container.resolve(interfaces_1.InsertQueryCompiler, [this]).compile();
return this._container.resolve(InsertQueryCompiler, [this]).compile();
}
}
__decorate([
(0, typescript_mix_1.use)(ColumnsBuilder),
use(ColumnsBuilder),
__metadata("design:type", Object)
], InsertQueryBuilder.prototype, "this", void 0);
exports.InsertQueryBuilder = InsertQueryBuilder;
let IndexQueryBuilder = class IndexQueryBuilder extends Builder {
constructor(container, driver) {
super(container, driver);
this.QueryContext = interfaces_1.QueryContext.Schema;
this.QueryContext = QueryContext.Schema;
}

@@ -1031,15 +1003,15 @@ name(name) {

toDB() {
return this._container.resolve(interfaces_1.IndexQueryCompiler, [this]).compile();
return this._container.resolve(IndexQueryCompiler, [this]).compile();
}
};
IndexQueryBuilder = __decorate([
(0, di_1.NewInstance)(),
(0, di_1.Inject)(di_1.Container),
__metadata("design:paramtypes", [di_1.Container, driver_1.OrmDriver])
NewInstance(),
Inject(Container),
__metadata("design:paramtypes", [Container, OrmDriver])
], IndexQueryBuilder);
exports.IndexQueryBuilder = IndexQueryBuilder;
export { IndexQueryBuilder };
let ForeignKeyBuilder = class ForeignKeyBuilder {
constructor() {
this.OnDeleteAction = interfaces_1.ReferentialAction.NoAction;
this.OnUpdateAction = interfaces_1.ReferentialAction.NoAction;
this.OnDeleteAction = ReferentialAction.NoAction;
this.OnUpdateAction = ReferentialAction.NoAction;
}

@@ -1092,4 +1064,4 @@ /**

cascade() {
this.OnUpdateAction = interfaces_1.ReferentialAction.Cascade;
this.OnDeleteAction = interfaces_1.ReferentialAction.Cascade;
this.OnUpdateAction = ReferentialAction.Cascade;
this.OnDeleteAction = ReferentialAction.Cascade;
return this;

@@ -1099,6 +1071,6 @@ }

ForeignKeyBuilder = __decorate([
(0, di_1.NewInstance)(),
NewInstance(),
__metadata("design:paramtypes", [])
], ForeignKeyBuilder);
exports.ForeignKeyBuilder = ForeignKeyBuilder;
export { ForeignKeyBuilder };
let ColumnQueryBuilder = class ColumnQueryBuilder {

@@ -1136,3 +1108,3 @@ constructor(container, name, type, ...args) {

default() {
this.Default = this.container.resolve((interfaces_1.DefaultValueBuilder), [this]);
this.Default = this.container.resolve((DefaultValueBuilder), [this]);
return this.Default;

@@ -1158,7 +1130,7 @@ }

ColumnQueryBuilder = __decorate([
(0, di_1.NewInstance)(),
(0, di_1.Inject)(di_1.Container),
NewInstance(),
Inject(Container),
__metadata("design:paramtypes", [Object, String, String, Object])
], ColumnQueryBuilder);
exports.ColumnQueryBuilder = ColumnQueryBuilder;
export { ColumnQueryBuilder };
let AlterColumnQueryBuilder = class AlterColumnQueryBuilder extends ColumnQueryBuilder {

@@ -1169,14 +1141,14 @@ constructor(container, name, type, ...args) {

// we assume add by default
this.AlterType = interfaces_1.ColumnAlterationType.Add;
this.AlterType = ColumnAlterationType.Add;
}
addColumn() {
this.AlterType = interfaces_1.ColumnAlterationType.Add;
this.AlterType = ColumnAlterationType.Add;
return this;
}
modify() {
this.AlterType = interfaces_1.ColumnAlterationType.Modify;
this.AlterType = ColumnAlterationType.Modify;
return this;
}
rename(newName) {
this.AlterType = interfaces_1.ColumnAlterationType.Rename;
this.AlterType = ColumnAlterationType.Rename;
this.Name = newName;

@@ -1191,18 +1163,17 @@ return this;

AlterColumnQueryBuilder = __decorate([
(0, di_1.Inject)(di_1.Container),
Inject(Container),
__metadata("design:paramtypes", [Object, String, String, Object])
], AlterColumnQueryBuilder);
exports.AlterColumnQueryBuilder = AlterColumnQueryBuilder;
class TableExistsQueryBuilder extends QueryBuilder {
export { AlterColumnQueryBuilder };
export class TableExistsQueryBuilder extends QueryBuilder {
constructor(container, driver, name) {
super(container, driver, null);
this.setTable(name);
this.QueryContext = interfaces_1.QueryContext.Select;
this.QueryContext = QueryContext.Select;
}
toDB() {
return this._container.resolve(interfaces_1.TableExistsCompiler, [this]).compile();
return this._container.resolve(TableExistsCompiler, [this]).compile();
}
}
exports.TableExistsQueryBuilder = TableExistsQueryBuilder;
class DropTableQueryBuilder extends QueryBuilder {
export class DropTableQueryBuilder extends QueryBuilder {
constructor(container, driver, name, database) {

@@ -1215,3 +1186,3 @@ super(container, driver, null);

this.Exists = false;
this.QueryContext = interfaces_1.QueryContext.Schema;
this.QueryContext = QueryContext.Schema;
}

@@ -1223,17 +1194,16 @@ ifExists() {

toDB() {
return this._container.resolve(interfaces_1.DropTableCompiler, [this]).compile();
return this._container.resolve(DropTableCompiler, [this]).compile();
}
}
exports.DropTableQueryBuilder = DropTableQueryBuilder;
class AlterTableQueryBuilder extends QueryBuilder {
export class AlterTableQueryBuilder extends QueryBuilder {
get Columns() {
return this._columns;
}
constructor(container, driver, name) {
super(container, driver, null);
this.setTable(name);
this.QueryContext = interfaces_1.QueryContext.Schema;
this.QueryContext = QueryContext.Schema;
this._columns = [];
this.DroppedColumns = [];
}
get Columns() {
return this._columns;
}
/**

@@ -1251,18 +1221,6 @@ * Renames table

toDB() {
return this._container.resolve(interfaces_1.AlterTableQueryCompiler, [this]).compile();
return this._container.resolve(AlterTableQueryCompiler, [this]).compile();
}
}
exports.AlterTableQueryBuilder = AlterTableQueryBuilder;
class TableQueryBuilder extends QueryBuilder {
constructor(container, driver, name) {
super(container, driver, null);
this._charset = '';
this._comment = '';
this._columns = [];
this._foreignKeys = [];
this._temporary = false;
this._trackHistory = false;
this.setTable(name);
this.QueryContext = interfaces_1.QueryContext.Schema;
}
export class TableQueryBuilder extends QueryBuilder {
/**

@@ -1308,2 +1266,13 @@ * Alias for string(name, 36 )

}
constructor(container, driver, name) {
super(container, driver, null);
this._charset = '';
this._comment = '';
this._columns = [];
this._foreignKeys = [];
this._temporary = false;
this._trackHistory = false;
this.setTable(name);
this.QueryContext = QueryContext.Schema;
}
increments(name) {

@@ -1325,6 +1294,5 @@ return this.int(name).autoIncrement().notNull().primaryKey();

toDB() {
return this._container.resolve(interfaces_1.TableQueryCompiler, [this]).compile();
return this._container.resolve(TableQueryCompiler, [this]).compile();
}
}
exports.TableQueryBuilder = TableQueryBuilder;
let TruncateTableQueryBuilder = class TruncateTableQueryBuilder extends QueryBuilder {

@@ -1337,20 +1305,12 @@ constructor(container, driver) {

toDB() {
return this._container.resolve(interfaces_1.TruncateTableQueryCompiler, [this]).compile();
return this._container.resolve(TruncateTableQueryCompiler, [this]).compile();
}
};
TruncateTableQueryBuilder = __decorate([
(0, di_1.NewInstance)(),
(0, di_1.Inject)(di_1.Container),
__metadata("design:paramtypes", [di_1.Container, driver_1.OrmDriver])
NewInstance(),
Inject(Container),
__metadata("design:paramtypes", [Container, OrmDriver])
], TruncateTableQueryBuilder);
exports.TruncateTableQueryBuilder = TruncateTableQueryBuilder;
export { TruncateTableQueryBuilder };
let CloneTableQueryBuilder = class CloneTableQueryBuilder extends QueryBuilder {
constructor(container, driver) {
super(container, driver);
this.container = container;
this.driver = driver;
this._shallow = true;
this._cloneSrc = '';
this._temporary = false;
}
get CloneSource() {

@@ -1368,2 +1328,10 @@ return this._cloneSrc;

}
constructor(container, driver) {
super(container, driver);
this.container = container;
this.driver = driver;
this._shallow = true;
this._cloneSrc = '';
this._temporary = false;
}
/**

@@ -1400,14 +1368,13 @@ * Clones table structure without data

toDB() {
return this._container.resolve(interfaces_1.TableCloneQueryCompiler, [this]).compile();
return this._container.resolve(TableCloneQueryCompiler, [this]).compile();
}
};
CloneTableQueryBuilder = __decorate([
(0, di_1.NewInstance)(),
(0, di_1.Inject)(di_1.Container),
__metadata("design:paramtypes", [di_1.Container, driver_1.OrmDriver])
NewInstance(),
Inject(Container),
__metadata("design:paramtypes", [Container, OrmDriver])
], CloneTableQueryBuilder);
exports.CloneTableQueryBuilder = CloneTableQueryBuilder;
class EventIntervalDesc {
export { CloneTableQueryBuilder };
export class EventIntervalDesc {
}
exports.EventIntervalDesc = EventIntervalDesc;
let EventQueryBuilder = class EventQueryBuilder extends QueryBuilder {

@@ -1448,3 +1415,3 @@ constructor(container, driver, Name) {

do(sql) {
if (sql instanceof statements_1.RawQueryStatement) {
if (sql instanceof RawQueryStatement) {
this.RawSql = sql;

@@ -1469,11 +1436,11 @@ }

toDB() {
return this._container.resolve(interfaces_1.EventQueryCompiler, [this]).compile();
return this._container.resolve(EventQueryCompiler, [this]).compile();
}
};
EventQueryBuilder = __decorate([
(0, di_1.NewInstance)(),
(0, di_1.Inject)(di_1.Container),
__metadata("design:paramtypes", [di_1.Container, driver_1.OrmDriver, String])
NewInstance(),
Inject(Container),
__metadata("design:paramtypes", [Container, OrmDriver, String])
], EventQueryBuilder);
exports.EventQueryBuilder = EventQueryBuilder;
export { EventQueryBuilder };
let DropEventQueryBuilder = class DropEventQueryBuilder extends QueryBuilder {

@@ -1487,11 +1454,11 @@ constructor(container, driver, Name) {

toDB() {
return this._container.resolve(interfaces_1.DropEventQueryCompiler, [this]).compile();
return this._container.resolve(DropEventQueryCompiler, [this]).compile();
}
};
DropEventQueryBuilder = __decorate([
(0, di_1.NewInstance)(),
(0, di_1.Inject)(di_1.Container),
__metadata("design:paramtypes", [di_1.Container, driver_1.OrmDriver, String])
NewInstance(),
Inject(Container),
__metadata("design:paramtypes", [Container, OrmDriver, String])
], DropEventQueryBuilder);
exports.DropEventQueryBuilder = DropEventQueryBuilder;
export { DropEventQueryBuilder };
/**

@@ -1517,7 +1484,7 @@ * Creates schedule job in database engine.

ScheduleQueryBuilder = __decorate([
(0, di_1.NewInstance)(),
(0, di_1.Inject)(di_1.Container),
__metadata("design:paramtypes", [di_1.Container, driver_1.OrmDriver])
NewInstance(),
Inject(Container),
__metadata("design:paramtypes", [Container, OrmDriver])
], ScheduleQueryBuilder);
exports.ScheduleQueryBuilder = ScheduleQueryBuilder;
export { ScheduleQueryBuilder };
let SchemaQueryBuilder = class SchemaQueryBuilder {

@@ -1562,8 +1529,8 @@ constructor(container, driver) {

SchemaQueryBuilder = __decorate([
(0, di_1.NewInstance)(),
(0, di_1.Inject)(di_1.Container),
__metadata("design:paramtypes", [di_1.Container, driver_1.OrmDriver])
NewInstance(),
Inject(Container),
__metadata("design:paramtypes", [Container, OrmDriver])
], SchemaQueryBuilder);
exports.SchemaQueryBuilder = SchemaQueryBuilder;
Object.values(enums_1.ColumnType).forEach((type) => {
export { SchemaQueryBuilder };
Object.values(ColumnType).forEach((type) => {
TableQueryBuilder.prototype[type] = function (name, ...args) {

@@ -1575,3 +1542,3 @@ const _builder = new ColumnQueryBuilder(this.Container, name, type, ...args);

});
Object.values(enums_1.ColumnType).forEach((type) => {
Object.values(ColumnType).forEach((type) => {
AlterTableQueryBuilder.prototype[type] = function (name, ...args) {

@@ -1578,0 +1545,0 @@ const _builder = new AlterColumnQueryBuilder(this.Container, name, type, ...args);

@@ -1,4 +0,4 @@

/// <reference types="node" />
import { IUniversalConverterOptions, ModelToSqlConverter, ValueConverter, ObjectToSqlConverter } from './interfaces';
import { ModelBase } from './model';
/// <reference types="node" resolution-mode="require"/>
import { IUniversalConverterOptions, ModelToSqlConverter, ValueConverter, ObjectToSqlConverter } from './interfaces.js';
import { ModelBase } from './model.js';
/**

@@ -21,1 +21,2 @@ * UUid converter to & from db as binary

}
//# sourceMappingURL=converters.d.ts.map

@@ -1,11 +0,8 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StandardObjectToSqlConverter = exports.StandardModelToSqlConverter = exports.UniversalValueConverter = exports.UuidConverter = void 0;
const luxon_1 = require("luxon");
const exceptions_1 = require("./exceptions");
const interfaces_1 = require("./interfaces");
import { DateTime } from 'luxon';
import { OrmException } from './exceptions.js';
import { ModelToSqlConverter, RelationType, ValueConverter, ObjectToSqlConverter } from './interfaces.js';
/**
* UUid converter to & from db as binary
*/
class UuidConverter extends interfaces_1.ValueConverter {
export class UuidConverter extends ValueConverter {
toDB(value) {

@@ -23,4 +20,3 @@ const buffer = Buffer.alloc(16);

}
exports.UuidConverter = UuidConverter;
class UniversalValueConverter extends interfaces_1.ValueConverter {
export class UniversalValueConverter extends ValueConverter {
toDB(value, model, options) {

@@ -48,3 +44,3 @@ switch (model[options.TypeColumn]) {

case 'datetime':
return luxon_1.DateTime.fromISO(value);
return DateTime.fromISO(value);
case 'float':

@@ -59,12 +55,10 @@ return parseFloat(value);

}
exports.UniversalValueConverter = UniversalValueConverter;
class StandardModelToSqlConverter extends interfaces_1.ModelToSqlConverter {
export class StandardModelToSqlConverter extends ModelToSqlConverter {
toSql(model) {
var _a;
const obj = {};
const relArr = [...model.ModelDescriptor.Relations.values()];
(_a = model.ModelDescriptor.Columns) === null || _a === void 0 ? void 0 : _a.forEach((c) => {
model.ModelDescriptor.Columns?.forEach((c) => {
const val = model[c.Name];
if (!c.PrimaryKey && !c.Nullable && (val === null || val === undefined || val === '')) {
throw new exceptions_1.OrmException(`Field ${c.Name} cannot be null`);
throw new OrmException(`Field ${c.Name} cannot be null`);
}

@@ -74,3 +68,3 @@ obj[c.Name] = c.Converter ? c.Converter.toDB(val, model, model.ModelDescriptor.Converters.get(c.Name).Options) : val;

for (const val of relArr) {
if (val.Type === interfaces_1.RelationType.One) {
if (val.Type === RelationType.One) {
if (model[val.Name].Value) {

@@ -84,4 +78,3 @@ obj[val.ForeignKey] = model[val.Name].Value.PrimaryKeyValue;

}
exports.StandardModelToSqlConverter = StandardModelToSqlConverter;
class StandardObjectToSqlConverter extends interfaces_1.ObjectToSqlConverter {
export class StandardObjectToSqlConverter extends ObjectToSqlConverter {
toSql(model) {

@@ -91,3 +84,2 @@ return model;

}
exports.StandardObjectToSqlConverter = StandardObjectToSqlConverter;
//# sourceMappingURL=converters.js.map
import { Constructor, IContainer } from '@spinajs/di';
import { IModelDescriptor, IRelationDescriptor, IDiscriminationEntry } from './interfaces';
import { IModelDescriptor, IRelationDescriptor, IDiscriminationEntry } from './interfaces.js';
import 'reflect-metadata';
import { ModelBase } from './model';
import { Relation } from './relations';
import { ModelBase } from './model.js';
import { Relation } from './relations.js';
export declare const MODEL_DESCTRIPTION_SYMBOL: unique symbol;

@@ -153,1 +153,2 @@ export declare const MIGRATION_DESCRIPTION_SYMBOL: unique symbol;

export declare function Set(): any;
//# sourceMappingURL=decorators.d.ts.map

@@ -1,25 +0,22 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Set = exports.UniversalConverter = exports.Json = exports.DateTime = exports.HasManyToMany = exports.Historical = exports.HasMany = exports.ForwardBelongsTo = exports.BelongsTo = exports.forwardRef = exports.Recursive = exports.DiscriminationMap = exports.JunctionTable = exports.Uuid = exports.Ignore = exports.Primary = exports.Archived = exports.SoftDelete = exports.UpdatedAt = exports.CreatedAt = exports.Model = exports.Connection = exports.Migration = exports.extractDecoratorDescriptor = exports.MIGRATION_DESCRIPTION_SYMBOL = exports.MODEL_DESCTRIPTION_SYMBOL = void 0;
const interfaces_1 = require("./interfaces");
import { JsonValueConverter } from './interfaces.js';
/* eslint-disable prettier/prettier */
const converters_1 = require("./converters");
const di_1 = require("@spinajs/di");
const interfaces_2 = require("./interfaces");
require("reflect-metadata");
const model_1 = require("./model");
const exceptions_1 = require("@spinajs/exceptions");
exports.MODEL_DESCTRIPTION_SYMBOL = Symbol.for('MODEL_DESCRIPTOR');
exports.MIGRATION_DESCRIPTION_SYMBOL = Symbol.for('MIGRATION_DESCRIPTOR');
import { UuidConverter } from './converters.js';
import { DI } from '@spinajs/di';
import { RelationType, DatetimeValueConverter, SetValueConverter } from './interfaces.js';
import 'reflect-metadata';
import { extractModelDescriptor } from './model.js';
import { InvalidOperation, InvalidArgument } from '../../exceptions/lib/index.js';
export const MODEL_DESCTRIPTION_SYMBOL = Symbol.for('MODEL_DESCRIPTOR');
export const MIGRATION_DESCRIPTION_SYMBOL = Symbol.for('MIGRATION_DESCRIPTOR');
/**
* Helper func to create model metadata
*/
function extractDecoratorDescriptor(callback, base = false) {
export function extractDecoratorDescriptor(callback, base = false) {
return (target, propertyKey, indexOrDescriptor) => {
let metadata = null;
if (!base) {
metadata = target.constructor[exports.MODEL_DESCTRIPTION_SYMBOL];
metadata = target.constructor[MODEL_DESCTRIPTION_SYMBOL];
}
else {
metadata = target[exports.MODEL_DESCTRIPTION_SYMBOL];
metadata = target[MODEL_DESCTRIPTION_SYMBOL];
}

@@ -54,6 +51,6 @@ if (!metadata) {

if (!base) {
target.constructor[exports.MODEL_DESCTRIPTION_SYMBOL] = metadata;
target.constructor[MODEL_DESCTRIPTION_SYMBOL] = metadata;
}
else {
target[exports.MODEL_DESCTRIPTION_SYMBOL] = metadata;
target[MODEL_DESCTRIPTION_SYMBOL] = metadata;
}

@@ -66,3 +63,2 @@ }

}
exports.extractDecoratorDescriptor = extractDecoratorDescriptor;
/**

@@ -73,5 +69,5 @@ * Sets migration option

*/
function Migration(connection) {
export function Migration(connection) {
return (target) => {
let metadata = target[exports.MIGRATION_DESCRIPTION_SYMBOL];
let metadata = target[MIGRATION_DESCRIPTION_SYMBOL];
if (!metadata) {

@@ -81,9 +77,8 @@ metadata = {

};
target[exports.MIGRATION_DESCRIPTION_SYMBOL] = metadata;
target[MIGRATION_DESCRIPTION_SYMBOL] = metadata;
}
metadata.Connection = connection;
di_1.DI.register(target).as('__migrations__');
DI.register(target).as('__migrations__');
};
}
exports.Migration = Migration;
/**

@@ -94,3 +89,3 @@ * Connection model decorator, assigns connection to model

*/
function Connection(name) {
export function Connection(name) {
return extractDecoratorDescriptor((model) => {

@@ -100,3 +95,2 @@ model.Connection = name;

}
exports.Connection = Connection;
/**

@@ -107,9 +101,8 @@ * TableName model decorator, assigns table from database to model

*/
function Model(tableName) {
export function Model(tableName) {
return extractDecoratorDescriptor((model, target) => {
di_1.DI.register(target).as('__models__');
DI.register(target).as('__models__');
model.TableName = tableName;
}, true);
}
exports.Model = Model;
/**

@@ -119,3 +112,3 @@ * Set create timestamps feature to model. Proper columns must be avaible in database table.

*/
function CreatedAt() {
export function CreatedAt() {
return extractDecoratorDescriptor((model, target, propertyKey) => {

@@ -129,7 +122,6 @@ const type = Reflect.getMetadata('design:type', target, propertyKey);

model.Converters.set(propertyKey, {
Class: interfaces_2.DatetimeValueConverter,
Class: DatetimeValueConverter,
});
});
}
exports.CreatedAt = CreatedAt;
/**

@@ -139,3 +131,3 @@ * Set update timestamps feature to model. Proper columns must be avaible in database table.

*/
function UpdatedAt() {
export function UpdatedAt() {
return extractDecoratorDescriptor((model, target, propertyKey) => {

@@ -149,7 +141,6 @@ const type = Reflect.getMetadata('design:type', target, propertyKey);

model.Converters.set(propertyKey, {
Class: interfaces_2.DatetimeValueConverter,
Class: DatetimeValueConverter,
});
});
}
exports.UpdatedAt = UpdatedAt;
/**

@@ -159,3 +150,3 @@ * Sets soft delete feature to model. Soft delete dont delete model, but sets deletion date and hides from

*/
function SoftDelete() {
export function SoftDelete() {
return extractDecoratorDescriptor((model, target, propertyKey) => {

@@ -169,7 +160,6 @@ const type = Reflect.getMetadata('design:type', target, propertyKey);

model.Converters.set(propertyKey, {
Class: interfaces_2.DatetimeValueConverter,
Class: DatetimeValueConverter,
});
});
}
exports.SoftDelete = SoftDelete;
/**

@@ -180,3 +170,3 @@ * Enable archive mode for model. If enabled all changes creates new instance in DB and old have set archived field

*/
function Archived() {
export function Archived() {
return extractDecoratorDescriptor((model, target, propertyKey) => {

@@ -190,11 +180,10 @@ const type = Reflect.getMetadata('design:type', target, propertyKey);

model.Converters.set(propertyKey, {
Class: interfaces_2.DatetimeValueConverter,
Class: DatetimeValueConverter,
});
});
}
exports.Archived = Archived;
/**
* Makrs field as primary key
*/
function Primary() {
export function Primary() {
return extractDecoratorDescriptor((model, _target, propertyKey) => {

@@ -204,7 +193,6 @@ model.PrimaryKey = propertyKey;

}
exports.Primary = Primary;
/**
* Marks columns as UUID. Column will be generated ad creation
*/
function Ignore() {
export function Ignore() {
return extractDecoratorDescriptor((model, _target, propertyKey) => {

@@ -221,7 +209,6 @@ const columnDesc = model.Columns.find((c) => c.Name === propertyKey);

}
exports.Ignore = Ignore;
/**
* Marks columns as UUID. Column will be generated ad creation
*/
function Uuid() {
export function Uuid() {
return extractDecoratorDescriptor((model, _target, propertyKey) => {

@@ -237,8 +224,7 @@ const columnDesc = model.Columns.find((c) => c.Name === propertyKey);

model.Converters.set(propertyKey, {
Class: converters_1.UuidConverter,
Class: UuidConverter,
});
}, true);
}
exports.Uuid = Uuid;
function JunctionTable() {
export function JunctionTable() {
return extractDecoratorDescriptor((model, target, propertyKey) => {

@@ -251,3 +237,2 @@ model.JunctionModelProperties.push({

}
exports.JunctionTable = JunctionTable;
/**

@@ -260,3 +245,3 @@ *

*/
function DiscriminationMap(fieldName, discriminationMap) {
export function DiscriminationMap(fieldName, discriminationMap) {
return extractDecoratorDescriptor((model, _target, _propertyKey) => {

@@ -270,3 +255,2 @@ model.DiscriminationMap.Field = fieldName;

}
exports.DiscriminationMap = DiscriminationMap;
/**

@@ -276,10 +260,10 @@ * Marks relation as recursive. When relation is populated it loads all to the top

*/
function Recursive() {
export function Recursive() {
return extractDecoratorDescriptor((model, _target, propertyKey) => {
if (!model.Relations.has(propertyKey)) {
throw new exceptions_1.InvalidOperation(`cannot set recursive on not existing relation ( relation ${propertyKey} on model ${model.Name} )`);
throw new InvalidOperation(`cannot set recursive on not existing relation ( relation ${propertyKey} on model ${model.Name} )`);
}
const relation = model.Relations.get(propertyKey);
if (relation.Type !== interfaces_2.RelationType.One) {
throw new exceptions_1.InvalidOperation(`cannot set recursive on non one-to-one relation ( relation ${propertyKey} on model ${model.Name} )`);
if (relation.Type !== RelationType.One) {
throw new InvalidOperation(`cannot set recursive on non one-to-one relation ( relation ${propertyKey} on model ${model.Name} )`);
}

@@ -289,7 +273,5 @@ relation.Recursive = true;

}
exports.Recursive = Recursive;
const forwardRef = (fn) => ({
export const forwardRef = (fn) => ({
forwardRef: fn,
});
exports.forwardRef = forwardRef;
/**

@@ -301,12 +283,12 @@ * Creates one to one relation with target model.

*/
function BelongsTo(targetModel, foreignKey, primaryKey) {
export function BelongsTo(targetModel, foreignKey, primaryKey) {
return extractDecoratorDescriptor((model, target, propertyKey) => {
model.Relations.set(propertyKey, {
Name: propertyKey,
Type: interfaces_2.RelationType.One,
Type: RelationType.One,
SourceModel: target.constructor,
TargetModelType: targetModel,
TargetModel: null,
ForeignKey: foreignKey !== null && foreignKey !== void 0 ? foreignKey : `${propertyKey.toLowerCase()}_id`,
PrimaryKey: primaryKey !== null && primaryKey !== void 0 ? primaryKey : model.PrimaryKey,
ForeignKey: foreignKey ?? `${propertyKey.toLowerCase()}_id`,
PrimaryKey: primaryKey ?? model.PrimaryKey,
Recursive: false,

@@ -316,3 +298,2 @@ });

}
exports.BelongsTo = BelongsTo;
/**

@@ -324,12 +305,12 @@ * Creates one to one relation with target model.

*/
function ForwardBelongsTo(forwardRef, foreignKey, primaryKey) {
export function ForwardBelongsTo(forwardRef, foreignKey, primaryKey) {
return extractDecoratorDescriptor((model, target, propertyKey) => {
model.Relations.set(propertyKey, {
Name: propertyKey,
Type: interfaces_2.RelationType.One,
Type: RelationType.One,
SourceModel: target.constructor,
TargetModelType: forwardRef.forwardRef,
TargetModel: null,
ForeignKey: foreignKey !== null && foreignKey !== void 0 ? foreignKey : `${propertyKey.toLowerCase()}_id`,
PrimaryKey: primaryKey !== null && primaryKey !== void 0 ? primaryKey : model.PrimaryKey,
ForeignKey: foreignKey ?? `${propertyKey.toLowerCase()}_id`,
PrimaryKey: primaryKey ?? model.PrimaryKey,
Recursive: false,

@@ -339,3 +320,2 @@ });

}
exports.ForwardBelongsTo = ForwardBelongsTo;
/**

@@ -349,13 +329,12 @@ * Creates one to many relation with target model.

*/
function HasMany(targetModel, options) {
export function HasMany(targetModel, options) {
return extractDecoratorDescriptor((model, target, propertyKey) => {
var _a, _b;
model.Relations.set(propertyKey, {
Name: propertyKey,
Type: interfaces_2.RelationType.Many,
Type: RelationType.Many,
SourceModel: target.constructor,
TargetModelType: targetModel,
TargetModel: null,
ForeignKey: options ? (_a = options.foreignKey) !== null && _a !== void 0 ? _a : `${model.Name.toLowerCase()}_id` : `${model.Name.toLowerCase()}_id`,
PrimaryKey: options ? (_b = options.primaryKey) !== null && _b !== void 0 ? _b : model.PrimaryKey : model.PrimaryKey,
ForeignKey: options ? options.foreignKey ?? `${model.Name.toLowerCase()}_id` : `${model.Name.toLowerCase()}_id`,
PrimaryKey: options ? options.primaryKey ?? model.PrimaryKey : model.PrimaryKey,
Recursive: false,

@@ -367,8 +346,7 @@ Factory: options ? options.factory : null,

}
exports.HasMany = HasMany;
function Historical(targetModel) {
export function Historical(targetModel) {
return extractDecoratorDescriptor((model, target, propertyKey) => {
model.Relations.set(propertyKey, {
Name: propertyKey,
Type: interfaces_2.RelationType.Many,
Type: RelationType.Many,
SourceModel: target.constructor,

@@ -383,3 +361,2 @@ TargetModelType: targetModel,

}
exports.Historical = Historical;
/**

@@ -395,21 +372,20 @@ * Creates many to many relation with separate join table

*/
function HasManyToMany(junctionModel, targetModel, targetModelPKey, sourceModelPKey, junctionModelTargetPk, junctionModelSourcePk) {
export function HasManyToMany(junctionModel, targetModel, targetModelPKey, sourceModelPKey, junctionModelTargetPk, junctionModelSourcePk) {
return extractDecoratorDescriptor((model, target, propertyKey) => {
const targetModelDescriptor = (0, model_1.extractModelDescriptor)(targetModel);
const targetModelDescriptor = extractModelDescriptor(targetModel);
model.Relations.set(propertyKey, {
Name: propertyKey,
Recursive: false,
Type: interfaces_2.RelationType.ManyToMany,
Type: RelationType.ManyToMany,
SourceModel: target.constructor,
TargetModelType: targetModel,
TargetModel: null,
ForeignKey: targetModelPKey !== null && targetModelPKey !== void 0 ? targetModelPKey : targetModelDescriptor.PrimaryKey,
PrimaryKey: sourceModelPKey !== null && sourceModelPKey !== void 0 ? sourceModelPKey : model.PrimaryKey,
ForeignKey: targetModelPKey ?? targetModelDescriptor.PrimaryKey,
PrimaryKey: sourceModelPKey ?? model.PrimaryKey,
JunctionModel: junctionModel,
JunctionModelTargetModelFKey_Name: junctionModelTargetPk !== null && junctionModelTargetPk !== void 0 ? junctionModelTargetPk : `${targetModelDescriptor.Name.toLowerCase()}_id`,
JunctionModelSourceModelFKey_Name: junctionModelSourcePk !== null && junctionModelSourcePk !== void 0 ? junctionModelSourcePk : `${model.Name.toLowerCase()}_id`,
JunctionModelTargetModelFKey_Name: junctionModelTargetPk ?? `${targetModelDescriptor.Name.toLowerCase()}_id`,
JunctionModelSourceModelFKey_Name: junctionModelSourcePk ?? `${model.Name.toLowerCase()}_id`,
});
});
}
exports.HasManyToMany = HasManyToMany;
/**

@@ -419,3 +395,3 @@ * Mark field as datetime type. It will ensure that conversion to & from DB is valid, eg. sqlite DB

*/
function DateTime() {
export function DateTime() {
return extractDecoratorDescriptor((model, target, propertyKey) => {

@@ -427,10 +403,9 @@ const type = Reflect.getMetadata('design:type', target, propertyKey);

if (model.Converters.has(propertyKey)) {
throw new exceptions_1.InvalidArgument(`property ${propertyKey} already have data converter attached`);
throw new InvalidArgument(`property ${propertyKey} already have data converter attached`);
}
model.Converters.set(propertyKey, {
Class: interfaces_2.DatetimeValueConverter,
Class: DatetimeValueConverter,
});
});
}
exports.DateTime = DateTime;
/**

@@ -441,11 +416,10 @@ * Converts data in db to json object. Column type in DB should be STRING.

*/
function Json() {
export function Json() {
return extractDecoratorDescriptor((model, _, propertyKey) => {
// add converter for this field
model.Converters.set(propertyKey, {
Class: interfaces_1.JsonValueConverter,
Class: JsonValueConverter,
});
});
}
exports.Json = Json;
/**

@@ -458,7 +432,7 @@ *

*/
function UniversalConverter(typeColumn) {
export function UniversalConverter(typeColumn) {
return extractDecoratorDescriptor((model, _, propertyKey) => {
// add converter for this field
model.Converters.set(propertyKey, {
Class: interfaces_1.JsonValueConverter,
Class: JsonValueConverter,
Options: {

@@ -470,7 +444,6 @@ TypeColumn: typeColumn,

}
exports.UniversalConverter = UniversalConverter;
/**
* Mark field as SET type. It will ensure that conversion to & from DB is valid, eg. to emulate field type SET in sqlite
*/
function Set() {
export function Set() {
return extractDecoratorDescriptor((model, target, propertyKey) => {

@@ -482,10 +455,9 @@ const type = Reflect.getMetadata('design:type', target, propertyKey);

if (model.Converters.has(propertyKey)) {
throw new exceptions_1.InvalidArgument(`property ${propertyKey} already have data converter attached`);
throw new InvalidArgument(`property ${propertyKey} already have data converter attached`);
}
model.Converters.set(propertyKey, {
Class: interfaces_2.SetValueConverter,
Class: SetValueConverter,
});
});
}
exports.Set = Set;
//# sourceMappingURL=decorators.js.map

@@ -1,2 +0,2 @@

import { ModelBase } from './model';
import { ModelBase } from './model.js';
export declare abstract class ModelDehydrator {

@@ -11,1 +11,2 @@ abstract dehydrate(model: ModelBase, omit?: string[]): any;

}
//# sourceMappingURL=dehydrators.d.ts.map

@@ -1,15 +0,10 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StandardModelWithRelationsDehydrator = exports.StandardModelDehydrator = exports.ModelDehydrator = void 0;
const exceptions_1 = require("./exceptions");
const interfaces_1 = require("./interfaces");
class ModelDehydrator {
import { OrmException } from './exceptions.js';
import { RelationType } from './interfaces.js';
export class ModelDehydrator {
}
exports.ModelDehydrator = ModelDehydrator;
class StandardModelDehydrator extends ModelDehydrator {
export class StandardModelDehydrator extends ModelDehydrator {
dehydrate(model, omit) {
var _a;
const obj = {};
const relArr = [...model.ModelDescriptor.Relations.values()];
(_a = model.ModelDescriptor.Columns) === null || _a === void 0 ? void 0 : _a.forEach((c) => {
model.ModelDescriptor.Columns?.forEach((c) => {
// if in omit list OR it is foreign key for relation - skip

@@ -21,3 +16,3 @@ if ((omit && omit.indexOf(c.Name) !== -1) || (relArr.find((r) => r.ForeignKey === c.Name) && !c.PrimaryKey)) {

if (!c.PrimaryKey && !c.Nullable && (val === null || val === undefined || val === '')) {
throw new exceptions_1.OrmException(`Field ${c.Name} cannot be null`);
throw new OrmException(`Field ${c.Name} cannot be null`);
}

@@ -29,4 +24,3 @@ obj[c.Name] = c.Converter ? c.Converter.toDB(val, model, null) : val;

}
exports.StandardModelDehydrator = StandardModelDehydrator;
class StandardModelWithRelationsDehydrator extends StandardModelDehydrator {
export class StandardModelWithRelationsDehydrator extends StandardModelDehydrator {
dehydrate(model, omit) {

@@ -36,3 +30,3 @@ const obj = super.dehydrate(model, omit);

for (const val of relArr) {
if (val.Type === interfaces_1.RelationType.One) {
if (val.Type === RelationType.One) {
if (model[val.Name].Value) {

@@ -42,3 +36,3 @@ obj[val.Name] = model[val.Name].Value.dehydrateWithRelations();

}
if (val.Type === interfaces_1.RelationType.Many) {
if (val.Type === RelationType.Many) {
if (model[val.Name]) {

@@ -52,3 +46,2 @@ obj[val.Name] = [...model[val.Name].map((x) => x.dehydrateWithRelations())];

}
exports.StandardModelWithRelationsDehydrator = StandardModelWithRelationsDehydrator;
//# sourceMappingURL=dehydrators.js.map
import { Log } from '@spinajs/log';
import { IColumnDescriptor, IDriverOptions, QueryContext } from './interfaces';
import { IColumnDescriptor, IDriverOptions, QueryContext } from './interfaces.js';
import { SyncService, IContainer, Container } from '@spinajs/di';
import { UpdateQueryBuilder, SelectQueryBuilder, IndexQueryBuilder, DeleteQueryBuilder, InsertQueryBuilder, SchemaQueryBuilder, QueryBuilder, TruncateTableQueryBuilder } from './builders';
import './hydrators';
import './dehydrators';
export declare type TransactionCallback = (driver: OrmDriver) => Promise<any>;
import { UpdateQueryBuilder, SelectQueryBuilder, IndexQueryBuilder, DeleteQueryBuilder, InsertQueryBuilder, SchemaQueryBuilder, QueryBuilder, TruncateTableQueryBuilder } from './builders.js';
import './hydrators.js';
import './dehydrators.js';
export type TransactionCallback = (driver: OrmDriver) => Promise<any>;
export declare abstract class OrmDriver extends SyncService {

@@ -83,1 +83,2 @@ /**

}
//# sourceMappingURL=driver.d.ts.map

@@ -1,2 +0,1 @@

"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {

@@ -11,13 +10,11 @@ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;

};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OrmDriver = void 0;
const log_1 = require("@spinajs/log");
import { Log } from '@spinajs/log';
/* eslint-disable prettier/prettier */
const interfaces_1 = require("./interfaces");
const di_1 = require("@spinajs/di");
const builders_1 = require("./builders");
const converters_1 = require("./converters");
require("./hydrators");
require("./dehydrators");
class OrmDriver extends di_1.SyncService {
import { ModelToSqlConverter, ObjectToSqlConverter } from './interfaces.js';
import { SyncService, DI, Container, Autoinject } from '@spinajs/di';
import { UpdateQueryBuilder, SelectQueryBuilder, IndexQueryBuilder, DeleteQueryBuilder, InsertQueryBuilder, SchemaQueryBuilder, TruncateTableQueryBuilder } from './builders.js';
import { StandardModelToSqlConverter, StandardObjectToSqlConverter } from './converters.js';
import './hydrators.js';
import './dehydrators.js';
export class OrmDriver extends SyncService {
constructor(options) {

@@ -37,3 +34,3 @@ super();

resolve() {
this.Log = di_1.DI.resolve(log_1.Log, [`orm-driver-${this.Options.Name}`]);
this.Log = DI.resolve(Log, [`orm-driver-${this.Options.Name}`]);
this.Log.addVariable('orm-name', this.Options.Name);

@@ -43,4 +40,4 @@ this.Log.addVariable('orm-host', this.Options.Host);

this.Container = this.RootContainer.child();
this.Container.register(converters_1.StandardModelToSqlConverter).as(interfaces_1.ModelToSqlConverter);
this.Container.register(converters_1.StandardObjectToSqlConverter).as(interfaces_1.ObjectToSqlConverter);
this.Container.register(StandardModelToSqlConverter).as(ModelToSqlConverter);
this.Container.register(StandardObjectToSqlConverter).as(ObjectToSqlConverter);
}

@@ -52,3 +49,3 @@ /**

select() {
return this.Container.resolve(builders_1.SelectQueryBuilder, [this]);
return this.Container.resolve(SelectQueryBuilder, [this]);
}

@@ -60,3 +57,3 @@ /**

del() {
return this.Container.resolve(builders_1.DeleteQueryBuilder, [this]);
return this.Container.resolve(DeleteQueryBuilder, [this]);
}

@@ -68,3 +65,3 @@ /**

insert() {
return this.Container.resolve(builders_1.InsertQueryBuilder, [this]);
return this.Container.resolve(InsertQueryBuilder, [this]);
}

@@ -75,3 +72,3 @@ /**

truncate(table) {
const b = this.Container.resolve(builders_1.TruncateTableQueryBuilder, [this]);
const b = this.Container.resolve(TruncateTableQueryBuilder, [this]);
b.setTable(table);

@@ -85,3 +82,3 @@ return b;

update() {
return this.Container.resolve(builders_1.UpdateQueryBuilder, [this]);
return this.Container.resolve(UpdateQueryBuilder, [this]);
}

@@ -93,3 +90,3 @@ /**

schema() {
return this.Container.resolve(builders_1.SchemaQueryBuilder, [this]);
return this.Container.resolve(SchemaQueryBuilder, [this]);
}

@@ -101,10 +98,9 @@ /**

index() {
return this.Container.resolve(builders_1.IndexQueryBuilder, [this]);
return this.Container.resolve(IndexQueryBuilder, [this]);
}
}
__decorate([
(0, di_1.Autoinject)(),
__metadata("design:type", di_1.Container)
Autoinject(),
__metadata("design:type", Container)
], OrmDriver.prototype, "RootContainer", void 0);
exports.OrmDriver = OrmDriver;
//# sourceMappingURL=driver.js.map

@@ -58,3 +58,3 @@ /**

}
export declare type Op = '<' | '>' | '!=' | '<=>' | '>=' | '<=' | '<>' | 'like' | '=' | 'rlike';
export type Op = '<' | '>' | '!=' | '<=>' | '>=' | '<=' | '<>' | 'like' | '=' | 'rlike';
/**

@@ -117,1 +117,2 @@ * Allowed join methods in queries

}
//# sourceMappingURL=enums.d.ts.map

@@ -1,8 +0,5 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SordOrder = exports.ColumnType = exports.ColumnMethods = exports.JoinMethod = exports.SqlOperator = exports.WhereBoolean = exports.QueryMethod = void 0;
/**
* Allowed query methods and types.
*/
var QueryMethod;
export var QueryMethod;
(function (QueryMethod) {

@@ -33,15 +30,15 @@ /**

QueryMethod[QueryMethod["SCHEMA"] = 5] = "SCHEMA";
})(QueryMethod = exports.QueryMethod || (exports.QueryMethod = {}));
})(QueryMethod || (QueryMethod = {}));
/**
* Logical operators used in queries
*/
var WhereBoolean;
export var WhereBoolean;
(function (WhereBoolean) {
WhereBoolean["AND"] = "and";
WhereBoolean["OR"] = "or";
})(WhereBoolean = exports.WhereBoolean || (exports.WhereBoolean = {}));
})(WhereBoolean || (WhereBoolean = {}));
/**
* Allowed operators in queries
*/
var SqlOperator;
export var SqlOperator;
(function (SqlOperator) {

@@ -64,7 +61,7 @@ SqlOperator["LT"] = "<";

SqlOperator["RLIKE"] = "rlike";
})(SqlOperator = exports.SqlOperator || (exports.SqlOperator = {}));
})(SqlOperator || (SqlOperator = {}));
/**
* Allowed join methods in queries
*/
var JoinMethod;
export var JoinMethod;
(function (JoinMethod) {

@@ -78,7 +75,7 @@ JoinMethod["INNER"] = "INNER JOIN";

JoinMethod["CROSS"] = "CROSS JOIN";
})(JoinMethod = exports.JoinMethod || (exports.JoinMethod = {}));
})(JoinMethod || (JoinMethod = {}));
/**
* Default column methods. For other methods user raw queries.
*/
var ColumnMethods;
export var ColumnMethods;
(function (ColumnMethods) {

@@ -90,7 +87,7 @@ ColumnMethods["MIN"] = "MIN";

ColumnMethods["COUNT"] = "COUNT";
})(ColumnMethods = exports.ColumnMethods || (exports.ColumnMethods = {}));
})(ColumnMethods || (ColumnMethods = {}));
/**
* Allowed column types
*/
var ColumnType;
export var ColumnType;
(function (ColumnType) {

@@ -123,8 +120,8 @@ ColumnType["SMALL_INTEGER"] = "smallint";

ColumnType["LONG_BLOB"] = "longblob";
})(ColumnType = exports.ColumnType || (exports.ColumnType = {}));
var SordOrder;
})(ColumnType || (ColumnType = {}));
export var SordOrder;
(function (SordOrder) {
SordOrder["ASC"] = "ASC";
SordOrder["DESC"] = "DESC";
})(SordOrder = exports.SordOrder || (exports.SordOrder = {}));
})(SordOrder || (SordOrder = {}));
//# sourceMappingURL=enums.js.map

@@ -1,2 +0,2 @@

import { Exception } from '@spinajs/exceptions';
import { Exception } from '../../exceptions/lib/index.js';
/**

@@ -7,1 +7,2 @@ * Exception thrown when functionality is not supported

}
//# sourceMappingURL=exceptions.d.ts.map

@@ -1,11 +0,7 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OrmException = void 0;
const exceptions_1 = require("@spinajs/exceptions");
import { Exception } from '../../exceptions/lib/index.js';
/**
* Exception thrown when functionality is not supported
*/
class OrmException extends exceptions_1.Exception {
export class OrmException extends Exception {
}
exports.OrmException = OrmException;
//# sourceMappingURL=exceptions.js.map

@@ -1,2 +0,2 @@

import { ModelBase } from './model';
import { ModelBase } from './model.js';
export declare abstract class ModelHydrator {

@@ -20,1 +20,2 @@ abstract hydrate(target: any, values: any): void;

}
//# sourceMappingURL=hydrators.d.ts.map

@@ -1,2 +0,1 @@

"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {

@@ -8,11 +7,8 @@ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;

};
Object.defineProperty(exports, "__esModule", { value: true });
exports.JunctionModelPropertyHydrator = exports.OneToOneRelationHydrator = exports.OneToManyRelationHydrator = exports.NonDbPropertyHydrator = exports.DbPropertyHydrator = exports.ModelHydrator = void 0;
/* eslint-disable prettier/prettier */
const interfaces_1 = require("./interfaces");
const di_1 = require("@spinajs/di");
const relations_1 = require("./relations");
class ModelHydrator {
import { RelationType } from './interfaces.js';
import { Injectable, isConstructor } from '@spinajs/di';
import { OneToManyRelationList, SingleRelation } from './relations.js';
export class ModelHydrator {
}
exports.ModelHydrator = ModelHydrator;
let DbPropertyHydrator = class DbPropertyHydrator extends ModelHydrator {

@@ -26,5 +22,4 @@ hydrate(target, values) {

// we handle it in later
const keys = Object.keys(values).filter((k) => { var _a; return (_a = descriptor.Columns) === null || _a === void 0 ? void 0 : _a.find((c) => c.Name === k); });
const keys = Object.keys(values).filter((k) => descriptor.Columns?.find((c) => c.Name === k));
keys.forEach((k) => {
var _a;
// skip if column is primary key & is null

@@ -35,3 +30,3 @@ // we dont want to override pkey of target model

}
const column = (_a = descriptor.Columns) === null || _a === void 0 ? void 0 : _a.find((c) => c.Name === k);
const column = descriptor.Columns?.find((c) => c.Name === k);
target[k] = column.Converter ? column.Converter.fromDB(values[k], values, descriptor.Converters.get(column.Name).Options) : values[k];

@@ -42,5 +37,5 @@ });

DbPropertyHydrator = __decorate([
(0, di_1.Injectable)(ModelHydrator)
Injectable(ModelHydrator)
], DbPropertyHydrator);
exports.DbPropertyHydrator = DbPropertyHydrator;
export { DbPropertyHydrator };
let NonDbPropertyHydrator = class NonDbPropertyHydrator extends ModelHydrator {

@@ -53,3 +48,3 @@ hydrate(target, values) {

// get only properties that are not in DB
const keys = Object.keys(values).filter((k) => { var _a; return ((_a = descriptor.Columns) === null || _a === void 0 ? void 0 : _a.find((c) => c.Name === k)) === undefined; });
const keys = Object.keys(values).filter((k) => descriptor.Columns?.find((c) => c.Name === k) === undefined);
keys.forEach((k) => {

@@ -61,5 +56,5 @@ target[k] = values[k];

NonDbPropertyHydrator = __decorate([
(0, di_1.Injectable)(ModelHydrator)
Injectable(ModelHydrator)
], NonDbPropertyHydrator);
exports.NonDbPropertyHydrator = NonDbPropertyHydrator;
export { NonDbPropertyHydrator };
let OneToManyRelationHydrator = class OneToManyRelationHydrator extends ModelHydrator {

@@ -72,3 +67,3 @@ hydrate(target, values) {

for (const [key, val] of descriptor.Relations) {
if (val.Type !== interfaces_1.RelationType.Many) {
if (val.Type !== RelationType.Many) {
continue;

@@ -79,3 +74,3 @@ }

const mapRel = values[key].map((x) => {
const tEntity = !(0, di_1.isConstructor)(val.TargetModel) ? new (val.TargetModel())() : new val.TargetModel();
const tEntity = !isConstructor(val.TargetModel) ? new (val.TargetModel())() : new val.TargetModel();
tEntity['__relationKey__'] = key;

@@ -85,3 +80,3 @@ tEntity.hydrate(x);

});
const rel = new relations_1.OneToManyRelationList(target, val.TargetModel, val, mapRel);
const rel = new OneToManyRelationList(target, val.TargetModel, val, mapRel);
entity[key] = rel;

@@ -94,5 +89,5 @@ delete target[val.ForeignKey];

OneToManyRelationHydrator = __decorate([
(0, di_1.Injectable)(ModelHydrator)
Injectable(ModelHydrator)
], OneToManyRelationHydrator);
exports.OneToManyRelationHydrator = OneToManyRelationHydrator;
export { OneToManyRelationHydrator };
let OneToOneRelationHydrator = class OneToOneRelationHydrator extends ModelHydrator {

@@ -105,3 +100,3 @@ hydrate(target, values) {

for (const [key, val] of descriptor.Relations) {
if (val.Type !== interfaces_1.RelationType.One) {
if (val.Type !== RelationType.One) {
continue;

@@ -111,6 +106,6 @@ }

const entity = target;
const tEntity = !(0, di_1.isConstructor)(val.TargetModel) ? new (val.TargetModel())() : new val.TargetModel();
const tEntity = !isConstructor(val.TargetModel) ? new (val.TargetModel())() : new val.TargetModel();
tEntity.hydrate(values[key]);
tEntity['__relationKey__'] = key;
const rel = new relations_1.SingleRelation(target, val.TargetModel, val, tEntity);
const rel = new SingleRelation(target, val.TargetModel, val, tEntity);
entity[key] = rel;

@@ -123,5 +118,5 @@ delete target[val.ForeignKey];

OneToOneRelationHydrator = __decorate([
(0, di_1.Injectable)(ModelHydrator)
Injectable(ModelHydrator)
], OneToOneRelationHydrator);
exports.OneToOneRelationHydrator = OneToOneRelationHydrator;
export { OneToOneRelationHydrator };
let JunctionModelPropertyHydrator = class JunctionModelPropertyHydrator extends ModelHydrator {

@@ -141,5 +136,5 @@ hydrate(target, values) {

JunctionModelPropertyHydrator = __decorate([
(0, di_1.Injectable)(ModelHydrator)
Injectable(ModelHydrator)
], JunctionModelPropertyHydrator);
exports.JunctionModelPropertyHydrator = JunctionModelPropertyHydrator;
export { JunctionModelPropertyHydrator };
//# sourceMappingURL=hydrators.js.map

@@ -1,15 +0,16 @@

export * from './interfaces';
export * from './enums';
export * from './statements';
export * from './builders';
export * from './model';
export * from './relations';
export * from './orm';
export * from './types';
export * from './decorators';
export * from './hydrators';
export * from './dehydrators';
export * from './driver';
export * from './converters';
export * from './wrappers';
export * from './exceptions';
export * from './interfaces.js';
export * from './enums.js';
export * from './statements.js';
export * from './builders.js';
export * from './model.js';
export * from './relations.js';
export * from './orm.js';
export * from './types.js';
export * from './decorators.js';
export * from './hydrators.js';
export * from './dehydrators.js';
export * from './driver.js';
export * from './converters.js';
export * from './wrappers.js';
export * from './exceptions.js';
//# sourceMappingURL=index.d.ts.map

@@ -1,32 +0,16 @@

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = 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) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./interfaces"), exports);
__exportStar(require("./enums"), exports);
__exportStar(require("./statements"), exports);
__exportStar(require("./builders"), exports);
__exportStar(require("./model"), exports);
__exportStar(require("./relations"), exports);
__exportStar(require("./orm"), exports);
__exportStar(require("./types"), exports);
__exportStar(require("./decorators"), exports);
__exportStar(require("./hydrators"), exports);
__exportStar(require("./dehydrators"), exports);
__exportStar(require("./driver"), exports);
__exportStar(require("./converters"), exports);
__exportStar(require("./wrappers"), exports);
__exportStar(require("./exceptions"), exports);
export * from './interfaces.js';
export * from './enums.js';
export * from './statements.js';
export * from './builders.js';
export * from './model.js';
export * from './relations.js';
export * from './orm.js';
export * from './types.js';
export * from './decorators.js';
export * from './hydrators.js';
export * from './dehydrators.js';
export * from './driver.js';
export * from './converters.js';
export * from './wrappers.js';
export * from './exceptions.js';
//# sourceMappingURL=index.js.map

@@ -1,10 +0,10 @@

import { Op } from './enums';
import { QueryBuilder, RawQuery } from './builders';
import { SordOrder, WhereBoolean } from './enums';
import { IQueryStatement, Wrap } from './statements';
import { PartialModel, Unbox, WhereFunction } from './types';
import { Relation } from './relations';
import { OrmDriver } from './driver';
import { Op } from './enums.js';
import { QueryBuilder, RawQuery } from './builders.js';
import { SordOrder, WhereBoolean } from './enums.js';
import { IQueryStatement, Wrap } from './statements.js';
import { PartialModel, Unbox, WhereFunction } from './types.js';
import { Relation } from './relations.js';
import { OrmDriver } from './driver.js';
import { Constructor, IContainer } from '@spinajs/di';
import { ModelBase } from './model';
import { ModelBase } from './model.js';
import { DateTime } from 'luxon';

@@ -256,3 +256,3 @@ export declare enum QueryContext {

}
export declare type ForwardRefFunction = () => Constructor<ModelBase>;
export type ForwardRefFunction = () => Constructor<ModelBase>;
/**

@@ -802,1 +802,2 @@ * Returns result of last insert or affected rows ( eg. rows affected would be 0 if insert is ignored )

}
//# sourceMappingURL=interfaces.d.ts.map

@@ -1,2 +0,1 @@

"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {

@@ -8,7 +7,5 @@ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;

};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ObjectToSqlConverter = exports.ModelToSqlConverter = exports.QueryScope = exports.TableAliasCompiler = exports.SetValueConverter = exports.JsonValueConverter = exports.DatetimeValueConverter = exports.ValueConverter = exports.ModelMiddleware = exports.QueryMiddleware = exports.GroupByQueryCompiler = exports.OrderByQueryCompiler = exports.AlterColumnQueryCompiler = exports.ColumnQueryCompiler = exports.DropTableCompiler = exports.TableExistsCompiler = exports.AlterTableQueryCompiler = exports.DropEventQueryCompiler = exports.EventQueryCompiler = exports.TableCloneQueryCompiler = exports.TruncateTableQueryCompiler = exports.TableHistoryQueryCompiler = exports.TableQueryCompiler = exports.OnDuplicateQueryCompiler = exports.InsertQueryCompiler = exports.UpdateQueryCompiler = exports.DeleteQueryCompiler = exports.ForeignKeyQueryCompiler = exports.LimitQueryCompiler = exports.IndexQueryCompiler = exports.JoinQueryCompiler = exports.SelectQueryCompiler = exports.RecursiveQueryCompiler = exports.OrmMigration = exports.RelationType = exports.MigrationTransactionMode = exports.ReferentialAction = exports.InsertBehaviour = exports.DefaultValueBuilder = exports.ColumnAlterationType = exports.QueryContext = void 0;
const di_1 = require("@spinajs/di");
const exceptions_1 = require("@spinajs/exceptions");
var QueryContext;
import { NewInstance, Singleton } from '@spinajs/di';
import { MethodNotImplemented } from '../../exceptions/lib/index.js';
export var QueryContext;
(function (QueryContext) {

@@ -21,4 +18,4 @@ QueryContext[QueryContext["Insert"] = 0] = "Insert";

QueryContext[QueryContext["Transaction"] = 5] = "Transaction";
})(QueryContext = exports.QueryContext || (exports.QueryContext = {}));
var ColumnAlterationType;
})(QueryContext || (QueryContext = {}));
export var ColumnAlterationType;
(function (ColumnAlterationType) {

@@ -28,7 +25,6 @@ ColumnAlterationType[ColumnAlterationType["Add"] = 0] = "Add";

ColumnAlterationType[ColumnAlterationType["Rename"] = 2] = "Rename";
})(ColumnAlterationType = exports.ColumnAlterationType || (exports.ColumnAlterationType = {}));
class DefaultValueBuilder {
})(ColumnAlterationType || (ColumnAlterationType = {}));
export class DefaultValueBuilder {
}
exports.DefaultValueBuilder = DefaultValueBuilder;
var InsertBehaviour;
export var InsertBehaviour;
(function (InsertBehaviour) {

@@ -48,7 +44,7 @@ /**

InsertBehaviour[InsertBehaviour["None"] = 3] = "None";
})(InsertBehaviour = exports.InsertBehaviour || (exports.InsertBehaviour = {}));
})(InsertBehaviour || (InsertBehaviour = {}));
/**
* Foreign key referential actions
*/
var ReferentialAction;
export var ReferentialAction;
(function (ReferentialAction) {

@@ -60,7 +56,7 @@ ReferentialAction["Cascade"] = "CASCADE";

ReferentialAction["SetDefault"] = "SET DEFAULT";
})(ReferentialAction = exports.ReferentialAction || (exports.ReferentialAction = {}));
})(ReferentialAction || (ReferentialAction = {}));
/**
* Transaction mode when migration DB
*/
var MigrationTransactionMode;
export var MigrationTransactionMode;
(function (MigrationTransactionMode) {

@@ -75,4 +71,4 @@ /**

MigrationTransactionMode[MigrationTransactionMode["PerMigration"] = 1] = "PerMigration";
})(MigrationTransactionMode = exports.MigrationTransactionMode || (exports.MigrationTransactionMode = {}));
var RelationType;
})(MigrationTransactionMode || (MigrationTransactionMode = {}));
export var RelationType;
(function (RelationType) {

@@ -82,9 +78,9 @@ RelationType[RelationType["One"] = 0] = "One";

RelationType[RelationType["ManyToMany"] = 2] = "ManyToMany";
})(RelationType = exports.RelationType || (exports.RelationType = {}));
})(RelationType || (RelationType = {}));
let OrmMigration = class OrmMigration {
};
OrmMigration = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], OrmMigration);
exports.OrmMigration = OrmMigration;
export { OrmMigration };
/**

@@ -97,144 +93,142 @@ * Definitions of query compiler are needed for DI resolving

RecursiveQueryCompiler = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], RecursiveQueryCompiler);
exports.RecursiveQueryCompiler = RecursiveQueryCompiler;
export { RecursiveQueryCompiler };
let SelectQueryCompiler = class SelectQueryCompiler {
};
SelectQueryCompiler = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], SelectQueryCompiler);
exports.SelectQueryCompiler = SelectQueryCompiler;
export { SelectQueryCompiler };
let JoinQueryCompiler = class JoinQueryCompiler {
};
JoinQueryCompiler = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], JoinQueryCompiler);
exports.JoinQueryCompiler = JoinQueryCompiler;
export { JoinQueryCompiler };
let IndexQueryCompiler = class IndexQueryCompiler {
};
IndexQueryCompiler = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], IndexQueryCompiler);
exports.IndexQueryCompiler = IndexQueryCompiler;
export { IndexQueryCompiler };
let LimitQueryCompiler = class LimitQueryCompiler {
};
LimitQueryCompiler = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], LimitQueryCompiler);
exports.LimitQueryCompiler = LimitQueryCompiler;
export { LimitQueryCompiler };
let ForeignKeyQueryCompiler = class ForeignKeyQueryCompiler {
};
ForeignKeyQueryCompiler = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], ForeignKeyQueryCompiler);
exports.ForeignKeyQueryCompiler = ForeignKeyQueryCompiler;
export { ForeignKeyQueryCompiler };
let DeleteQueryCompiler = class DeleteQueryCompiler {
};
DeleteQueryCompiler = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], DeleteQueryCompiler);
exports.DeleteQueryCompiler = DeleteQueryCompiler;
export { DeleteQueryCompiler };
let UpdateQueryCompiler = class UpdateQueryCompiler {
};
UpdateQueryCompiler = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], UpdateQueryCompiler);
exports.UpdateQueryCompiler = UpdateQueryCompiler;
export { UpdateQueryCompiler };
let InsertQueryCompiler = class InsertQueryCompiler {
};
InsertQueryCompiler = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], InsertQueryCompiler);
exports.InsertQueryCompiler = InsertQueryCompiler;
export { InsertQueryCompiler };
let OnDuplicateQueryCompiler = class OnDuplicateQueryCompiler {
};
OnDuplicateQueryCompiler = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], OnDuplicateQueryCompiler);
exports.OnDuplicateQueryCompiler = OnDuplicateQueryCompiler;
export { OnDuplicateQueryCompiler };
let TableQueryCompiler = class TableQueryCompiler {
};
TableQueryCompiler = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], TableQueryCompiler);
exports.TableQueryCompiler = TableQueryCompiler;
export { TableQueryCompiler };
let TableHistoryQueryCompiler = class TableHistoryQueryCompiler {
};
TableHistoryQueryCompiler = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], TableHistoryQueryCompiler);
exports.TableHistoryQueryCompiler = TableHistoryQueryCompiler;
export { TableHistoryQueryCompiler };
let TruncateTableQueryCompiler = class TruncateTableQueryCompiler {
};
TruncateTableQueryCompiler = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], TruncateTableQueryCompiler);
exports.TruncateTableQueryCompiler = TruncateTableQueryCompiler;
export { TruncateTableQueryCompiler };
let TableCloneQueryCompiler = class TableCloneQueryCompiler {
};
TableCloneQueryCompiler = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], TableCloneQueryCompiler);
exports.TableCloneQueryCompiler = TableCloneQueryCompiler;
export { TableCloneQueryCompiler };
let EventQueryCompiler = class EventQueryCompiler {
};
EventQueryCompiler = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], EventQueryCompiler);
exports.EventQueryCompiler = EventQueryCompiler;
export { EventQueryCompiler };
let DropEventQueryCompiler = class DropEventQueryCompiler {
};
DropEventQueryCompiler = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], DropEventQueryCompiler);
exports.DropEventQueryCompiler = DropEventQueryCompiler;
export { DropEventQueryCompiler };
let AlterTableQueryCompiler = class AlterTableQueryCompiler {
};
AlterTableQueryCompiler = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], AlterTableQueryCompiler);
exports.AlterTableQueryCompiler = AlterTableQueryCompiler;
export { AlterTableQueryCompiler };
let TableExistsCompiler = class TableExistsCompiler {
};
TableExistsCompiler = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], TableExistsCompiler);
exports.TableExistsCompiler = TableExistsCompiler;
export { TableExistsCompiler };
let DropTableCompiler = class DropTableCompiler {
};
DropTableCompiler = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], DropTableCompiler);
exports.DropTableCompiler = DropTableCompiler;
export { DropTableCompiler };
let ColumnQueryCompiler = class ColumnQueryCompiler {
};
ColumnQueryCompiler = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], ColumnQueryCompiler);
exports.ColumnQueryCompiler = ColumnQueryCompiler;
export { ColumnQueryCompiler };
let AlterColumnQueryCompiler = class AlterColumnQueryCompiler {
};
AlterColumnQueryCompiler = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], AlterColumnQueryCompiler);
exports.AlterColumnQueryCompiler = AlterColumnQueryCompiler;
export { AlterColumnQueryCompiler };
let OrderByQueryCompiler = class OrderByQueryCompiler {
};
OrderByQueryCompiler = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], OrderByQueryCompiler);
exports.OrderByQueryCompiler = OrderByQueryCompiler;
export { OrderByQueryCompiler };
let GroupByQueryCompiler = class GroupByQueryCompiler {
};
GroupByQueryCompiler = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], GroupByQueryCompiler);
exports.GroupByQueryCompiler = GroupByQueryCompiler;
class QueryMiddleware {
export { GroupByQueryCompiler };
export class QueryMiddleware {
}
exports.QueryMiddleware = QueryMiddleware;
class ModelMiddleware {
export class ModelMiddleware {
}
exports.ModelMiddleware = ModelMiddleware;
class ValueConverter {
export class ValueConverter {
/**

@@ -246,3 +240,3 @@ * Converts value to database type

toDB(_value, _model, _options) {
throw new exceptions_1.MethodNotImplemented();
throw new MethodNotImplemented();
}

@@ -255,13 +249,11 @@ /**

fromDB(_value, _rawData, _options) {
throw new exceptions_1.MethodNotImplemented();
throw new MethodNotImplemented();
}
}
exports.ValueConverter = ValueConverter;
/**
* Converter for DATETIME field (eg. mysql datetime)
*/
class DatetimeValueConverter extends ValueConverter {
export class DatetimeValueConverter extends ValueConverter {
}
exports.DatetimeValueConverter = DatetimeValueConverter;
class JsonValueConverter extends ValueConverter {
export class JsonValueConverter extends ValueConverter {
/**

@@ -284,27 +276,22 @@ * Converts value to database type

}
exports.JsonValueConverter = JsonValueConverter;
/**
* Converter for set field (eg. mysql SET)
*/
class SetValueConverter extends ValueConverter {
export class SetValueConverter extends ValueConverter {
}
exports.SetValueConverter = SetValueConverter;
let TableAliasCompiler = class TableAliasCompiler {
};
TableAliasCompiler = __decorate([
(0, di_1.Singleton)()
Singleton()
], TableAliasCompiler);
exports.TableAliasCompiler = TableAliasCompiler;
export { TableAliasCompiler };
/**
* base class for select & where builder for defining scopes
*/
class QueryScope {
export class QueryScope {
}
exports.QueryScope = QueryScope;
class ModelToSqlConverter {
export class ModelToSqlConverter {
}
exports.ModelToSqlConverter = ModelToSqlConverter;
class ObjectToSqlConverter {
export class ObjectToSqlConverter {
}
exports.ObjectToSqlConverter = ObjectToSqlConverter;
//# sourceMappingURL=interfaces.js.map

@@ -1,10 +0,10 @@

import { ModelData, ModelDataWithRelationData, PickRelations } from './types';
import { IModelDescriptor, InsertBehaviour, IUpdateResult, IWhereBuilder, QueryScope, IHistoricalModel } from './interfaces';
import { WhereFunction } from './types';
import { RawQuery, UpdateQueryBuilder, TruncateTableQueryBuilder, QueryBuilder, SelectQueryBuilder, DeleteQueryBuilder, InsertQueryBuilder } from './builders';
import { Op } from './enums';
import { ModelData, ModelDataWithRelationData, PickRelations } from './types.js';
import { IModelDescriptor, InsertBehaviour, IUpdateResult, IWhereBuilder, QueryScope, IHistoricalModel } from './interfaces.js';
import { WhereFunction } from './types.js';
import { RawQuery, UpdateQueryBuilder, TruncateTableQueryBuilder, QueryBuilder, SelectQueryBuilder, DeleteQueryBuilder, InsertQueryBuilder } from './builders.js';
import { Op } from './enums.js';
import { Class, IContainer } from '@spinajs/di';
import { Wrap } from './statements';
import { Wrap } from './statements.js';
import { DateTime } from 'luxon';
import { OrmDriver } from './driver';
import { OrmDriver } from './driver.js';
export declare function extractModelDescriptor(targetOrForward: any): IModelDescriptor;

@@ -344,1 +344,2 @@ export interface IModelBase {

};
//# sourceMappingURL=model.d.ts.map

@@ -1,43 +0,17 @@

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = 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) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MODEL_STATIC_MIXINS = exports.createQuery = exports.HistoricalModel = exports.ModelBase = exports.extractModelDescriptor = void 0;
/* eslint-disable prettier/prettier */
const relations_1 = require("./relations");
const enums_1 = require("./enums");
const decorators_1 = require("./decorators");
const interfaces_1 = require("./interfaces");
const builders_1 = require("./builders");
const di_1 = require("@spinajs/di");
const orm_1 = require("./orm");
const hydrators_1 = require("./hydrators");
const _ = __importStar(require("lodash"));
const uuid_1 = require("uuid");
const exceptions_1 = require("./exceptions");
const dehydrators_1 = require("./dehydrators");
const luxon_1 = require("luxon");
function extractModelDescriptor(targetOrForward) {
const target = !(0, di_1.isConstructor)(targetOrForward) && targetOrForward ? targetOrForward() : targetOrForward;
import { DiscriminationMapMiddleware, OneToManyRelationList, ManyToManyRelationList, SingleRelation } from './relations.js';
import { SordOrder } from './enums.js';
import { MODEL_DESCTRIPTION_SYMBOL } from './decorators.js';
import { RelationType, InsertBehaviour, ModelToSqlConverter, ObjectToSqlConverter } from './interfaces.js';
import { UpdateQueryBuilder, TruncateTableQueryBuilder, SelectQueryBuilder, DeleteQueryBuilder, InsertQueryBuilder } from './builders.js';
import { DI, isConstructor } from '@spinajs/di';
import { Orm } from './orm.js';
import { ModelHydrator } from './hydrators.js';
import _ from 'lodash';
import { v4 as uuidv4 } from 'uuid';
import { OrmException } from './exceptions.js';
import { StandardModelDehydrator, StandardModelWithRelationsDehydrator } from './dehydrators.js';
import { DateTime } from 'luxon';
export function extractModelDescriptor(targetOrForward) {
const target = !isConstructor(targetOrForward) && targetOrForward ? targetOrForward() : targetOrForward;
if (!target) {

@@ -53,5 +27,5 @@ return null;

}
if (t[decorators_1.MODEL_DESCTRIPTION_SYMBOL]) {
descriptor = descriptor !== null && descriptor !== void 0 ? descriptor : {};
_.mergeWith(descriptor, t[decorators_1.MODEL_DESCTRIPTION_SYMBOL], (a, b) => {
if (t[MODEL_DESCTRIPTION_SYMBOL]) {
descriptor = descriptor ?? {};
_.mergeWith(descriptor, t[MODEL_DESCTRIPTION_SYMBOL], (a, b) => {
if (!a) {

@@ -70,15 +44,3 @@ return b;

}
exports.extractModelDescriptor = extractModelDescriptor;
class ModelBase {
constructor(data) {
/**
* List of hidden properties from JSON / dehydrations
* eg. password field of user
*/
this._hidden = [];
this.setDefaults();
if (data) {
this.hydrate(data);
}
}
export class ModelBase {
/**

@@ -96,3 +58,3 @@ * Gets descriptor for this model. It contains information about relations, orm driver, connection properties,

if (!this._container) {
const orm = di_1.DI.get(orm_1.Orm);
const orm = DI.get(Orm);
const driver = orm.Connections.get(this.ModelDescriptor.Connection);

@@ -119,9 +81,9 @@ if (!driver) {

switch (r.Type) {
case interfaces_1.RelationType.One:
case RelationType.One:
rel[r.ForeignKey] = newVal;
break;
case interfaces_1.RelationType.Many:
case RelationType.Many:
rel.forEach((rVal) => (rVal[r.ForeignKey] = newVal));
break;
case interfaces_1.RelationType.ManyToMany:
case RelationType.ManyToMany:
// TODO: rethink this

@@ -133,3 +95,3 @@ break;

driver() {
const orm = di_1.DI.get(orm_1.Orm);
const orm = DI.get(Orm);
const driver = orm.Connections.get(this.ModelDescriptor.Connection);

@@ -145,3 +107,3 @@ return driver;

const models = _.flatMap(relations, (r) => {
if (r.Type === interfaces_1.RelationType.Many || r.Type === interfaces_1.RelationType.ManyToMany) {
if (r.Type === RelationType.Many || r.Type === RelationType.ManyToMany) {
return m[r.Name];

@@ -177,3 +139,3 @@ }

*/
static insert(_data, _insertBehaviour = interfaces_1.InsertBehaviour.None) {
static insert(_data, _insertBehaviour = InsertBehaviour.None) {
throw new Error('Not implemented');

@@ -274,2 +236,13 @@ }

}
constructor(data) {
/**
* List of hidden properties from JSON / dehydrations
* eg. password field of user
*/
this._hidden = [];
this.setDefaults();
if (data) {
this.hydrate(data);
}
}
/**

@@ -281,3 +254,3 @@ * Fills model with data. It only fills properties that exists in database

hydrate(data) {
this.Container.resolve(Array.ofType(hydrators_1.ModelHydrator)).forEach((h) => h.hydrate(this, data));
this.Container.resolve(Array.ofType(ModelHydrator)).forEach((h) => h.hydrate(this, data));
}

@@ -297,7 +270,7 @@ /**

switch (v.Type) {
case interfaces_1.RelationType.One:
case RelationType.One:
this[v.Name].attach(data);
break;
case interfaces_1.RelationType.Many:
case interfaces_1.RelationType.ManyToMany:
case RelationType.Many:
case RelationType.ManyToMany:
this[v.Name].push(data);

@@ -313,3 +286,3 @@ break;

dehydrate(omit) {
return this.Container.resolve(dehydrators_1.StandardModelDehydrator).dehydrate(this, [...(omit !== null && omit !== void 0 ? omit : []), ...this._hidden]);
return this.Container.resolve(StandardModelDehydrator).dehydrate(this, [...(omit ?? []), ...this._hidden]);
}

@@ -323,6 +296,6 @@ /**

dehydrateWithRelations(omit) {
return this.Container.resolve(dehydrators_1.StandardModelWithRelationsDehydrator).dehydrate(this, [...(omit !== null && omit !== void 0 ? omit : []), ...this._hidden]);
return this.Container.resolve(StandardModelWithRelationsDehydrator).dehydrate(this, [...(omit ?? []), ...this._hidden]);
}
toSql() {
return this.Container.resolve(interfaces_1.ModelToSqlConverter).toSql(this);
return this.Container.resolve(ModelToSqlConverter).toSql(this);
}

@@ -343,6 +316,6 @@ /**

if (this.ModelDescriptor.Archived) {
this[this.ModelDescriptor.Archived.ArchivedAt] = luxon_1.DateTime.now();
this[this.ModelDescriptor.Archived.ArchivedAt] = DateTime.now();
}
else {
throw new exceptions_1.OrmException('archived at column not exists in model');
throw new OrmException('archived at column not exists in model');
}

@@ -355,3 +328,3 @@ const { query } = this.createUpdateQuery();

if (this.ModelDescriptor.Timestamps.UpdatedAt) {
this[this.ModelDescriptor.Timestamps.UpdatedAt] = luxon_1.DateTime.now();
this[this.ModelDescriptor.Timestamps.UpdatedAt] = DateTime.now();
}

@@ -364,12 +337,12 @@ await query.update(this.toSql()).where(this.PrimaryKeyName, this.PrimaryKeyValue);

*/
async insert(insertBehaviour = interfaces_1.InsertBehaviour.None) {
async insert(insertBehaviour = InsertBehaviour.None) {
const { query, description } = this.createInsertQuery();
switch (insertBehaviour) {
case interfaces_1.InsertBehaviour.InsertOrIgnore:
case InsertBehaviour.InsertOrIgnore:
query.orIgnore();
break;
case interfaces_1.InsertBehaviour.InsertOrUpdate:
case InsertBehaviour.InsertOrUpdate:
query.onDuplicate().update(description.Columns.filter((c) => !c.PrimaryKey).map((c) => c.Name));
break;
case interfaces_1.InsertBehaviour.InsertOrReplace:
case InsertBehaviour.InsertOrReplace:
query.orReplace();

@@ -380,4 +353,3 @@ break;

afterQuery: (data) => {
var _a;
this.PrimaryKeyValue = (_a = this.PrimaryKeyValue) !== null && _a !== void 0 ? _a : data.LastInsertId;
this.PrimaryKeyValue = this.PrimaryKeyValue ?? data.LastInsertId;
return data;

@@ -398,3 +370,3 @@ },

*/
async insertOrUpdate(insertBehaviour = interfaces_1.InsertBehaviour.None) {
async insertOrUpdate(insertBehaviour = InsertBehaviour.None) {
if (this.PrimaryKeyValue) {

@@ -441,6 +413,5 @@ await this.update();

setDefaults() {
var _a;
(_a = this.ModelDescriptor.Columns) === null || _a === void 0 ? void 0 : _a.forEach((c) => {
this.ModelDescriptor.Columns?.forEach((c) => {
if (c.Uuid) {
this[c.Name] = (0, uuid_1.v4)();
this[c.Name] = uuidv4();
}

@@ -452,3 +423,3 @@ else {

if (this.ModelDescriptor.Timestamps.CreatedAt) {
this[this.ModelDescriptor.Timestamps.CreatedAt] = luxon_1.DateTime.now();
this[this.ModelDescriptor.Timestamps.CreatedAt] = DateTime.now();
}

@@ -462,10 +433,10 @@ for (const [, rel] of this.ModelDescriptor.Relations) {

}
else if (rel.Type === interfaces_1.RelationType.Many) {
this[rel.Name] = new relations_1.OneToManyRelationList(this, rel.TargetModel, rel, []);
else if (rel.Type === RelationType.Many) {
this[rel.Name] = new OneToManyRelationList(this, rel.TargetModel, rel, []);
}
else if (rel.Type === interfaces_1.RelationType.ManyToMany) {
this[rel.Name] = new relations_1.ManyToManyRelationList(this, rel.TargetModel, rel, []);
else if (rel.Type === RelationType.ManyToMany) {
this[rel.Name] = new ManyToManyRelationList(this, rel.TargetModel, rel, []);
}
else {
this[rel.Name] = new relations_1.SingleRelation(this, rel.TargetModel, rel, null);
this[rel.Name] = new SingleRelation(this, rel.TargetModel, rel, null);
}

@@ -475,14 +446,13 @@ }

createSelectQuery() {
return createQuery(this.constructor, builders_1.SelectQueryBuilder);
return createQuery(this.constructor, SelectQueryBuilder);
}
createUpdateQuery() {
return createQuery(this.constructor, builders_1.UpdateQueryBuilder);
return createQuery(this.constructor, UpdateQueryBuilder);
}
createInsertQuery() {
return createQuery(this.constructor, builders_1.InsertQueryBuilder);
return createQuery(this.constructor, InsertQueryBuilder);
}
}
exports.ModelBase = ModelBase;
function _descriptor(model) {
return model[decorators_1.MODEL_DESCTRIPTION_SYMBOL];
return model[MODEL_DESCTRIPTION_SYMBOL];
}

@@ -501,3 +471,3 @@ function _preparePkWhere(description, query, model) {

else {
throw new exceptions_1.OrmException('Model dont have primary key set or columns with unique constraint, cannot fetch model from database');
throw new OrmException('Model dont have primary key set or columns with unique constraint, cannot fetch model from database');
}

@@ -507,5 +477,4 @@ }

function _prepareOrderBy(description, query, order) {
var _a, _b;
if (description.PrimaryKey) {
query.order(description.PrimaryKey, order !== null && order !== void 0 ? order : enums_1.SordOrder.DESC);
query.order(description.PrimaryKey, order ?? SordOrder.DESC);
}

@@ -515,15 +484,14 @@ else {

if (unique.length !== 0) {
unique.forEach((c) => query.order(c.Name, order !== null && order !== void 0 ? order : enums_1.SordOrder.DESC));
unique.forEach((c) => query.order(c.Name, order ?? SordOrder.DESC));
}
else if ((_a = description.Timestamps) === null || _a === void 0 ? void 0 : _a.CreatedAt) {
query.order(description.Timestamps.CreatedAt, order !== null && order !== void 0 ? order : enums_1.SordOrder.DESC);
else if (description.Timestamps?.CreatedAt) {
query.order(description.Timestamps.CreatedAt, order ?? SordOrder.DESC);
}
else if ((_b = description.Timestamps) === null || _b === void 0 ? void 0 : _b.UpdatedAt) {
query.order(description.Timestamps.UpdatedAt, order !== null && order !== void 0 ? order : enums_1.SordOrder.DESC);
else if (description.Timestamps?.UpdatedAt) {
query.order(description.Timestamps.UpdatedAt, order ?? SordOrder.DESC);
}
}
}
class HistoricalModel {
export class HistoricalModel {
}
exports.HistoricalModel = HistoricalModel;
/**

@@ -538,3 +506,3 @@ * Helper function to create query based on model

*/
function createQuery(model, query, injectModel = true) {
export function createQuery(model, query, injectModel = true) {
const dsc = _descriptor(model);

@@ -544,3 +512,3 @@ if (!dsc) {

}
const orm = di_1.DI.get(orm_1.Orm);
const orm = DI.get(Orm);
const driver = orm.Connections.get(dsc.Connection);

@@ -552,3 +520,3 @@ if (!driver) {

const qr = cnt.resolve(query, [driver, injectModel ? orm.Models.find((x) => x.name === model.name).type : null]);
if (qr instanceof builders_1.SelectQueryBuilder) {
if (qr instanceof SelectQueryBuilder) {
const scope = model._queryScopes;

@@ -565,3 +533,3 @@ if (scope) {

}
qr.middleware(new relations_1.DiscriminationMapMiddleware(dsc));
qr.middleware(new DiscriminationMapMiddleware(dsc));
qr.setTable(dsc.TableName);

@@ -578,6 +546,5 @@ if (driver.Options.Database) {

}
exports.createQuery = createQuery;
exports.MODEL_STATIC_MIXINS = {
export const MODEL_STATIC_MIXINS = {
truncate() {
const { query } = createQuery(this, builders_1.TruncateTableQueryBuilder, false);
const { query } = createQuery(this, TruncateTableQueryBuilder, false);
return query;

@@ -587,3 +554,3 @@ },

const dsc = _descriptor(this);
const orm = di_1.DI.get(orm_1.Orm);
const orm = DI.get(Orm);
const driver = orm.Connections.get(dsc.Connection);

@@ -596,7 +563,7 @@ if (!driver) {

query() {
const { query } = createQuery(this, builders_1.SelectQueryBuilder);
const { query } = createQuery(this, SelectQueryBuilder);
return query;
},
where(column, operator, value) {
const { query } = createQuery(this, builders_1.SelectQueryBuilder);
const { query } = createQuery(this, SelectQueryBuilder);
query.select('*');

@@ -606,7 +573,7 @@ return query.where(column, operator, value);

update(data) {
const { query } = createQuery(this, builders_1.UpdateQueryBuilder);
const { query } = createQuery(this, UpdateQueryBuilder);
return query.update(data);
},
all(page, perPage) {
const { query } = createQuery(this, builders_1.SelectQueryBuilder);
const { query } = createQuery(this, SelectQueryBuilder);
query.select('*');

@@ -621,8 +588,8 @@ if (page >= 0 && perPage > 0) {

*/
async insert(data, insertBehaviour = interfaces_1.InsertBehaviour.None) {
const { query, description, container } = createQuery(this, builders_1.InsertQueryBuilder);
const converter = container.resolve(interfaces_1.ObjectToSqlConverter);
async insert(data, insertBehaviour = InsertBehaviour.None) {
const { query, description, container } = createQuery(this, InsertQueryBuilder);
const converter = container.resolve(ObjectToSqlConverter);
if (Array.isArray(data)) {
if (insertBehaviour !== interfaces_1.InsertBehaviour.None) {
throw new exceptions_1.OrmException(`insert behaviour is not supported with arrays`);
if (insertBehaviour !== InsertBehaviour.None) {
throw new OrmException(`insert behaviour is not supported with arrays`);
}

@@ -638,9 +605,9 @@ query.values(data.map((d) => {

switch (insertBehaviour) {
case interfaces_1.InsertBehaviour.InsertOrIgnore:
case InsertBehaviour.InsertOrIgnore:
query.orIgnore();
break;
case interfaces_1.InsertBehaviour.InsertOrUpdate:
case InsertBehaviour.InsertOrUpdate:
query.onDuplicate().update(description.Columns.filter((c) => !c.PrimaryKey).map((c) => c.Name));
break;
case interfaces_1.InsertBehaviour.InsertOrReplace:
case InsertBehaviour.InsertOrReplace:
query.orReplace();

@@ -658,8 +625,6 @@ break;

afterQuery: (result) => {
var _a;
if (Array.isArray(data)) {
data.forEach((v, idx) => {
var _a;
if (v instanceof ModelBase) {
v.PrimaryKeyValue = (_a = v.PrimaryKeyValue) !== null && _a !== void 0 ? _a : result.LastInsertId - data.length + idx;
v.PrimaryKeyValue = v.PrimaryKeyValue ?? result.LastInsertId - data.length + idx;
}

@@ -669,3 +634,3 @@ });

else if (data instanceof ModelBase) {
data.PrimaryKeyValue = (_a = data.PrimaryKeyValue) !== null && _a !== void 0 ? _a : result.LastInsertId;
data.PrimaryKeyValue = data.PrimaryKeyValue ?? result.LastInsertId;
}

@@ -681,3 +646,3 @@ return result;

async find(pks) {
const { query, description } = createQuery(this, builders_1.SelectQueryBuilder);
const { query, description } = createQuery(this, SelectQueryBuilder);
const pkey = description.PrimaryKey;

@@ -689,3 +654,3 @@ query.select('*');

async findOrFail(pks) {
const { query, description, model } = createQuery(this, builders_1.SelectQueryBuilder);
const { query, description, model } = createQuery(this, SelectQueryBuilder);
const pkey = description.PrimaryKey;

@@ -701,3 +666,3 @@ query.select('*');

async get(pk) {
const { query, description } = createQuery(this, builders_1.SelectQueryBuilder);
const { query, description } = createQuery(this, SelectQueryBuilder);
const pkey = description.PrimaryKey;

@@ -710,3 +675,3 @@ query.select('*');

async getOrFail(pk) {
const { query, description } = createQuery(this, builders_1.SelectQueryBuilder);
const { query, description } = createQuery(this, SelectQueryBuilder);
const pkey = description.PrimaryKey;

@@ -719,9 +684,8 @@ query.select('*');

destroy(pks) {
var _a, _b;
const description = _descriptor(this);
const data = Array.isArray(pks) ? pks : [pks];
const { query } = ((_a = description.SoftDelete) === null || _a === void 0 ? void 0 : _a.DeletedAt) ? createQuery(this, builders_1.UpdateQueryBuilder) : createQuery(this, builders_1.DeleteQueryBuilder);
if ((_b = description.SoftDelete) === null || _b === void 0 ? void 0 : _b.DeletedAt) {
const { query } = description.SoftDelete?.DeletedAt ? createQuery(this, UpdateQueryBuilder) : createQuery(this, DeleteQueryBuilder);
if (description.SoftDelete?.DeletedAt) {
query.update({
[description.SoftDelete.DeletedAt]: luxon_1.DateTime.now(),
[description.SoftDelete.DeletedAt]: DateTime.now(),
});

@@ -740,3 +704,3 @@ }

async getOrCreate(pk, data) {
const { query, description } = createQuery(this, builders_1.SelectQueryBuilder);
const { query, description } = createQuery(this, SelectQueryBuilder);
// pk constrain

@@ -760,3 +724,3 @@ if (description.PrimaryKey && pk !== null) {

async getOrNew(pk, data) {
const { query, description } = createQuery(this, builders_1.SelectQueryBuilder);
const { query, description } = createQuery(this, SelectQueryBuilder);
// pk constrain

@@ -779,4 +743,4 @@ if (description.PrimaryKey) {

async first(callback) {
const { query, description } = createQuery(this, builders_1.SelectQueryBuilder);
_prepareOrderBy(description, query, enums_1.SordOrder.ASC);
const { query, description } = createQuery(this, SelectQueryBuilder);
_prepareOrderBy(description, query, SordOrder.ASC);
if (callback) {

@@ -788,4 +752,4 @@ callback(query);

async last(callback) {
const { query, description } = createQuery(this, builders_1.SelectQueryBuilder);
_prepareOrderBy(description, query, enums_1.SordOrder.DESC);
const { query, description } = createQuery(this, SelectQueryBuilder);
_prepareOrderBy(description, query, SordOrder.DESC);
if (callback) {

@@ -797,9 +761,8 @@ callback(query);

async newest(callback) {
var _a;
const { query, description } = createQuery(this, builders_1.SelectQueryBuilder);
if ((_a = description.Timestamps) === null || _a === void 0 ? void 0 : _a.CreatedAt) {
query.order(description.Timestamps.CreatedAt, enums_1.SordOrder.DESC);
const { query, description } = createQuery(this, SelectQueryBuilder);
if (description.Timestamps?.CreatedAt) {
query.order(description.Timestamps.CreatedAt, SordOrder.DESC);
}
else {
throw new exceptions_1.OrmException('cannot fetch newest entity - CreateAt column not exists in model/db');
throw new OrmException('cannot fetch newest entity - CreateAt column not exists in model/db');
}

@@ -812,9 +775,8 @@ if (callback) {

async oldest(callback) {
var _a;
const { query, description } = createQuery(this, builders_1.SelectQueryBuilder);
if ((_a = description.Timestamps) === null || _a === void 0 ? void 0 : _a.CreatedAt) {
query.order(description.Timestamps.CreatedAt, enums_1.SordOrder.ASC);
const { query, description } = createQuery(this, SelectQueryBuilder);
if (description.Timestamps?.CreatedAt) {
query.order(description.Timestamps.CreatedAt, SordOrder.ASC);
}
else {
throw new exceptions_1.OrmException('cannot fetch oldest entity - CreateAt column not exists in model/db');
throw new OrmException('cannot fetch oldest entity - CreateAt column not exists in model/db');
}

@@ -827,3 +789,3 @@ if (callback) {

async count(callback) {
const { query } = createQuery(this, builders_1.SelectQueryBuilder);
const { query } = createQuery(this, SelectQueryBuilder);
query.count('*', 'count');

@@ -830,0 +792,0 @@ if (callback) {

@@ -5,5 +5,5 @@ import { Configuration } from '@spinajs/configuration';

import { ClassInfo } from '@spinajs/reflection';
import { OrmMigration } from './interfaces';
import { ModelBase } from './model';
import { OrmDriver } from './driver';
import { OrmMigration } from './interfaces.js';
import { ModelBase } from './model.js';
import { OrmDriver } from './driver.js';
export declare class Orm extends AsyncService {

@@ -64,1 +64,2 @@ Models: Array<ClassInfo<ModelBase>>;

}
//# sourceMappingURL=orm.d.ts.map

@@ -1,18 +0,1 @@

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = 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) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {

@@ -24,26 +7,17 @@ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;

};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Orm = void 0;
const interfaces_1 = require("./interfaces");
import { DatetimeValueConverter } from './interfaces.js';
/* eslint-disable prettier/prettier */
const configuration_1 = require("@spinajs/configuration");
const di_1 = require("@spinajs/di");
const log_1 = require("@spinajs/log");
const _ = __importStar(require("lodash"));
const interfaces_2 = require("./interfaces");
const model_1 = require("./model");
const decorators_1 = require("./decorators");
const exceptions_1 = require("@spinajs/exceptions");
const exceptions_2 = require("./exceptions");
const luxon_1 = require("luxon");
import { Configuration } from '@spinajs/configuration';
import { AsyncService, Autoinject, Container, DI } from '@spinajs/di';
import { Log, Logger } from '@spinajs/log';
import _ from 'lodash';
import { MigrationTransactionMode } from './interfaces.js';
import { MODEL_STATIC_MIXINS, extractModelDescriptor } from './model.js';
import { MIGRATION_DESCRIPTION_SYMBOL, MODEL_DESCTRIPTION_SYMBOL } from './decorators.js';
import { InvalidOperation } from '../../exceptions/lib/index.js';
import { OrmException } from './exceptions.js';
import { DateTime } from 'luxon';
/**

@@ -55,3 +29,3 @@ * Used to exclude sensitive data to others. eg. removed password field from cfg

const MIGRATION_FILE_REGEXP = /(.*)_([0-9]{4}_[0-9]{2}_[0-9]{2}_[0-9]{2}_[0-9]{2}_[0-9]{2})/;
class Orm extends di_1.AsyncService {
export class Orm extends AsyncService {
constructor() {

@@ -72,9 +46,7 @@ super(...arguments);

await this.executeAvaibleMigrations(name, async (migration, driver) => {
var _a, _b;
const trFunction = async (driver) => {
var _a, _b;
await migration.up(driver);
await driver
.insert()
.into((_b = (_a = driver.Options.Migration) === null || _a === void 0 ? void 0 : _a.Table) !== null && _b !== void 0 ? _b : MIGRATION_TABLE_NAME)
.into(driver.Options.Migration?.Table ?? MIGRATION_TABLE_NAME)
.values({

@@ -86,3 +58,3 @@ Migration: migration.constructor.name,

};
if (((_b = (_a = driver.Options.Migration) === null || _a === void 0 ? void 0 : _a.Transaction) === null || _b === void 0 ? void 0 : _b.Mode) === interfaces_2.MigrationTransactionMode.PerMigration) {
if (driver.Options.Migration?.Transaction?.Mode === MigrationTransactionMode.PerMigration) {
await driver.transaction(trFunction);

@@ -105,9 +77,7 @@ }

await this.executeAvaibleMigrations(name, async (migration, driver) => {
var _a, _b;
const trFunction = async (driver) => {
var _a, _b;
await migration.down(driver);
await driver
.del()
.from((_b = (_a = driver.Options.Migration) === null || _a === void 0 ? void 0 : _a.Table) !== null && _b !== void 0 ? _b : MIGRATION_TABLE_NAME)
.from(driver.Options.Migration?.Table ?? MIGRATION_TABLE_NAME)
.where({

@@ -118,3 +88,3 @@ Migration: migration.constructor.name,

};
if (((_b = (_a = driver.Options.Migration) === null || _a === void 0 ? void 0 : _a.Transaction) === null || _b === void 0 ? void 0 : _b.Mode) === interfaces_2.MigrationTransactionMode.PerMigration) {
if (driver.Options.Migration?.Transaction?.Mode === MigrationTransactionMode.PerMigration) {
await driver.transaction(trFunction);

@@ -134,10 +104,10 @@ }

for (const m of this.Models) {
const descriptor = (0, model_1.extractModelDescriptor)(m.type);
const descriptor = extractModelDescriptor(m.type);
if (descriptor) {
const connection = this.Connections.get(descriptor.Connection);
if (connection) {
m.type[decorators_1.MODEL_DESCTRIPTION_SYMBOL].Driver = connection;
m.type[MODEL_DESCTRIPTION_SYMBOL].Driver = connection;
const columns = await connection.tableInfo(descriptor.TableName, connection.Options.Database);
if (columns) {
m.type[decorators_1.MODEL_DESCTRIPTION_SYMBOL].Columns = _.uniqBy(_.map(columns, (c) => {
m.type[MODEL_DESCTRIPTION_SYMBOL].Columns = _.uniqBy(_.map(columns, (c) => {
return _.assign(c, _.find(descriptor.Columns, { Name: c.Name }));

@@ -148,3 +118,3 @@ }), 'Name');

for (const [key, val] of descriptor.Converters) {
const column = m.type[decorators_1.MODEL_DESCTRIPTION_SYMBOL].Columns.find((c) => c.Name === key);
const column = m.type[MODEL_DESCTRIPTION_SYMBOL].Columns.find((c) => c.Name === key);
if (column) {

@@ -161,3 +131,3 @@ column.Converter = connection.Container.hasRegistered(val.Class) ? connection.Container.resolve(val.Class) : null;

// add all registered migrations via DI
const migrations = di_1.DI.getRegisteredTypes('__migrations__');
const migrations = DI.getRegisteredTypes('__migrations__');
if (migrations) {

@@ -168,3 +138,3 @@ migrations.forEach((m) => {

}
const models = di_1.DI.getRegisteredTypes('__models__');
const models = DI.getRegisteredTypes('__models__');
if (models) {

@@ -182,8 +152,8 @@ models.forEach((m) => {

registerDefaultConverters() {
this.Container.register(interfaces_1.DatetimeValueConverter).asMapValue('__orm_db_value_converters__', Date.name);
this.Container.register(interfaces_1.DatetimeValueConverter).asMapValue('__orm_db_value_converters__', luxon_1.DateTime.name);
this.Container.register(DatetimeValueConverter).asMapValue('__orm_db_value_converters__', Date.name);
this.Container.register(DatetimeValueConverter).asMapValue('__orm_db_value_converters__', DateTime.name);
}
wireRelations() {
this.Models.forEach((x) => {
const desc = (0, model_1.extractModelDescriptor)(x.type);
const desc = extractModelDescriptor(x.type);
if (!desc)

@@ -197,3 +167,3 @@ return;

if (!found) {
throw new exceptions_2.OrmException(`type ${rel.TargetModelType} not found for relation ${rel.Name} in model ${x.name} in file ${x.file}`);
throw new OrmException(`type ${rel.TargetModelType} not found for relation ${rel.Name} in model ${x.name} in file ${x.file}`);
}

@@ -232,3 +202,3 @@ rel.TargetModel = found.type;

if (created === null) {
throw new exceptions_2.OrmException(`Migration file ${migration.name} have invalid name format ( invalid migration name, expected: some_name_yyyy_MM_dd_HH_mm_ss got ${migration.name})`);
throw new OrmException(`Migration file ${migration.name} have invalid name format ( invalid migration name, expected: some_name_yyyy_MM_dd_HH_mm_ss got ${migration.name})`);
}

@@ -264,3 +234,3 @@ this.Migrations.push({

if (!this.Connections.has(defaultConnection)) {
throw new exceptions_1.InvalidOperation(`default connection ${defaultConnection} not exists`);
throw new InvalidOperation(`default connection ${defaultConnection} not exists`);
}

@@ -273,4 +243,4 @@ this.Connections.set('default', this.Connections.get(defaultConnection));

// tslint:disable-next-line: forin
for (const mixin in model_1.MODEL_STATIC_MIXINS) {
m.type[mixin] = model_1.MODEL_STATIC_MIXINS[mixin].bind(m.type);
for (const mixin in MODEL_STATIC_MIXINS) {
m.type[mixin] = MODEL_STATIC_MIXINS[mixin].bind(m.type);
}

@@ -284,3 +254,3 @@ });

}
const created = luxon_1.DateTime.fromFormat(match[2], 'yyyy_MM_dd_HH_mm_ss');
const created = DateTime.fromFormat(match[2], 'yyyy_MM_dd_HH_mm_ss');
if (!created.isValid) {

@@ -292,3 +262,2 @@ return null;

async executeAvaibleMigrations(name, callback, down, force) {
var _a, _b, _c;
const toMigrate = name ? this.Migrations.filter((m) => m.name === name) : this.Migrations;

@@ -299,5 +268,8 @@ let migrations = toMigrate

if (created === null) {
throw new exceptions_2.OrmException(`Migration file ${x.name} have invalid name format ( invalid migration name, expected: some_name_yyyy_MM_dd_HH_mm_ss got ${x.name})`);
throw new OrmException(`Migration file ${x.name} have invalid name format ( invalid migration name, expected: some_name_yyyy_MM_dd_HH_mm_ss got ${x.name})`);
}
return Object.assign({ created }, x);
return {
created,
...x,
};
})

@@ -315,3 +287,3 @@ .filter((x) => x !== null)

for (const m of migrations) {
const md = m.type[decorators_1.MIGRATION_DESCRIPTION_SYMBOL];
const md = m.type[MIGRATION_DESCRIPTION_SYMBOL];
const cn = this.Connections.get(md.Connection);

@@ -322,4 +294,4 @@ if (!cn) {

}
const migrationTableName = (_b = (_a = cn.Options.Migration) === null || _a === void 0 ? void 0 : _a.Table) !== null && _b !== void 0 ? _b : MIGRATION_TABLE_NAME;
if (!((_c = cn.Options.Migration) === null || _c === void 0 ? void 0 : _c.OnStartup)) {
const migrationTableName = cn.Options.Migration?.Table ?? MIGRATION_TABLE_NAME;
if (!cn.Options.Migration?.OnStartup) {
if (!force) {

@@ -354,14 +326,13 @@ this.Log.warn(`Migration for connection ${md.Connection} is disabled on startup, please check conf file for db.[connection].migration.OnStartup property`);

__decorate([
(0, di_1.Autoinject)(),
__metadata("design:type", di_1.Container)
Autoinject(),
__metadata("design:type", Container)
], Orm.prototype, "Container", void 0);
__decorate([
(0, log_1.Logger)('ORM'),
__metadata("design:type", log_1.Log)
Logger('ORM'),
__metadata("design:type", Log)
], Orm.prototype, "Log", void 0);
__decorate([
(0, di_1.Autoinject)(),
__metadata("design:type", configuration_1.Configuration)
Autoinject(),
__metadata("design:type", Configuration)
], Orm.prototype, "Configuration", void 0);
exports.Orm = Orm;
//# sourceMappingURL=orm.js.map

@@ -1,7 +0,7 @@

import { IRelationDescriptor, IModelDescriptor, InsertBehaviour, ForwardRefFunction, IBuilderMiddleware } from './interfaces';
import { IRelationDescriptor, IModelDescriptor, InsertBehaviour, ForwardRefFunction, IBuilderMiddleware } from './interfaces.js';
import { Constructor } from '@spinajs/di';
import { SelectQueryBuilder } from './builders';
import { IModelBase, ModelBase } from './model';
import { Orm } from './orm';
import { OrmDriver } from './driver';
import { SelectQueryBuilder } from './builders.js';
import { IModelBase, ModelBase } from './model.js';
import { Orm } from './orm.js';
import { OrmDriver } from './driver.js';
export interface IOrmRelation {

@@ -48,5 +48,2 @@ /**

export declare class BelongsToRelation extends OrmRelation {
protected _targetModel: Constructor<ModelBase>;
protected _targetModelDescriptor: IModelDescriptor;
protected _relationQuery: SelectQueryBuilder;
constructor(_orm: Orm, _query: SelectQueryBuilder<any>, _description: IRelationDescriptor, _parentRelation?: OrmRelation);

@@ -56,5 +53,2 @@ execute(callback: (this: SelectQueryBuilder, relation: OrmRelation) => void): void;

export declare class BelongsToRecursiveRelation extends OrmRelation {
protected _targetModel: Constructor<ModelBase>;
protected _targetModelDescriptor: IModelDescriptor;
protected _relationQuery: SelectQueryBuilder;
constructor(_orm: Orm, _query: SelectQueryBuilder<any>, _description: IRelationDescriptor, _parentRelation?: OrmRelation);

@@ -184,1 +178,2 @@ execute(callback: (this: SelectQueryBuilder, relation: OrmRelation) => void): void;

}
//# sourceMappingURL=relations.d.ts.map

@@ -1,18 +0,1 @@

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = 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) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {

@@ -24,9 +7,2 @@ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;

};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __metadata = (this && this.__metadata) || function (k, v) {

@@ -36,15 +12,15 @@ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);

var OneToManyRelation_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.OneToManyRelationList = exports.ManyToManyRelationList = exports.Relation = exports.SingleRelation = exports.ManyToManyRelation = exports.OneToManyRelation = exports.BelongsToRecursiveRelation = exports.BelongsToRelation = exports.DiscriminationMapMiddleware = exports.OrmRelation = void 0;
/* eslint-disable prettier/prettier */
const exceptions_1 = require("@spinajs/exceptions");
const interfaces_1 = require("./interfaces");
const di_1 = require("@spinajs/di");
const builders_1 = require("./builders");
const model_1 = require("./model");
const orm_1 = require("./orm");
const _ = __importStar(require("lodash"));
class OrmRelation {
import { InvalidOperation } from '../../exceptions/lib/index.js';
import { RelationType, InsertBehaviour } from './interfaces.js';
import { NewInstance, DI, isConstructor } from '@spinajs/di';
import { SelectQueryBuilder } from './builders.js';
import { createQuery, extractModelDescriptor, ModelBase } from './model.js';
import { Orm } from './orm.js';
import _ from 'lodash';
export class OrmRelation {
get Alias() {
return this.parentRelation ? `${this.parentRelation.Alias}.${this._separator}${this._description.Name}${this._separator}` : `${this._separator}${this._description.Name}${this._separator}`;
}
constructor(_orm, _query, _description, parentRelation) {
var _a;
this._orm = _orm;

@@ -55,8 +31,8 @@ this._query = _query;

if (this._description) {
this._targetModel = (_a = this._description.TargetModel) !== null && _a !== void 0 ? _a : undefined;
this._targetModel = this._description.TargetModel ?? undefined;
}
this._targetModelDescriptor = (0, model_1.extractModelDescriptor)(this._targetModel);
this._targetModelDescriptor = extractModelDescriptor(this._targetModel);
const driver = this._orm.Connections.get(this._targetModelDescriptor.Connection);
const cnt = driver.Container;
this._relationQuery = cnt.resolve(builders_1.SelectQueryBuilder, [driver, this._targetModel, this]);
this._relationQuery = cnt.resolve(SelectQueryBuilder, [driver, this._targetModel, this]);
this._separator = driver.Options.AliasSeparator;

@@ -67,5 +43,2 @@ if (driver.Options.Database) {

}
get Alias() {
return this.parentRelation ? `${this.parentRelation.Alias}.${this._separator}${this._description.Name}${this._separator}` : `${this._separator}${this._description.Name}${this._separator}`;
}
executeOnQuery(callback) {

@@ -75,3 +48,2 @@ callback.call(this._relationQuery, [this]);

}
exports.OrmRelation = OrmRelation;
class HasManyRelationMiddleware {

@@ -285,3 +257,3 @@ constructor(_relationQuery, _description, _path) {

}
class DiscriminationMapMiddleware {
export class DiscriminationMapMiddleware {
constructor(_description) {

@@ -307,3 +279,2 @@ this._description = _description;

}
exports.DiscriminationMapMiddleware = DiscriminationMapMiddleware;
let BelongsToRelation = class BelongsToRelation extends OrmRelation {

@@ -342,6 +313,6 @@ constructor(_orm, _query, _description, _parentRelation) {

BelongsToRelation = __decorate([
(0, di_1.NewInstance)(),
__metadata("design:paramtypes", [orm_1.Orm, builders_1.SelectQueryBuilder, Object, OrmRelation])
NewInstance(),
__metadata("design:paramtypes", [Orm, SelectQueryBuilder, Object, OrmRelation])
], BelongsToRelation);
exports.BelongsToRelation = BelongsToRelation;
export { BelongsToRelation };
let BelongsToRecursiveRelation = class BelongsToRecursiveRelation extends OrmRelation {

@@ -363,6 +334,6 @@ constructor(_orm, _query, _description, _parentRelation) {

BelongsToRecursiveRelation = __decorate([
(0, di_1.NewInstance)(),
__metadata("design:paramtypes", [orm_1.Orm, builders_1.SelectQueryBuilder, Object, OrmRelation])
NewInstance(),
__metadata("design:paramtypes", [Orm, SelectQueryBuilder, Object, OrmRelation])
], BelongsToRecursiveRelation);
exports.BelongsToRecursiveRelation = BelongsToRecursiveRelation;
export { BelongsToRecursiveRelation };
let OneToManyRelation = OneToManyRelation_1 = class OneToManyRelation extends OrmRelation {

@@ -394,19 +365,24 @@ constructor(_orm, _query, _description, _parentRelation) {

OneToManyRelation = OneToManyRelation_1 = __decorate([
(0, di_1.NewInstance)(),
__metadata("design:paramtypes", [orm_1.Orm, builders_1.SelectQueryBuilder, Object, OrmRelation])
NewInstance(),
__metadata("design:paramtypes", [Orm, SelectQueryBuilder, Object, OrmRelation])
], OneToManyRelation);
exports.OneToManyRelation = OneToManyRelation;
export { OneToManyRelation };
let ManyToManyRelation = class ManyToManyRelation extends OrmRelation {
get TableJoinQuery() {
return this._joinQuery;
}
get RelationQuery() {
return this._relationQuery;
}
constructor(_orm, _query, _description, _parentRelation) {
var _a, _b;
super(_orm, _query, _description, _parentRelation);
this._joinModel = (_b = (_a = this._orm.Models.find((m) => { var _a; return m.name === ((_a = this._description.JunctionModel) === null || _a === void 0 ? void 0 : _a.name); })) === null || _a === void 0 ? void 0 : _a.type) !== null && _b !== void 0 ? _b : undefined;
this._joinModel = this._orm.Models.find((m) => m.name === this._description.JunctionModel?.name)?.type ?? undefined;
if (this._joinModel === undefined) {
throw new exceptions_1.InvalidOperation(`model ${this._description.JunctionModel} not exists in orm module`);
throw new InvalidOperation(`model ${this._description.JunctionModel} not exists in orm module`);
}
this._joinModelDescriptor = (0, model_1.extractModelDescriptor)(this._joinModel);
const orm = di_1.DI.get(orm_1.Orm);
this._joinModelDescriptor = extractModelDescriptor(this._joinModel);
const orm = DI.get(Orm);
const driver = orm.Connections.get(this._targetModelDescriptor.Connection);
const cnt = driver.Container;
this._joinQuery = cnt.resolve(builders_1.SelectQueryBuilder, [driver, this._targetModel, this]);
this._joinQuery = cnt.resolve(SelectQueryBuilder, [driver, this._targetModel, this]);
if (driver.Options.Database) {

@@ -424,8 +400,2 @@ this._joinQuery.database(driver.Options.Database);

}
get TableJoinQuery() {
return this._joinQuery;
}
get RelationQuery() {
return this._relationQuery;
}
execute(callback) {

@@ -438,3 +408,3 @@ this._joinQuery.leftJoin(this._targetModelDescriptor.TableName, this.Alias, this._description.JunctionModelTargetModelFKey_Name, this._description.ForeignKey);

Name: this._description.Name,
Type: interfaces_1.RelationType.Many,
Type: RelationType.Many,
TargetModelType: this._description.JunctionModel,

@@ -452,7 +422,7 @@ TargetModel: this._description.JunctionModel,

ManyToManyRelation = __decorate([
(0, di_1.NewInstance)(),
__metadata("design:paramtypes", [orm_1.Orm, builders_1.SelectQueryBuilder, Object, OrmRelation])
NewInstance(),
__metadata("design:paramtypes", [Orm, SelectQueryBuilder, Object, OrmRelation])
], ManyToManyRelation);
exports.ManyToManyRelation = ManyToManyRelation;
class SingleRelation {
export { ManyToManyRelation };
export class SingleRelation {
constructor(_owner, model, Relation, object) {

@@ -463,4 +433,4 @@ this._owner = _owner;

this.Populated = false;
this.TargetModelDescriptor = (0, model_1.extractModelDescriptor)(model);
this.Orm = di_1.DI.get(orm_1.Orm);
this.TargetModelDescriptor = extractModelDescriptor(model);
this.Orm = DI.get(Orm);
this.Value = object;

@@ -490,4 +460,4 @@ }

*/
const query = (0, model_1.createQuery)(this.Relation.TargetModel, (builders_1.SelectQueryBuilder)).query;
const desc = (0, model_1.extractModelDescriptor)(this.Relation.TargetModel);
const query = createQuery(this.Relation.TargetModel, (SelectQueryBuilder)).query;
const desc = extractModelDescriptor(this.Relation.TargetModel);
query.where({ [desc.PrimaryKey]: this._owner[this.Relation.ForeignKey] });

@@ -504,3 +474,2 @@ if (callback) {

}
exports.SingleRelation = SingleRelation;
/**

@@ -511,3 +480,3 @@ * Iterable list of populated relation entities

*/
class Relation extends Array {
export class Relation extends Array {
constructor(owner, Model, Relation, objects) {

@@ -522,8 +491,8 @@ super();

}
this.TargetModelDescriptor = (0, model_1.extractModelDescriptor)(Model);
this.Orm = di_1.DI.get(orm_1.Orm);
this.TargetModelDescriptor = extractModelDescriptor(Model);
this.Orm = DI.get(Orm);
if (this.TargetModelDescriptor) {
this.Driver = this.Orm.Connections.get(this.TargetModelDescriptor.Connection);
}
this.IsModelAForwardRef = !(0, di_1.isConstructor)(this.Model);
this.IsModelAForwardRef = !isConstructor(this.Model);
}

@@ -555,4 +524,3 @@ /**

}
exports.Relation = Relation;
class ManyToManyRelationList extends Relation {
export class ManyToManyRelationList extends Relation {
intersection(_obj, _callback) {

@@ -573,3 +541,3 @@ throw new Error('Method not implemented.');

const data = (Array.isArray(obj) ? obj : [obj]).map((d) => d.PrimaryKeyValue);
const jmodelDescriptor = (0, model_1.extractModelDescriptor)(this.Relation.JunctionModel);
const jmodelDescriptor = extractModelDescriptor(this.Relation.JunctionModel);
const query = this.Driver.del()

@@ -601,4 +569,3 @@ .from(jmodelDescriptor.TableName)

}
exports.ManyToManyRelationList = ManyToManyRelationList;
class OneToManyRelationList extends Relation {
export class OneToManyRelationList extends Relation {
async deleteRelationData(data) {

@@ -629,7 +596,7 @@ if (data.length === 0) {

await this.deleteRelationData(finalDiff);
await this.add(finalDiff, interfaces_1.InsertBehaviour.InsertOrUpdate);
await this.add(finalDiff, InsertBehaviour.InsertOrUpdate);
}
async set(obj) {
await this.deleteRelationData(obj);
await this.add(obj, interfaces_1.InsertBehaviour.InsertOrUpdate);
await this.add(obj, InsertBehaviour.InsertOrUpdate);
}

@@ -639,6 +606,6 @@ async intersection(obj, callback) {

await this.deleteRelationData(result);
await this.add(result, interfaces_1.InsertBehaviour.InsertOrUpdate);
await this.add(result, InsertBehaviour.InsertOrUpdate);
}
async union(obj, mode) {
await this.add(obj, mode !== null && mode !== void 0 ? mode : interfaces_1.InsertBehaviour.InsertOrIgnore);
await this.add(obj, mode ?? InsertBehaviour.InsertOrIgnore);
}

@@ -657,3 +624,3 @@ async remove(obj) {

const tInsert = data.map((x) => {
if (x instanceof model_1.ModelBase) {
if (x instanceof ModelBase) {
return x;

@@ -675,3 +642,2 @@ }

}
exports.OneToManyRelationList = OneToManyRelationList;
//# sourceMappingURL=relations.js.map

@@ -1,7 +0,7 @@

import { ISelectQueryBuilder } from './interfaces';
import { SelectQueryBuilder, WhereBuilder, RawQuery } from './builders';
import { ColumnMethods, SqlOperator, JoinMethod } from './enums';
import { ISelectQueryBuilder } from './interfaces.js';
import type { SelectQueryBuilder, WhereBuilder, RawQuery } from './builders.js';
import { ColumnMethods, SqlOperator, JoinMethod } from './enums.js';
import { Container, Class, Constructor } from '@spinajs/di';
import { IColumnDescriptor } from './interfaces';
import { ModelBase } from './model';
import { IColumnDescriptor } from './interfaces.js';
import { ModelBase } from './model.js';
export interface IQueryStatementResult {

@@ -84,3 +84,2 @@ Statements: string[];

protected _alias: string;
protected _tableAlias: string;
protected _model: Constructor<ModelBase>;

@@ -121,3 +120,2 @@ protected _sourceModel: Constructor<ModelBase>;

protected _alias: string;
protected _tableAlias: string;
protected _descriptor: IColumnDescriptor;

@@ -143,1 +141,2 @@ constructor(column: string | RawQuery, alias: string, tableAlias: string, descriptor: IColumnDescriptor);

}
//# sourceMappingURL=statements.d.ts.map

@@ -1,18 +0,1 @@

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = 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) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {

@@ -24,25 +7,11 @@ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;

};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ColumnMethodStatement = exports.ColumnRawStatement = exports.ColumnStatement = exports.InSetStatement = exports.ExistsQueryStatement = exports.SelectQueryStatement = exports.InStatement = exports.JoinStatement = exports.DateTimeWrapper = exports.DateWrapper = exports.WrapStatement = exports.Wrap = exports.WhereStatement = exports.WhereQueryStatement = exports.BetweenStatement = exports.GroupByStatement = exports.WithRecursiveStatement = exports.RawQueryStatement = exports.QueryStatement = void 0;
/* eslint-disable prettier/prettier */
const builders_1 = require("./builders");
const enums_1 = require("./enums");
const di_1 = require("@spinajs/di");
const _ = __importStar(require("lodash"));
const model_1 = require("./model");
const exceptions_1 = require("./exceptions");
class QueryStatement {
constructor(tableAlias) {
this._tableAlias = tableAlias;
}
import { ColumnMethods, SqlOperator, JoinMethod } from './enums.js';
import { NewInstance, Container } from '@spinajs/di';
import _ from 'lodash';
import { extractModelDescriptor } from './model.js';
import { OrmException } from './exceptions.js';
export class QueryStatement {
get TableAlias() {

@@ -54,4 +23,6 @@ return this._tableAlias;

}
constructor(tableAlias) {
this._tableAlias = tableAlias;
}
}
exports.QueryStatement = QueryStatement;
let RawQueryStatement = class RawQueryStatement extends QueryStatement {

@@ -65,6 +36,6 @@ constructor(query, bindings) {

RawQueryStatement = __decorate([
(0, di_1.NewInstance)(),
NewInstance(),
__metadata("design:paramtypes", [String, Array])
], RawQueryStatement);
exports.RawQueryStatement = RawQueryStatement;
export { RawQueryStatement };
let WithRecursiveStatement = class WithRecursiveStatement extends QueryStatement {

@@ -80,6 +51,6 @@ constructor(_name, _query, _rcKeyName, _pkName) {

WithRecursiveStatement = __decorate([
(0, di_1.NewInstance)(),
__metadata("design:paramtypes", [String, builders_1.SelectQueryBuilder, String, String])
NewInstance(),
__metadata("design:paramtypes", [String, Function, String, String])
], WithRecursiveStatement);
exports.WithRecursiveStatement = WithRecursiveStatement;
export { WithRecursiveStatement };
let GroupByStatement = class GroupByStatement extends QueryStatement {

@@ -92,6 +63,6 @@ constructor(expression, tableAlias) {

GroupByStatement = __decorate([
(0, di_1.NewInstance)(),
NewInstance(),
__metadata("design:paramtypes", [Object, String])
], GroupByStatement);
exports.GroupByStatement = GroupByStatement;
export { GroupByStatement };
let BetweenStatement = class BetweenStatement extends QueryStatement {

@@ -106,6 +77,6 @@ constructor(column, val, not, tableAlias) {

BetweenStatement = __decorate([
(0, di_1.NewInstance)(),
NewInstance(),
__metadata("design:paramtypes", [String, Array, Boolean, String])
], BetweenStatement);
exports.BetweenStatement = BetweenStatement;
export { BetweenStatement };
let WhereQueryStatement = class WhereQueryStatement extends QueryStatement {

@@ -118,6 +89,6 @@ constructor(builder, tableAlias) {

WhereQueryStatement = __decorate([
(0, di_1.NewInstance)(),
__metadata("design:paramtypes", [builders_1.WhereBuilder, String])
NewInstance(),
__metadata("design:paramtypes", [Function, String])
], WhereQueryStatement);
exports.WhereQueryStatement = WhereQueryStatement;
export { WhereQueryStatement };
let WhereStatement = class WhereStatement extends QueryStatement {

@@ -134,7 +105,7 @@ constructor(column, operator, value, tableAlias, container, model) {

WhereStatement = __decorate([
(0, di_1.NewInstance)(),
__metadata("design:paramtypes", [String, String, Object, String, di_1.Container, Object])
NewInstance(),
__metadata("design:paramtypes", [String, String, Object, String, Container, Object])
], WhereStatement);
exports.WhereStatement = WhereStatement;
class Wrap {
export { WhereStatement };
export class Wrap {
constructor(column, wrapper) {

@@ -145,3 +116,2 @@ this.Column = column;

}
exports.Wrap = Wrap;
let WrapStatement = class WrapStatement {

@@ -154,18 +124,18 @@ constructor(value, tableAlias) {

WrapStatement = __decorate([
(0, di_1.NewInstance)(),
NewInstance(),
__metadata("design:paramtypes", [Object, String])
], WrapStatement);
exports.WrapStatement = WrapStatement;
export { WrapStatement };
let DateWrapper = class DateWrapper extends WrapStatement {
};
DateWrapper = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], DateWrapper);
exports.DateWrapper = DateWrapper;
export { DateWrapper };
let DateTimeWrapper = class DateTimeWrapper extends WrapStatement {
};
DateTimeWrapper = __decorate([
(0, di_1.NewInstance)()
NewInstance()
], DateTimeWrapper);
exports.DateTimeWrapper = DateTimeWrapper;
export { DateTimeWrapper };
let JoinStatement = class JoinStatement extends QueryStatement {

@@ -185,3 +155,3 @@ constructor(builder, sourceModel, table, method, foreignKey, primaryKey, alias, tableAlias) {

}
else if (table instanceof builders_1.RawQuery) {
else if (table.constructor.name === 'RawQuery') {
this._query = table;

@@ -192,4 +162,4 @@ }

this._sourceModel = sourceModel;
const sDesc = (0, model_1.extractModelDescriptor)(this._sourceModel);
const tDesc = (0, model_1.extractModelDescriptor)(this._model);
const sDesc = extractModelDescriptor(this._sourceModel);
const tDesc = extractModelDescriptor(this._model);
const sAlias = `${sDesc.Driver.Options.AliasSeparator}${sDesc.Name}${sDesc.Driver.Options.AliasSeparator}`;

@@ -204,3 +174,3 @@ this._tableAlias = `${sDesc.Driver.Options.AliasSeparator}${tDesc.Name}${sDesc.Driver.Options.AliasSeparator}`;

const cnt = driver.Container;
this._whereBuilder = cnt.resolve(builders_1.SelectQueryBuilder, [driver, this._model, this]);
this._whereBuilder = cnt.resolve('SelectQueryBuilder', [driver, this._model, this]);
this._whereBuilder.setAlias(this._tableAlias);

@@ -212,3 +182,3 @@ this._whereCallback.call(this._whereBuilder, [this]);

if (!relation) {
throw new exceptions_1.OrmException(`Cannot find relation between ${this._model.name} and ${this._sourceModel.name}, thus cannot perform join statement`);
throw new OrmException(`Cannot find relation between ${this._model.name} and ${this._sourceModel.name}, thus cannot perform join statement`);
}

@@ -223,6 +193,6 @@ this._table = tDesc.TableName;

JoinStatement = __decorate([
(0, di_1.NewInstance)(),
__metadata("design:paramtypes", [builders_1.SelectQueryBuilder, Object, Object, String, Object, String, String, String])
NewInstance(),
__metadata("design:paramtypes", [Function, Object, Object, String, Object, String, String, String])
], JoinStatement);
exports.JoinStatement = JoinStatement;
export { JoinStatement };
let InStatement = class InStatement extends QueryStatement {

@@ -237,6 +207,6 @@ constructor(column, val, not, tableAlias) {

InStatement = __decorate([
(0, di_1.NewInstance)(),
NewInstance(),
__metadata("design:paramtypes", [String, Array, Boolean, String])
], InStatement);
exports.InStatement = InStatement;
export { InStatement };
let SelectQueryStatement = class SelectQueryStatement extends QueryStatement {

@@ -249,6 +219,6 @@ constructor(builder, tableAlias) {

SelectQueryStatement = __decorate([
(0, di_1.NewInstance)(),
__metadata("design:paramtypes", [builders_1.SelectQueryBuilder, String])
NewInstance(),
__metadata("design:paramtypes", [Function, String])
], SelectQueryStatement);
exports.SelectQueryStatement = SelectQueryStatement;
export { SelectQueryStatement };
let ExistsQueryStatement = class ExistsQueryStatement extends SelectQueryStatement {

@@ -261,6 +231,6 @@ constructor(builder, not) {

ExistsQueryStatement = __decorate([
(0, di_1.NewInstance)(),
__metadata("design:paramtypes", [builders_1.SelectQueryBuilder, Boolean])
NewInstance(),
__metadata("design:paramtypes", [Function, Boolean])
], ExistsQueryStatement);
exports.ExistsQueryStatement = ExistsQueryStatement;
export { ExistsQueryStatement };
let InSetStatement = class InSetStatement extends QueryStatement {

@@ -275,6 +245,6 @@ constructor(column, val, not, tableAlias) {

InSetStatement = __decorate([
(0, di_1.NewInstance)(),
NewInstance(),
__metadata("design:paramtypes", [String, Array, Boolean, String])
], InSetStatement);
exports.InSetStatement = InSetStatement;
export { InSetStatement };
let ColumnStatement = class ColumnStatement extends QueryStatement {

@@ -304,3 +274,3 @@ constructor(column, alias, tableAlias, descriptor) {

get IsWildcard() {
if (this._column instanceof builders_1.RawQuery) {
if (this._column.constructor.name === 'RawQuery') {
return false;

@@ -312,7 +282,7 @@ }

ColumnStatement = __decorate([
(0, di_1.NewInstance)(),
NewInstance(),
__metadata("design:paramtypes", [Object, String, String, Object])
], ColumnStatement);
exports.ColumnStatement = ColumnStatement;
class ColumnRawStatement extends QueryStatement {
export { ColumnStatement };
export class ColumnRawStatement extends QueryStatement {
constructor(RawQuery) {

@@ -323,3 +293,2 @@ super();

}
exports.ColumnRawStatement = ColumnRawStatement;
let ColumnMethodStatement = class ColumnMethodStatement extends ColumnStatement {

@@ -332,6 +301,6 @@ constructor(column, method, alias, tableAlias) {

ColumnMethodStatement = __decorate([
(0, di_1.NewInstance)(),
NewInstance(),
__metadata("design:paramtypes", [String, String, String, String])
], ColumnMethodStatement);
exports.ColumnMethodStatement = ColumnMethodStatement;
export { ColumnMethodStatement };
//# sourceMappingURL=statements.js.map

@@ -1,24 +0,25 @@

import { IWhereBuilder } from './interfaces';
import { Relation, SingleRelation } from './relations';
export declare type WhereFunction<T> = (this: IWhereBuilder<T>) => void;
export declare type Unbox<T> = T extends Array<infer U> ? U : T;
export declare type UnboxRelation<T> = T extends Relation<infer U, any> ? U[] : T extends SingleRelation<infer Z> ? Z : never;
export declare type UnboxRelationWithModelData<T> = T extends Relation<infer U, any> ? Omit<ModelDataWithRelationData<U>, ExcludedModelProperties>[] : T extends SingleRelation<infer Z> ? Omit<ModelDataWithRelationData<Z>, ExcludedModelProperties> : T;
export declare type PickRelations<T> = {
import { IWhereBuilder } from './interfaces.js';
import { Relation, SingleRelation } from './relations.js';
export type WhereFunction<T> = (this: IWhereBuilder<T>) => void;
export type Unbox<T> = T extends Array<infer U> ? U : T;
export type UnboxRelation<T> = T extends Relation<infer U, any> ? U[] : T extends SingleRelation<infer Z> ? Z : never;
export type UnboxRelationWithModelData<T> = T extends Relation<infer U, any> ? Omit<ModelDataWithRelationData<U>, ExcludedModelProperties>[] : T extends SingleRelation<infer Z> ? Omit<ModelDataWithRelationData<Z>, ExcludedModelProperties> : T;
export type PickRelations<T> = {
[P in keyof T as T[P] extends Relation<any, any> | SingleRelation<any> ? P : never]: UnboxRelation<T[P]>;
};
export declare type PickRelationsWithModelData<T> = {
export type PickRelationsWithModelData<T> = {
[P in keyof T as T[P] extends Relation<any, any> | SingleRelation<any> ? P : never]: UnboxRelationWithModelData<T[P]>;
};
export declare type PartialModel<T> = {
export type PartialModel<T> = {
[P in keyof T]?: T[P] extends SingleRelation<infer W> ? W : T[P] | undefined;
};
export declare type NonFunctionAndRelationPropertyNames<T> = {
export type NonFunctionAndRelationPropertyNames<T> = {
[K in keyof T]: T[K] extends Function | Relation<any, any> | SingleRelation<any> ? never : K;
}[keyof T];
export declare type NonFunctionPropertyNames<T> = {
export type NonFunctionPropertyNames<T> = {
[K in keyof T]: T[K] extends Function ? never : K;
}[keyof T];
export declare type ExcludedModelProperties = 'PrimaryKeyValue' | 'PrimaryKeyName' | 'ModelDescriptor' | 'Container' | 'JunctionModelProps';
export declare type ModelData<T> = Omit<Pick<T, NonFunctionAndRelationPropertyNames<T>>, ExcludedModelProperties>;
export declare type ModelDataWithRelationData<T> = Omit<Pick<T, NonFunctionAndRelationPropertyNames<T>>, ExcludedModelProperties> & PickRelationsWithModelData<T>;
export type ExcludedModelProperties = 'PrimaryKeyValue' | 'PrimaryKeyName' | 'ModelDescriptor' | 'Container' | 'JunctionModelProps';
export type ModelData<T> = Omit<Pick<T, NonFunctionAndRelationPropertyNames<T>>, ExcludedModelProperties>;
export type ModelDataWithRelationData<T> = Omit<Pick<T, NonFunctionAndRelationPropertyNames<T>>, ExcludedModelProperties> & PickRelationsWithModelData<T>;
//# sourceMappingURL=types.d.ts.map

@@ -1,3 +0,2 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
export {};
//# sourceMappingURL=types.js.map

@@ -1,2 +0,2 @@

import { Wrap } from './statements';
import { Wrap } from './statements.js';
export declare const Wrapper: {

@@ -6,1 +6,2 @@ Date: (val: any) => Wrap;

};
//# sourceMappingURL=wrappers.d.ts.map

@@ -1,13 +0,10 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Wrapper = void 0;
const statements_1 = require("./statements");
exports.Wrapper = {
import { Wrap, DateTimeWrapper, DateWrapper } from './statements.js';
export const Wrapper = {
Date: (val) => {
return new statements_1.Wrap(val, statements_1.DateWrapper);
return new Wrap(val, DateWrapper);
},
DateTime: (val) => {
return new statements_1.Wrap(val, statements_1.DateTimeWrapper);
return new Wrap(val, DateTimeWrapper);
},
};
//# sourceMappingURL=wrappers.js.map
{
"name": "@spinajs/orm",
"version": "2.0.46",
"version": "2.0.48",
"description": "framework orm module",
"main": "lib/index.js",
"exports": "./lib/index.js",
"type": "module",
"private": false,
"engines": {
"node": ">=16.11"
},
"scripts": {
"build": "npm run clean && npm run compile",
"compile": "tsc -p tsconfig.build.json",
"clean": "",
"compile": "tsc -b tsconfig.json",
"rimraf": "./node_modules/rimraf/bin.js",
"clean": "rimraf lib/ && rimraf tsconfig.tsbuildinfo",
"test": "ts-mocha -p tsconfig.json test/**/*.test.ts",
"coverage": "nyc npm run test",
"build-docs": "rimraf docs && typedoc --options typedoc.json src/",
"prepare": "npm run build",
"format": "prettier --write \"src/**/*.ts\"",
"lint": "eslint -c .eslintrc.js --ext .ts src --fix",
"prepublishOnly": "npm test && npm run lint",
"lint": "eslint -c .eslintrc.cjs --ext .ts src --fix",
"preversion": "npm run lint",
"version": "npm run format && git add -A src",
"postversion": "git push && git push --tags"
"postinstall": "npm run build"
},

@@ -43,6 +46,6 @@ "files": [

"devDependencies": {
"@types/lodash": "4.14.182",
"@types/lodash": "4.14.191",
"@types/luxon": "^3.2.0",
"@types/node": "^16.11.44",
"@types/uuid": "8.3.4"
"@types/node": "^18.11.18",
"@types/uuid": "9.0.0"
},

@@ -53,11 +56,10 @@ "dependencies": {

"@spinajs/exceptions": "^2.0.39",
"@spinajs/internal-logger": "^2.0.46",
"@spinajs/log": "^2.0.46",
"@spinajs/reflection": "^2.0.46",
"glob": "^7.1.4",
"lodash": "^4.17.14",
"glob": "^8.1.0",
"lodash": "^4.17.21",
"luxon": "^3.2.1",
"uuid": "^8.3.2"
"uuid": "^9.0.0"
},
"gitHead": "bd560afd6c9a156071102cc6b4f36115b5498e9d"
"gitHead": "002dc553b0ffffd72193d0121ac425a4083bc9ee"
}

@@ -0,0 +0,0 @@ # `@spinajs/orm`

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc