@spinajs/orm
Advanced tools
Comparing version 1.0.6 to 1.0.7
@@ -13,10 +13,13 @@ import { Container } from "@spinajs/di"; | ||
protected _container: Container; | ||
constructor(driver: OrmDriver, container: Container); | ||
protected _model?: Constructor<any>; | ||
protected _nonSelect: boolean; | ||
constructor(container: Container, driver: OrmDriver, model?: Constructor<any>); | ||
get Table(): string; | ||
get TableAlias(): string; | ||
get Schema(): string; | ||
setSchema(schema: string): this; | ||
schema(schema: string): this; | ||
toDB(): ICompilerOutput; | ||
then(resolve: (rows: any[]) => void, reject: (err: Error) => void): void; | ||
protected setTable(table: string, alias?: string): void; | ||
setTable(table: string, alias?: string): this; | ||
from(table: string, alias?: string): this; | ||
} | ||
@@ -47,2 +50,3 @@ export declare class LimitBuilder implements ILimitBuilder { | ||
columns(names: string[]): this; | ||
select(column: string | RawQuery, alias?: string): this; | ||
getColumns(): IQueryStatement[]; | ||
@@ -95,3 +99,3 @@ } | ||
get IsDistinct(): boolean; | ||
constructor(driver: OrmDriver, container: Container); | ||
constructor(container: Container, driver: OrmDriver, model: Constructor<any>); | ||
min(column: string, as?: string): this; | ||
@@ -104,2 +108,3 @@ max(column: string, as?: string): this; | ||
toDB(): ICompilerOutput; | ||
then(resolve: (rows: any[]) => void, reject: (err: Error) => void): void; | ||
} | ||
@@ -109,7 +114,11 @@ export interface DeleteQueryBuilder extends IWhereBuilder, ILimitBuilder { | ||
export declare class DeleteQueryBuilder extends QueryBuilder { | ||
protected _statements: IQueryStatement[]; | ||
protected _boolean: WhereBoolean; | ||
protected _truncate: boolean; | ||
protected _limit: IQueryLimit; | ||
get Truncate(): boolean; | ||
private this; | ||
constructor(driver: OrmDriver, container: Container); | ||
constructor(container: Container, driver: OrmDriver, model: Constructor<any>); | ||
toDB(): ICompilerOutput; | ||
truncate(): this; | ||
} | ||
@@ -119,6 +128,8 @@ export interface UpdateQueryBuilder extends IWhereBuilder { | ||
export declare class UpdateQueryBuilder extends QueryBuilder { | ||
protected _statements: IQueryStatement[]; | ||
protected _boolean: WhereBoolean; | ||
protected _value: {}; | ||
get Value(): {}; | ||
private this; | ||
constructor(driver: OrmDriver, container: Container); | ||
constructor(container: Container, driver: OrmDriver, model: Constructor<any>); | ||
in(name: string): this; | ||
@@ -136,3 +147,3 @@ update(value: {}): this; | ||
get Values(): any[][]; | ||
constructor(driver: OrmDriver, container: Container); | ||
constructor(container: Container, driver: OrmDriver, model: Constructor<any>); | ||
values(data: {} | Array<{}>): this; | ||
@@ -144,14 +155,14 @@ into(table: string, schema?: string): this; | ||
export declare class ColumnQueryBuilder { | ||
protected _name: string; | ||
protected _unique: boolean; | ||
protected _unsigned: boolean; | ||
protected _autoIncrement: boolean; | ||
protected _default: string | RawQuery | number; | ||
protected _primaryKey: boolean; | ||
protected _comment: string; | ||
protected _charset: string; | ||
protected _collation: string; | ||
protected _notNull: boolean; | ||
protected _type: string; | ||
protected _args: any[]; | ||
Name: string; | ||
Unique: boolean; | ||
Unsigned: boolean; | ||
AutoIncrement: boolean; | ||
Default: string | RawQuery | number; | ||
PrimaryKey: boolean; | ||
Comment: string; | ||
Charset: string; | ||
Collation: string; | ||
NotNull: boolean; | ||
Type: string; | ||
Args: any[]; | ||
constructor(name: string, type: string, ...args: any[]); | ||
@@ -195,3 +206,3 @@ notNull(): this; | ||
protected _charset: string; | ||
constructor(name: string, driver: OrmDriver, container: Container); | ||
constructor(container: Container, driver: OrmDriver, name: string); | ||
increments(name: string): ColumnQueryBuilder; | ||
@@ -203,6 +214,6 @@ comment(comment: string): void; | ||
export declare class SchemaQueryBuilder { | ||
protected container: Container; | ||
protected driver: OrmDriver; | ||
protected container: Container; | ||
constructor(driver: OrmDriver, container: Container); | ||
createTable(name: string, callback: (table: TableQueryBuilder) => void): this; | ||
constructor(container: Container, driver: OrmDriver); | ||
createTable(name: string, callback: (table: TableQueryBuilder) => void): TableQueryBuilder; | ||
} |
@@ -11,2 +11,9 @@ "use strict"; | ||
}; | ||
var __importStar = (this && this.__importStar) || function (mod) { | ||
if (mod && mod.__esModule) return mod; | ||
var result = {}; | ||
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; | ||
result["default"] = mod; | ||
return result; | ||
}; | ||
var RawQuery_1, WhereBuilder_1; | ||
@@ -16,3 +23,3 @@ Object.defineProperty(exports, "__esModule", { value: true }); | ||
const exceptions_1 = require("@spinajs/exceptions"); | ||
const _ = require("lodash"); | ||
const _ = __importStar(require("lodash")); | ||
const typescript_mix_1 = require("typescript-mix"); | ||
@@ -27,5 +34,7 @@ const util_1 = require("util"); | ||
let QueryBuilder = class QueryBuilder { | ||
constructor(driver, container) { | ||
constructor(container, driver, model) { | ||
this._driver = driver; | ||
this._container = container; | ||
this._model = model; | ||
this._nonSelect = true; | ||
} | ||
@@ -41,3 +50,3 @@ get Table() { | ||
} | ||
setSchema(schema) { | ||
schema(schema) { | ||
if (!schema) { | ||
@@ -54,16 +63,29 @@ throw new exceptions_1.ArgumentException(`schema argument cannot be null or empty`); | ||
const compiled = this.toDB(); | ||
this._driver.execute(compiled.expression, compiled.bindings).then(resolve, reject); | ||
this._driver.execute(compiled.expression, compiled.bindings).then((result) => { | ||
if (this._model && !this._nonSelect) { | ||
resolve(result.map(r => { | ||
return new this._model(r); | ||
})); | ||
} | ||
else { | ||
resolve(result); | ||
} | ||
}, reject); | ||
} | ||
setTable(table, alias) { | ||
if (!table) { | ||
if (!table.trim()) { | ||
throw new exceptions_1.ArgumentException("table name is empty"); | ||
} | ||
this._table = table; | ||
this._tableAlias = alias; | ||
this._tableAlias = alias ? alias : null; | ||
return this; | ||
} | ||
from(table, alias) { | ||
return this.setTable(table, alias); | ||
} | ||
}; | ||
QueryBuilder = __decorate([ | ||
di_1.NewInstance(), | ||
di_1.Inject(interfaces_1.OrmDriver, di_1.Container), | ||
__metadata("design:paramtypes", [interfaces_1.OrmDriver, di_1.Container]) | ||
di_1.Inject(di_1.Container), | ||
__metadata("design:paramtypes", [di_1.Container, interfaces_1.OrmDriver, Object]) | ||
], QueryBuilder); | ||
@@ -134,3 +156,3 @@ exports.QueryBuilder = QueryBuilder; | ||
getSort() { | ||
return this._sort; | ||
return this._sort.column.trim() !== "" ? this._sort : null; | ||
} | ||
@@ -157,2 +179,11 @@ }; | ||
} | ||
select(column, alias) { | ||
if (column instanceof RawQuery) { | ||
this._columns.push(this._container.resolve(statements_1.ColumnRawStatement, [column])); | ||
} | ||
else { | ||
this._columns.push(this._container.resolve(statements_1.ColumnStatement, [column, alias])); | ||
} | ||
return this; | ||
} | ||
getColumns() { | ||
@@ -221,3 +252,3 @@ return this._columns; | ||
} | ||
if (arguments.length === 2) { | ||
if (typeof value === 'undefined') { | ||
return _handleForTwo.call(this, column, operator); | ||
@@ -321,4 +352,4 @@ } | ||
class SelectQueryBuilder extends QueryBuilder { | ||
constructor(driver, container) { | ||
super(driver, container); | ||
constructor(container, driver, model) { | ||
super(container, driver, model); | ||
this._distinct = false; | ||
@@ -333,2 +364,3 @@ this._columns = []; | ||
}; | ||
this._first = false; | ||
this._limit = { | ||
@@ -338,2 +370,3 @@ limit: -1, | ||
}; | ||
this._nonSelect = false; | ||
} | ||
@@ -365,2 +398,5 @@ get IsDistinct() { | ||
distinct() { | ||
if (this._columns.length === 0 || this._columns[0].IsWildcard) { | ||
throw new exceptions_1.InvalidOperationException("Cannot force DISTINCT on unknown column"); | ||
} | ||
this._distinct = true; | ||
@@ -370,5 +406,20 @@ return this; | ||
toDB() { | ||
const compiler = this._container.resolve(interfaces_1.SelectQueryCompiler); | ||
const compiler = this._container.resolve(interfaces_1.SelectQueryCompiler, [this]); | ||
return compiler.compile(); | ||
} | ||
then(resolve, reject) { | ||
super.then((result) => { | ||
if (this._first) { | ||
if (this._fail && result.length === 0) { | ||
reject(new Error("empty results")); | ||
} | ||
else { | ||
resolve(result[0]); | ||
} | ||
} | ||
else { | ||
resolve(result); | ||
} | ||
}, reject); | ||
} | ||
} | ||
@@ -381,6 +432,12 @@ __decorate([ | ||
class DeleteQueryBuilder extends QueryBuilder { | ||
constructor(driver, container) { | ||
super(driver, container); | ||
constructor(container, driver, model) { | ||
super(container, driver, model); | ||
this._truncate = false; | ||
this._method = enums_1.QueryMethod.DELETE; | ||
this._statements = []; | ||
this._boolean = enums_1.WhereBoolean.AND; | ||
this._limit = { | ||
limit: -1, | ||
offset: -1 | ||
}; | ||
} | ||
@@ -391,4 +448,8 @@ get Truncate() { | ||
toDB() { | ||
return this._container.resolve(interfaces_1.DeleteQueryCompiler).compile(); | ||
return this._container.resolve(interfaces_1.DeleteQueryCompiler, [this]).compile(); | ||
} | ||
truncate() { | ||
this._truncate = true; | ||
return this; | ||
} | ||
} | ||
@@ -401,6 +462,8 @@ __decorate([ | ||
class UpdateQueryBuilder extends QueryBuilder { | ||
constructor(driver, container) { | ||
super(driver, container); | ||
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._statements = []; | ||
} | ||
@@ -419,3 +482,3 @@ get Value() { | ||
toDB() { | ||
return this._container.resolve(interfaces_1.UpdateQueryCompiler).compile(); | ||
return this._container.resolve(interfaces_1.UpdateQueryCompiler, [this]).compile(); | ||
} | ||
@@ -429,4 +492,4 @@ } | ||
class InsertQueryBuilder extends QueryBuilder { | ||
constructor(driver, container) { | ||
super(driver, container); | ||
constructor(container, driver, model) { | ||
super(container, driver, model); | ||
this._method = enums_1.QueryMethod.INSERT; | ||
@@ -436,3 +499,2 @@ this._columns = []; | ||
} | ||
; | ||
get Values() { | ||
@@ -455,5 +517,5 @@ return this._values; | ||
const binding = []; | ||
self._columns.map(c => { | ||
self._columns.filter(c => !(c.Column instanceof RawQuery)).map(c => { | ||
return c.Column; | ||
}).forEach(c => { | ||
}).forEach((c) => { | ||
binding.push(d[c]); | ||
@@ -470,3 +532,3 @@ }); | ||
onDuplicate(callback) { | ||
this._onDuplicate = new UpdateQueryBuilder(this._driver, this._container); | ||
this._onDuplicate = new UpdateQueryBuilder(this._container, this._driver, this._model); | ||
callback.call(this._onDuplicate); | ||
@@ -476,3 +538,3 @@ return this; | ||
toDB() { | ||
return this._container.resolve(interfaces_1.InsertQueryCompiler).compile(); | ||
return this._container.resolve(interfaces_1.InsertQueryCompiler, [this]).compile(); | ||
} | ||
@@ -485,59 +547,63 @@ } | ||
exports.InsertQueryBuilder = InsertQueryBuilder; | ||
class ColumnQueryBuilder { | ||
let ColumnQueryBuilder = class ColumnQueryBuilder { | ||
constructor(name, type, ...args) { | ||
this._name = name; | ||
this._type = type; | ||
this._charset = ""; | ||
this._args = []; | ||
this._autoIncrement = false; | ||
this._notNull = false; | ||
this._default = ""; | ||
this._name = ""; | ||
this._collation = ""; | ||
this._comment = ""; | ||
this._unique = false; | ||
this._unsigned = false; | ||
this._args.push(...args); | ||
this.Name = name; | ||
this.Type = type; | ||
this.Charset = ""; | ||
this.Args = []; | ||
this.AutoIncrement = false; | ||
this.NotNull = false; | ||
this.Default = ""; | ||
this.Collation = ""; | ||
this.Comment = ""; | ||
this.Unique = false; | ||
this.Unsigned = false; | ||
this.Args.push(...args); | ||
} | ||
notNull() { | ||
this._notNull = true; | ||
this.NotNull = true; | ||
return this; | ||
} | ||
unique() { | ||
this._unique = true; | ||
this.Unique = true; | ||
return this; | ||
} | ||
unsigned() { | ||
this._unsigned = true; | ||
this.Unsigned = true; | ||
return this; | ||
} | ||
autoIncrement() { | ||
this._autoIncrement = true; | ||
this.AutoIncrement = true; | ||
return this; | ||
} | ||
default(val) { | ||
this._default = val; | ||
this.Default = val; | ||
return this; | ||
} | ||
primaryKey() { | ||
this._primaryKey = true; | ||
this.PrimaryKey = true; | ||
return this; | ||
} | ||
comment(comment) { | ||
this._comment = comment; | ||
this.Comment = comment; | ||
return this; | ||
} | ||
charset(charset) { | ||
this._charset = charset; | ||
this.Charset = charset; | ||
return this; | ||
} | ||
collation(collation) { | ||
this._collation = collation; | ||
this.Collation = collation; | ||
return this; | ||
} | ||
} | ||
}; | ||
ColumnQueryBuilder = __decorate([ | ||
di_1.NewInstance(), | ||
di_1.Inject(di_1.Container), | ||
__metadata("design:paramtypes", [String, String, Object]) | ||
], ColumnQueryBuilder); | ||
exports.ColumnQueryBuilder = ColumnQueryBuilder; | ||
class TableQueryBuilder extends QueryBuilder { | ||
constructor(name, driver, container) { | ||
super(driver, container); | ||
constructor(container, driver, name) { | ||
super(container, driver, null); | ||
this._charset = ""; | ||
@@ -564,17 +630,22 @@ this._comment = ""; | ||
toDB() { | ||
return this._container.resolve(interfaces_1.TableQueryCompiler).compile(); | ||
return this._container.resolve(interfaces_1.TableQueryCompiler, [this]).compile(); | ||
} | ||
} | ||
exports.TableQueryBuilder = TableQueryBuilder; | ||
class SchemaQueryBuilder { | ||
constructor(driver, container) { | ||
let SchemaQueryBuilder = class SchemaQueryBuilder { | ||
constructor(container, driver) { | ||
this.container = container; | ||
this.driver = driver; | ||
this.container = container; | ||
} | ||
createTable(name, callback) { | ||
const builder = new TableQueryBuilder(name, this.driver, this.container); | ||
const builder = new TableQueryBuilder(this.container, this.driver, name); | ||
callback.call(this, builder); | ||
return this; | ||
return builder; | ||
} | ||
} | ||
}; | ||
SchemaQueryBuilder = __decorate([ | ||
di_1.NewInstance(), | ||
di_1.Inject(di_1.Container), | ||
__metadata("design:paramtypes", [di_1.Container, interfaces_1.OrmDriver]) | ||
], SchemaQueryBuilder); | ||
exports.SchemaQueryBuilder = SchemaQueryBuilder; | ||
@@ -581,0 +652,0 @@ Object.values(enums_1.ColumnType).forEach(type => { |
@@ -0,6 +1,9 @@ | ||
import "reflect-metadata"; | ||
export declare const MODEL_DESCTRIPTION_SYMBOL: unique symbol; | ||
export declare function Connection(name: string): any; | ||
export declare function TableName(name: string): any; | ||
export declare function Timestamps(createdColumn?: string, updatedColumn?: string): any; | ||
export declare function SoftDelete(deletedColumn?: string): any; | ||
export declare function PrimaryKey(keyName: string): any; | ||
export declare function Model(tableName: string): any; | ||
export declare function CreatedAt(): any; | ||
export declare function UpdatedAt(): any; | ||
export declare function SoftDelete(): any; | ||
export declare function Archived(): any; | ||
export declare function Primary(): any; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
require("reflect-metadata"); | ||
exports.MODEL_DESCTRIPTION_SYMBOL = Symbol.for("MODEL_DESCRIPTOR"); | ||
function Model(callback) { | ||
function _model(callback, base = false) { | ||
return (target, propertyKey, indexOrDescriptor) => { | ||
let metadata = target[exports.MODEL_DESCTRIPTION_SYMBOL]; | ||
let metadata = null; | ||
if (!base) { | ||
metadata = target.constructor[exports.MODEL_DESCTRIPTION_SYMBOL]; | ||
} | ||
else { | ||
metadata = target[exports.MODEL_DESCTRIPTION_SYMBOL]; | ||
} | ||
if (!metadata) { | ||
metadata = { | ||
Columns: [], | ||
Columns: null, | ||
Connection: null, | ||
ConnectionName: "", | ||
PrimaryKey: "", | ||
SoftDelete: null, | ||
SoftDelete: { | ||
DeletedAt: "" | ||
}, | ||
Archived: { | ||
ArchivedAt: "" | ||
}, | ||
TableName: "", | ||
Timestamps: null, | ||
Timestamps: { | ||
CreatedAt: "", | ||
UpdatedAt: "" | ||
}, | ||
}; | ||
if (!base) { | ||
target.constructor[exports.MODEL_DESCTRIPTION_SYMBOL] = metadata; | ||
} | ||
else { | ||
target[exports.MODEL_DESCTRIPTION_SYMBOL] = metadata; | ||
} | ||
} | ||
@@ -24,36 +44,59 @@ if (callback) { | ||
function Connection(name) { | ||
return Model((model) => { | ||
model.ConnectionName = name; | ||
}); | ||
return _model((model) => { | ||
model.Connection = name; | ||
}, true); | ||
} | ||
exports.Connection = Connection; | ||
function TableName(name) { | ||
return Model((model) => { | ||
model.TableName = name; | ||
function Model(tableName) { | ||
return _model((model) => { | ||
model.TableName = tableName; | ||
}, true); | ||
} | ||
exports.Model = Model; | ||
function CreatedAt() { | ||
return _model((model, target, propertyKey) => { | ||
const type = Reflect.getMetadata('design:type', target, propertyKey); | ||
if (type.name !== "Date") { | ||
throw Error("Proprety CreatedAt must be Date type"); | ||
} | ||
model.Timestamps.CreatedAt = propertyKey; | ||
}); | ||
} | ||
exports.TableName = TableName; | ||
function Timestamps(createdColumn, updatedColumn) { | ||
return Model((model) => { | ||
model.Timestamps = { | ||
CreatedAt: (createdColumn) ? createdColumn : "created_at", | ||
UpdatedAt: (updatedColumn) ? updatedColumn : "updated_at" | ||
}; | ||
exports.CreatedAt = CreatedAt; | ||
function UpdatedAt() { | ||
return _model((model, target, propertyKey) => { | ||
const type = Reflect.getMetadata('design:type', target, propertyKey); | ||
if (type.name !== "Date") { | ||
throw Error("Proprety UpdatedAt must be Date type"); | ||
} | ||
model.Timestamps.UpdatedAt = propertyKey; | ||
}); | ||
} | ||
exports.Timestamps = Timestamps; | ||
function SoftDelete(deletedColumn) { | ||
return Model((model) => { | ||
model.SoftDelete = { | ||
DeletedAt: (deletedColumn) ? deletedColumn : "deleted_at", | ||
}; | ||
exports.UpdatedAt = UpdatedAt; | ||
function SoftDelete() { | ||
return _model((model, target, propertyKey) => { | ||
const type = Reflect.getMetadata('design:type', target, propertyKey); | ||
if (type.name !== "Date") { | ||
throw Error("Proprety DeletedAt must be Date type"); | ||
} | ||
model.SoftDelete.DeletedAt = propertyKey; | ||
}); | ||
} | ||
exports.SoftDelete = SoftDelete; | ||
function PrimaryKey(keyName) { | ||
return Model((model) => { | ||
model.PrimaryKey = keyName; | ||
function Archived() { | ||
return _model((model, target, propertyKey) => { | ||
const type = Reflect.getMetadata('design:type', target, propertyKey); | ||
if (type.name !== "Date") { | ||
throw Error("Proprety DeletedAt must be Date type"); | ||
} | ||
model.Archived.ArchivedAt = propertyKey; | ||
}); | ||
} | ||
exports.PrimaryKey = PrimaryKey; | ||
exports.Archived = Archived; | ||
function Primary() { | ||
return _model((model, _target, propertyKey) => { | ||
model.PrimaryKey = propertyKey; | ||
}); | ||
} | ||
exports.Primary = Primary; | ||
//# sourceMappingURL=decorators.js.map |
@@ -9,1 +9,2 @@ export * from "./interfaces"; | ||
export * from "./decorators"; | ||
export * from "./hydrators"; |
@@ -13,2 +13,3 @@ "use strict"; | ||
__export(require("./decorators")); | ||
__export(require("./hydrators")); | ||
//# sourceMappingURL=index.js.map |
@@ -0,7 +1,10 @@ | ||
import { RawQuery } from './builders'; | ||
import { SORT_ORDER, WhereBoolean } from './enums'; | ||
import { IQueryStatement } from './statements'; | ||
import { WhereFunction } from './types'; | ||
import { ResolveStrategy, IContainer } from '@spinajs/di'; | ||
export interface IDriverOptions { | ||
Database?: string; | ||
User?: string; | ||
Password?: string; | ||
Host?: string; | ||
@@ -14,18 +17,20 @@ Port?: number; | ||
} | ||
export declare abstract class OrmDriver { | ||
static DBDriver: string; | ||
export declare abstract class OrmDriver extends ResolveStrategy { | ||
Options: IDriverOptions; | ||
constructor(options: IDriverOptions); | ||
abstract execute(stmt: string | object, params?: any[]): Promise<any[]>; | ||
Container: IContainer; | ||
constructor(container: IContainer, options: IDriverOptions); | ||
abstract execute(stmt: string | object, params?: any[]): Promise<any[] | any>; | ||
abstract ping(): Promise<void>; | ||
abstract connect(): Promise<void>; | ||
abstract disconnect(): void; | ||
abstract tableInfo(name: string, schema?: string): Promise<IColumnDescriptor[]>; | ||
abstract resolve(container: IContainer): void; | ||
} | ||
export interface IModelDescrtiptor { | ||
PrimaryKey: string; | ||
ConnectionName: string; | ||
Connection: string; | ||
TableName: string; | ||
Connection: OrmDriver; | ||
Timestamps?: IModelTimestampDescriptor; | ||
SoftDelete?: IModelSoftDeleteDescriptor; | ||
Timestamps: IModelTimestampDescriptor; | ||
SoftDelete: IModelSoftDeleteDescriptor; | ||
Archived: IModelArchivedDescriptor; | ||
Columns: IColumnDescriptor[]; | ||
@@ -41,3 +46,3 @@ } | ||
Nullable: boolean; | ||
PrimaryKey: string; | ||
PrimaryKey: boolean; | ||
AutoIncrement: boolean; | ||
@@ -59,2 +64,5 @@ Name: string; | ||
} | ||
export interface IModelArchivedDescriptor { | ||
ArchivedAt: string; | ||
} | ||
export interface IQueryLimit { | ||
@@ -72,3 +80,4 @@ limit?: number; | ||
Schema: string; | ||
setSchema(schema: string): IQueryBuilder; | ||
schema(schema: string): IQueryBuilder; | ||
from(table: string, alias?: string): this; | ||
} | ||
@@ -91,2 +100,3 @@ export interface ILimitBuilder { | ||
getColumns(): IQueryStatement[]; | ||
select(column: string | RawQuery, alias?: string): this; | ||
} | ||
@@ -155,1 +165,4 @@ export interface IWhereBuilder { | ||
} | ||
export declare abstract class ColumnQueryCompiler implements IQueryCompiler { | ||
abstract compile(): ICompilerOutput; | ||
} |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
class OrmDriver { | ||
constructor(options) { | ||
const di_1 = require("@spinajs/di"); | ||
class OrmDriver extends di_1.ResolveStrategy { | ||
constructor(container, options) { | ||
super(); | ||
this.Options = options; | ||
this.Container = container; | ||
} | ||
@@ -7,0 +10,0 @@ } |
@@ -1,2 +0,34 @@ | ||
export declare abstract class Model { | ||
import { IModelDescrtiptor } from "./interfaces"; | ||
import { WhereFunction } from './types'; | ||
import { RawQuery, SelectQueryBuilder } from './builders'; | ||
import { WhereOperators } from './enums'; | ||
export declare abstract class ModelBase<T> { | ||
get ModelDescriptor(): IModelDescrtiptor; | ||
get PrimaryKeyName(): string; | ||
get PrimaryKeyValue(): any; | ||
set PrimaryKeyValue(newVal: any); | ||
static all<U>(): Promise<U[]>; | ||
static where(column: string | boolean | WhereFunction | RawQuery | {}, operator?: WhereOperators | any, value?: any): SelectQueryBuilder; | ||
static find<U>(pks: any[]): Promise<U[]>; | ||
static find<U>(pks: any): Promise<U>; | ||
static findOrFail<U>(pk: any): Promise<U>; | ||
static firstOrCreate<U>(_pk: any): Promise<U>; | ||
static firstOrNew<U>(_pk: any): Promise<U>; | ||
static destroy(_pk: any | any[]): Promise<void>; | ||
constructor(data?: any); | ||
hydrate(data: any): void; | ||
dehydrate(): {}; | ||
destroy(): Promise<void>; | ||
save(): Promise<void>; | ||
abstract fresh(): Promise<T>; | ||
protected defaults(): void; | ||
} | ||
export declare const MODEL_STATIC_MIXINS: { | ||
where(column: string | boolean | {} | RawQuery | WhereFunction, operator?: any, value?: any): SelectQueryBuilder; | ||
all(): Promise<any[]>; | ||
find(pks: any): Promise<any>; | ||
findOrFail(pks: any): Promise<any>; | ||
destroy(pks: any): Promise<void>; | ||
firstOrCreate(pk: any): Promise<any>; | ||
firstOrNew(pk: any): Promise<any>; | ||
}; |
175
lib/model.js
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
class Model { | ||
const decorators_1 = require("./decorators"); | ||
const builders_1 = require("./builders"); | ||
const di_1 = require("@spinajs/di"); | ||
const orm_1 = require("./orm"); | ||
const hydrators_1 = require("./hydrators"); | ||
class ModelBase { | ||
get ModelDescriptor() { | ||
return this.constructor[decorators_1.MODEL_DESCTRIPTION_SYMBOL]; | ||
} | ||
get PrimaryKeyName() { | ||
return this.ModelDescriptor.PrimaryKey; | ||
} | ||
get PrimaryKeyValue() { | ||
return this[this.PrimaryKeyName]; | ||
} | ||
set PrimaryKeyValue(newVal) { | ||
this[this.PrimaryKeyName] = newVal; | ||
} | ||
static async all() { | ||
throw Error("Not implemented"); | ||
} | ||
static where(column, operator, value) { | ||
throw Error("Not implemented"); | ||
} | ||
static find(pks) { | ||
throw Error("Not implemented"); | ||
} | ||
static findOrFail(pk) { | ||
throw Error("Not implemented"); | ||
} | ||
static firstOrCreate(_pk) { | ||
throw Error("Not implemented"); | ||
} | ||
static firstOrNew(_pk) { | ||
throw Error("Not implemented"); | ||
} | ||
static destroy(_pk) { | ||
throw Error("Not implemented"); | ||
} | ||
constructor(data) { | ||
this.defaults(); | ||
if (data) { | ||
this.hydrate(data); | ||
} | ||
} | ||
hydrate(data) { | ||
di_1.DI.resolve(Array.ofType(hydrators_1.ModelHydrator)).forEach(h => h.hydrate(this, data)); | ||
} | ||
dehydrate() { | ||
var _a; | ||
const obj = {}; | ||
(_a = this.ModelDescriptor.Columns) === null || _a === void 0 ? void 0 : _a.forEach(c => { | ||
const val = this[c.Name]; | ||
obj[c.Name] = c.Converter ? c.Converter.toDB(val) : val; | ||
}); | ||
return obj; | ||
} | ||
async destroy() { | ||
if (!this.PrimaryKeyValue) { | ||
return; | ||
} | ||
await this.constructor.destroy(this.PrimaryKeyValue); | ||
} | ||
async save() { | ||
if (this.PrimaryKeyValue) { | ||
const { query } = _createQuery(this.constructor, builders_1.UpdateQueryBuilder); | ||
await query.update(this.dehydrate()).where(this.PrimaryKeyName, this.PrimaryKeyValue); | ||
} | ||
else { | ||
const { query } = _createQuery(this.constructor, builders_1.InsertQueryBuilder); | ||
const id = await query.values(this.dehydrate()); | ||
if (this.ModelDescriptor.Timestamps.UpdatedAt) { | ||
this[this.ModelDescriptor.Timestamps.CreatedAt] = new Date(); | ||
} | ||
this.PrimaryKeyValue = id[0]; | ||
} | ||
} | ||
defaults() { | ||
var _a; | ||
(_a = this.ModelDescriptor.Columns) === null || _a === void 0 ? void 0 : _a.forEach(c => { | ||
this[c.Name] = c.DefaultValue; | ||
}); | ||
if (this.ModelDescriptor.Timestamps.CreatedAt) { | ||
this[this.ModelDescriptor.Timestamps.CreatedAt] = new Date(); | ||
} | ||
} | ||
} | ||
exports.Model = Model; | ||
exports.ModelBase = ModelBase; | ||
function _descriptor(model) { | ||
return model[decorators_1.MODEL_DESCTRIPTION_SYMBOL]; | ||
} | ||
function _createQuery(model, query) { | ||
const dsc = _descriptor(model); | ||
if (!dsc) { | ||
throw new Error(`model ${model.name} does not have model descriptor. Use @model decorator on class`); | ||
} | ||
const orm = di_1.DI.get(orm_1.Orm); | ||
const driver = orm.Connections.get(dsc.Connection); | ||
if (!driver) { | ||
throw new Error(`model ${model.name} have invalid connection ${dsc.Connection}, please check your db config file or model connection name`); | ||
} | ||
const cnt = driver.Container; | ||
const qr = cnt.resolve(query, [driver, model]); | ||
qr.setTable(dsc.TableName); | ||
if (driver.Options.Database) { | ||
qr.schema(driver.Options.Database); | ||
} | ||
return { | ||
query: qr, | ||
description: dsc, | ||
model | ||
}; | ||
} | ||
exports.MODEL_STATIC_MIXINS = { | ||
where(column, operator, value) { | ||
const { query } = _createQuery(this, builders_1.SelectQueryBuilder); | ||
return query.where(column, operator, value); | ||
}, | ||
async all() { | ||
const { query } = _createQuery(this, builders_1.SelectQueryBuilder); | ||
return await query; | ||
}, | ||
async find(pks) { | ||
const { query, description } = _createQuery(this, builders_1.SelectQueryBuilder); | ||
const pkey = description.PrimaryKey; | ||
return await Array.isArray(pks) ? query.whereIn(pkey, pks) : query.where(pkey, pks).first(); | ||
}, | ||
async findOrFail(pks) { | ||
const { query, description, model } = _createQuery(this, builders_1.SelectQueryBuilder); | ||
const pkey = description.PrimaryKey; | ||
if (Array.isArray(pks)) { | ||
const ar = await query.whereIn(pkey, pks); | ||
if (ar.length !== pks.length) { | ||
throw new Error(`could not find all of pkeys in model ${model.name}`); | ||
} | ||
return ar; | ||
} | ||
return await query.where(pkey, pks).firstOrFail(); | ||
}, | ||
async destroy(pks) { | ||
var _a; | ||
const description = _descriptor(this); | ||
if ((_a = description.SoftDelete) === null || _a === void 0 ? void 0 : _a.DeletedAt) { | ||
const data = Array.isArray(pks) ? pks : [pks]; | ||
const { query } = _createQuery(this, builders_1.UpdateQueryBuilder); | ||
await query.whereIn(description.PrimaryKey, data.map(d => d.PrimaryKeyValue)).update({ | ||
[description.SoftDelete.DeletedAt]: new Date() | ||
}); | ||
} | ||
else { | ||
const { query } = _createQuery(this, builders_1.DeleteQueryBuilder); | ||
await query.whereIn(description.PrimaryKey, Array.isArray(pks) ? pks : [pks]); | ||
} | ||
}, | ||
async firstOrCreate(pk) { | ||
const { query, description } = _createQuery(this, builders_1.SelectQueryBuilder); | ||
let entity = await query.where(description.PrimaryKey, pk).first(); | ||
if (!entity) { | ||
entity = new (Function.prototype.bind.apply(this))(); | ||
await entity.save(); | ||
return entity; | ||
} | ||
return entity; | ||
}, | ||
async firstOrNew(pk) { | ||
const { query, description } = _createQuery(this, builders_1.SelectQueryBuilder); | ||
let entity = await query.where(description.PrimaryKey, pk).first(); | ||
if (!entity) { | ||
entity = new (Function.prototype.bind.apply(this))(); | ||
return entity; | ||
} | ||
return entity; | ||
}, | ||
}; | ||
//# sourceMappingURL=model.js.map |
import { AsyncResolveStrategy, IContainer } from "@spinajs/di"; | ||
import { ClassInfo } from "@spinajs/reflection"; | ||
import { OrmDriver } from "./interfaces"; | ||
import { Model } from "./model"; | ||
import { ModelBase } from "./model"; | ||
export declare class Orm extends AsyncResolveStrategy { | ||
Models: Array<ClassInfo<Model>>; | ||
Models: Array<ClassInfo<ModelBase<any>>>; | ||
Connections: Map<string, OrmDriver>; | ||
Container : IContainer; | ||
Container: IContainer; | ||
private Log; | ||
private Configuration; | ||
resolveAsync(container: IContainer): Promise<void>; | ||
} |
@@ -11,2 +11,5 @@ "use strict"; | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
@@ -16,18 +19,54 @@ const configuration_1 = require("@spinajs/configuration"); | ||
const di_2 = require("@spinajs/di"); | ||
const log_1 = require("@spinajs/log"); | ||
const reflection_1 = require("@spinajs/reflection"); | ||
const interfaces_1 = require("./interfaces"); | ||
const lodash_1 = __importDefault(require("lodash")); | ||
const model_1 = require("./model"); | ||
const decorators_1 = require("./decorators"); | ||
const CFG_PROPS = ["Database", "User", "Host", "Port", "Filename", "Driver", "Name"]; | ||
class Orm extends di_1.AsyncResolveStrategy { | ||
constructor() { | ||
super(...arguments); | ||
this.Connections = new Map(); | ||
} | ||
async resolveAsync(container) { | ||
const drivers = container.Registry.get(interfaces_1.OrmDriver); | ||
const connections = this.Configuration.get("db.connections"); | ||
for (const c of connections) { | ||
const driver = drivers.find(d => d.DbDriver === c.Driver); | ||
const connections = this.Configuration.get("db.connections", []); | ||
try { | ||
for (const c of connections) { | ||
const driver = container.resolve(c.Driver, [container, c]); | ||
if (!driver) { | ||
this.Log.warn(`No Orm driver was found for DB ${c.Driver}, connection: ${c.Name}`, lodash_1.default.pick(c, CFG_PROPS)); | ||
continue; | ||
} | ||
this.Connections.set(c.Name, driver); | ||
} | ||
await Promise.all(Array.from(this.Connections.values()).map((d) => { | ||
d.connect(); | ||
})); | ||
for (const m of this.Models) { | ||
for (const mixin in model_1.MODEL_STATIC_MIXINS) { | ||
m.type[mixin] = (model_1.MODEL_STATIC_MIXINS[mixin]).bind(m.type); | ||
} | ||
const descriptor = m.type[decorators_1.MODEL_DESCTRIPTION_SYMBOL]; | ||
if (descriptor) { | ||
const connection = this.Connections.get(descriptor.Connection); | ||
if (connection) { | ||
descriptor.Columns = await connection.tableInfo(descriptor.TableName, connection.Options.Database); | ||
} | ||
} | ||
} | ||
} | ||
catch (err) { | ||
this.Log.error("Cannot initialize ORM module", err); | ||
} | ||
} | ||
} | ||
__decorate([ | ||
reflection_1.FromFiles("/**/*.{ts,js}", "system.dirs.models"), | ||
reflection_1.ListFromFiles("/**/*.{ts,js}", "system.dirs.models"), | ||
__metadata("design:type", Array) | ||
], Orm.prototype, "Models", void 0); | ||
__decorate([ | ||
log_1.Logger({ module: "ORM" }), | ||
__metadata("design:type", Object) | ||
], Orm.prototype, "Log", void 0); | ||
__decorate([ | ||
di_2.Autoinject(), | ||
@@ -34,0 +73,0 @@ __metadata("design:type", configuration_1.Configuration) |
@@ -1,2 +0,2 @@ | ||
import { SelectQueryBuilder, WhereBuilder } from "./builders"; | ||
import { SelectQueryBuilder, WhereBuilder, RawQuery } from "./builders"; | ||
import { ColumnMethods, WhereOperators } from "./enums"; | ||
@@ -60,6 +60,6 @@ export interface IQueryStatementResult { | ||
export declare abstract class ColumnStatement implements IQueryStatement { | ||
protected _column: string; | ||
protected _column: string | RawQuery; | ||
protected _alias: string; | ||
constructor(column: string, alias?: string); | ||
get Column(): string; | ||
constructor(column: string | RawQuery, alias?: string); | ||
get Column(): string | RawQuery; | ||
get Alias(): string; | ||
@@ -69,2 +69,7 @@ get IsWildcard(): boolean; | ||
} | ||
export declare abstract class ColumnRawStatement implements IQueryStatement { | ||
RawQuery: RawQuery; | ||
constructor(RawQuery: RawQuery); | ||
abstract build(): IQueryStatementResult; | ||
} | ||
export declare abstract class ColumnMethodStatement extends ColumnStatement { | ||
@@ -71,0 +76,0 @@ protected _method: ColumnMethods; |
"use strict"; | ||
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { | ||
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; | ||
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); | ||
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; | ||
return c > 3 && r && Object.defineProperty(target, key, r), r; | ||
}; | ||
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 }); | ||
class RawQueryStatement { | ||
const builders_1 = require("./builders"); | ||
const enums_1 = require("./enums"); | ||
const di_1 = require("@spinajs/di"); | ||
let RawQueryStatement = class RawQueryStatement { | ||
constructor(query, bindings) { | ||
@@ -8,5 +20,9 @@ this._query = query || ""; | ||
} | ||
} | ||
}; | ||
RawQueryStatement = __decorate([ | ||
di_1.NewInstance(), | ||
__metadata("design:paramtypes", [String, Array]) | ||
], RawQueryStatement); | ||
exports.RawQueryStatement = RawQueryStatement; | ||
class BetweenStatement { | ||
let BetweenStatement = class BetweenStatement { | ||
constructor(column, val, not) { | ||
@@ -17,11 +33,19 @@ this._val = val || []; | ||
} | ||
} | ||
}; | ||
BetweenStatement = __decorate([ | ||
di_1.NewInstance(), | ||
__metadata("design:paramtypes", [String, Array, Boolean]) | ||
], BetweenStatement); | ||
exports.BetweenStatement = BetweenStatement; | ||
class WhereQueryStatement { | ||
let WhereQueryStatement = class WhereQueryStatement { | ||
constructor(builder) { | ||
this._builder = builder; | ||
} | ||
} | ||
}; | ||
WhereQueryStatement = __decorate([ | ||
di_1.NewInstance(), | ||
__metadata("design:paramtypes", [builders_1.WhereBuilder]) | ||
], WhereQueryStatement); | ||
exports.WhereQueryStatement = WhereQueryStatement; | ||
class WhereStatement { | ||
let WhereStatement = class WhereStatement { | ||
constructor(column, operator, value) { | ||
@@ -32,5 +56,9 @@ this._column = column; | ||
} | ||
} | ||
}; | ||
WhereStatement = __decorate([ | ||
di_1.NewInstance(), | ||
__metadata("design:paramtypes", [String, String, Object]) | ||
], WhereStatement); | ||
exports.WhereStatement = WhereStatement; | ||
class InStatement { | ||
let InStatement = class InStatement { | ||
constructor(column, val, not) { | ||
@@ -41,11 +69,19 @@ this._val = val || []; | ||
} | ||
} | ||
}; | ||
InStatement = __decorate([ | ||
di_1.NewInstance(), | ||
__metadata("design:paramtypes", [String, Array, Boolean]) | ||
], InStatement); | ||
exports.InStatement = InStatement; | ||
class SelectQueryStatement { | ||
let SelectQueryStatement = class SelectQueryStatement { | ||
constructor(builder) { | ||
this._builder = builder; | ||
} | ||
} | ||
}; | ||
SelectQueryStatement = __decorate([ | ||
di_1.NewInstance(), | ||
__metadata("design:paramtypes", [builders_1.SelectQueryBuilder]) | ||
], SelectQueryStatement); | ||
exports.SelectQueryStatement = SelectQueryStatement; | ||
class ExistsQueryStatement extends SelectQueryStatement { | ||
let ExistsQueryStatement = class ExistsQueryStatement extends SelectQueryStatement { | ||
constructor(builder, not) { | ||
@@ -55,5 +91,9 @@ super(builder); | ||
} | ||
} | ||
}; | ||
ExistsQueryStatement = __decorate([ | ||
di_1.NewInstance(), | ||
__metadata("design:paramtypes", [builders_1.SelectQueryBuilder, Boolean]) | ||
], ExistsQueryStatement); | ||
exports.ExistsQueryStatement = ExistsQueryStatement; | ||
class InSetStatement { | ||
let InSetStatement = class InSetStatement { | ||
constructor(column, val, not) { | ||
@@ -64,5 +104,9 @@ this._val = val || []; | ||
} | ||
} | ||
}; | ||
InSetStatement = __decorate([ | ||
di_1.NewInstance(), | ||
__metadata("design:paramtypes", [String, Array, Boolean]) | ||
], InSetStatement); | ||
exports.InSetStatement = InSetStatement; | ||
class ColumnStatement { | ||
let ColumnStatement = class ColumnStatement { | ||
constructor(column, alias) { | ||
@@ -79,7 +123,20 @@ this._column = column || ""; | ||
get IsWildcard() { | ||
if (this._column instanceof builders_1.RawQuery) { | ||
return false; | ||
} | ||
return this._column && this._column.trim() === "*"; | ||
} | ||
}; | ||
ColumnStatement = __decorate([ | ||
di_1.NewInstance(), | ||
__metadata("design:paramtypes", [Object, String]) | ||
], ColumnStatement); | ||
exports.ColumnStatement = ColumnStatement; | ||
class ColumnRawStatement { | ||
constructor(RawQuery) { | ||
this.RawQuery = RawQuery; | ||
} | ||
} | ||
exports.ColumnStatement = ColumnStatement; | ||
class ColumnMethodStatement extends ColumnStatement { | ||
exports.ColumnRawStatement = ColumnRawStatement; | ||
let ColumnMethodStatement = class ColumnMethodStatement extends ColumnStatement { | ||
constructor(column, method, alias) { | ||
@@ -89,4 +146,8 @@ super(column, alias); | ||
} | ||
} | ||
}; | ||
ColumnMethodStatement = __decorate([ | ||
di_1.NewInstance(), | ||
__metadata("design:paramtypes", [String, String, String]) | ||
], ColumnMethodStatement); | ||
exports.ColumnMethodStatement = ColumnMethodStatement; | ||
//# sourceMappingURL=statements.js.map |
{ | ||
"name": "@spinajs/orm", | ||
"version": "1.0.6", | ||
"version": "1.0.7", | ||
"description": "SpinaJS Orm module", | ||
@@ -5,0 +5,0 @@ "main": "lib/index.js", |
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
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
142157
39
1890