@fxjs/orm
Advanced tools
Comparing version 1.7.3 to 1.8.0
declare module "events" { | ||
export const EventEmitter: typeof Class_EventEmitter | ||
} | ||
declare namespace FxOrmNSSqlQueryNS { | ||
export class Query { | ||
constructor(dialect: string); | ||
constructor(options: { | ||
dialect: string; | ||
}); | ||
static Text(type: string): TextQuery; | ||
static Comparators: string[]; | ||
static between(a: number, b: number): Comparator; | ||
static not_between(a: number, b: number): Comparator; | ||
static like(expression: string): Comparator; | ||
static eq(value: any): Comparator; | ||
static ne(value: any): Comparator; | ||
static gt(value: any): Comparator; | ||
static gte(value: any): Comparator; | ||
static lt(value: any): Comparator; | ||
static lte(value: any): Comparator; | ||
escapeId(id: string): string; | ||
escapeId(id: string, table: string): string; | ||
escapeVal(value: any): string; | ||
select(): SelectQuery; | ||
insert(): InsertQuery; | ||
update(): UpdateQuery; | ||
remove(): RemoveQuery; | ||
} | ||
export interface Comparator { | ||
sql_comparator(): string; | ||
from?: any; | ||
to?: any; | ||
expr?: string; | ||
value?: any; | ||
} | ||
export interface TextQuery { | ||
data: any; | ||
type: string; | ||
} | ||
export interface SelectQuery { | ||
select(fields: string): SelectQuery; | ||
calculateFoundRows: SelectQuery; | ||
as(alias: string): SelectQuery; | ||
fun(fun: string, column: string, alias: string): SelectQuery; | ||
from(table: string, from_id: string, to_id: string): SelectQuery; | ||
from(table: string, from_id: string, to_table: string, to_id: string): SelectQuery; | ||
where(...args: any[]): SelectQuery; | ||
whereExists(table: string, table_link: string, link: string, conditions: { [column: string]: any }): SelectQuery; | ||
groupBy(...columns: string[]): SelectQuery; | ||
offset(offset: number): SelectQuery; | ||
limit(limit: number): SelectQuery; | ||
order(column: string, direction: string): SelectQuery; | ||
build(): string; | ||
} | ||
export interface InsertQuery { | ||
into(table: string): InsertQuery; | ||
set(values: { [key: string]: any }[]): InsertQuery; | ||
build(): string; | ||
} | ||
export interface UpdateQuery { | ||
into(table: string): UpdateQuery; | ||
set(values: { [column: string]: any }): UpdateQuery; | ||
where(...conditions: { [column: string]: any }[]): UpdateQuery; | ||
build(): string; | ||
} | ||
export interface RemoveQuery { | ||
from(table: string): RemoveQuery; | ||
where(...conditions: { [column: string]: any }[]): RemoveQuery; | ||
build(): string; | ||
} | ||
} | ||
} |
declare namespace FxOrmDb { | ||
interface DatabaseBase { | ||
on: (ev) => void; | ||
execute: (sql: string) => void; | ||
on: { | ||
<T=any>(ev: string, func: FxOrmNS.GenericCallback<T>): void | ||
}; | ||
execute: { | ||
(sql: string, ...args: any[]): any[]; | ||
} | ||
end?: (cb: Function) => void; | ||
close?: () => void; | ||
connect?: (cb: Function) => void | ||
query?: Function; | ||
end?: { | ||
(cb: FxOrmNS.VoidCallback): void | ||
}; | ||
connect?: { | ||
(cb: FxOrmNS.GenericCallback<FxOrmNS.IDbConnection>): void | ||
} | ||
// useless now | ||
pool: any | ||
} | ||
interface DatabaseBase_SQLite extends DatabaseBase { | ||
close: { | ||
<T=any>(cb?: FxOrmNS.GenericCallback<T>): void | ||
} | ||
all: { | ||
<T=any>(query: string, cb?: FxOrmNS.GenericCallback<T>): void | ||
} | ||
} | ||
interface DatabaseBase_MySQL extends DatabaseBase { | ||
conn: FxOrmNS.IDbConnection; | ||
opts: FxOrmNS.IDBConnectionConfig; | ||
ping: { | ||
(cb?: FxOrmNS.VoidCallback): void | ||
} | ||
} | ||
} |
@@ -15,6 +15,12 @@ declare namespace FxOrmNS { | ||
declare namespace FxOrmError { | ||
interface BatchOperationInstanceErrorItem extends Error { | ||
interface ExtendedError extends Error { | ||
code?: number | string | ||
[ext: string]: any | ||
} | ||
interface BatchOperationInstanceErrorItem extends ExtendedError { | ||
index: number | ||
instance: FxOrmNS.Instance | ||
instance: FxOrmInstance.Instance | ||
} | ||
} |
@@ -1,841 +0,3 @@ | ||
/// <reference types="fibjs" /> | ||
/// <reference types="@fibjs/enforce" /> | ||
/// <reference types="@fxjs/sql-query" /> | ||
/// <reference path="ORM.d.ts" /> | ||
/// <reference path="3rd.d.ts" /> | ||
/// <reference path="Error.d.ts" /> | ||
/// <reference path="Adapter.d.ts" /> | ||
/// <reference path="Validators.d.ts" /> | ||
// fix fibjs types' missing | ||
declare var console: any | ||
declare namespace FxOrmNS { | ||
/* Connection About Patch :start */ | ||
interface InstanceDataPayload { | ||
[key: string]: any | ||
} | ||
interface ExtensibleError extends Error { | ||
[extensibleProperty: string]: any | ||
} | ||
/** | ||
* it should be defined in 'orm' but there is not, so we should fix it | ||
*/ | ||
interface ConnInstanceInOrmConnDriverDB { | ||
begin(): void; | ||
close(): void; | ||
commit(): void; | ||
rollback(): void; | ||
trans(func: Function): boolean | ||
execute(sql: string, ...args: any[]): any[]; | ||
hasMany?: Function; | ||
remove?: Function; | ||
propertyToValue?: Function; | ||
insert?: Function; | ||
} | ||
interface DbInstanceInOrmConnDriver { | ||
conn: ConnInstanceInOrmConnDriverDB | ||
} | ||
export interface OrigOrmExecQueryOpts { | ||
[key: string]: any; | ||
} | ||
export interface OrigOrmConnDriver { | ||
// dialog type | ||
dialect: string; | ||
propertyToValue: Function; | ||
valueToProperty: Function; | ||
insert: Function; | ||
db: DbInstanceInOrmConnDriver | ||
} | ||
/** | ||
* then we should patch still | ||
*/ | ||
export interface PatchedOrmConnDriver extends OrigOrmConnDriver { | ||
execQuerySync: (query: FxOrmNSSqlQueryNS.Query, opt: OrigOrmExecQueryOpts) => any | ||
} | ||
export interface OrmConnectionOpts { | ||
} | ||
/* Connection About Patch :end */ | ||
interface ORMMethod__CommonCallback { | ||
(err: Error): void | ||
} | ||
interface TransformFibOrmModel2InstanceOptions extends ModelOptions {} | ||
export interface FibORM extends ORM { | ||
/* all fixed: start */ | ||
models: { [key: string]: Model }; | ||
use(plugin: string, options?: any): FibORM; | ||
use(plugin: Plugin, options?: any): FibORM; | ||
define(name: string, properties: { [key: string]: OrigModelPropertyDefinition }, opts?: ModelOptions): Model; | ||
ping(callback: ORMMethod__CommonCallback): FibORM; | ||
close(callback: ORMMethod__CommonCallback): FibORM; | ||
load(file: string, callback: ORMMethod__CommonCallback): any; | ||
sync(callback: ORMMethod__CommonCallback): FibORM; | ||
drop(callback: ORMMethod__CommonCallback): FibORM; | ||
/* all fixed: end */ | ||
/* memeber patch: start */ | ||
driver: PatchedOrmConnDriver | ||
begin: () => any | ||
commit: () => any | ||
rollback: () => any | ||
trans: (func: Function) => any | ||
syncSync(): void; | ||
[extraMember: string]: any; | ||
/* memeber patch: end */ | ||
} | ||
// bad annotation but 'db' is used as like 'orm' ever, so we use 'FibOrmDB' to substitute FibORM | ||
type FibOrmDB = FibORM | ||
export interface FibORMIConnectionOptions extends IConnectionOptions { | ||
timezone: string; | ||
} | ||
type AssociationKeyComputation = Function | string | ||
interface AssociationDefinitionOptions { | ||
name?: string; | ||
model?: Model; | ||
field?: ModelPropertyDefinitionHash | ||
// is the association is extendsTo | ||
extension?: boolean; | ||
required?: boolean; | ||
reversed?: boolean; | ||
accessor?: string; | ||
reverseAccessor?: string; | ||
autoFetch?: boolean; | ||
autoFetchLimit?: number; | ||
} | ||
interface InstanceAssociationItem { | ||
name: string; | ||
field?: ModelPropertyDefinitionHash; | ||
// is the association is extendsTo | ||
extension?: boolean; | ||
getAccessor: string; | ||
setAccessor: string; | ||
hasAccessor: string; | ||
delAccessor: string; | ||
addAccessor?: string; | ||
model: Model; | ||
reversed?: boolean; | ||
autoFetch: boolean; | ||
autoFetchLimit: number | ||
} | ||
interface AssociationDefinitionOptions_HasOne extends AssociationDefinitionOptions { | ||
reverse?: string; | ||
} | ||
interface AssociationDefinitionOptions_HasMany extends AssociationDefinitionOptions { | ||
reverse?: string; | ||
// is association property a primary key | ||
key?: boolean | ||
mergeId?: string | ||
mergeAssocId?: string | ||
reverseAssociation?: string | ||
hooks?: HasManyHooks | ||
mergeTable?: string | ||
association?: string | ||
getAccessor?: string; | ||
setAccessor?: string; | ||
hasAccessor?: string; | ||
delAccessor?: string; | ||
addAccessor?: string; | ||
} | ||
interface InstanceAssociationItem_ExtendTos extends InstanceAssociationItem { | ||
field: ModelPropertyDefinitionHash; | ||
table: string; | ||
} | ||
interface InstanceAssociationItem_HasOne extends InstanceAssociationItem { | ||
field?: ModelPropertyDefinitionHash; | ||
reverse?: string; | ||
// template name | ||
accessor?: string; | ||
reverseAccessor?: string; | ||
addAccessor?: string; | ||
required?: boolean; | ||
extension?: boolean; | ||
mapsTo?: { | ||
[key: string]: any; | ||
} | ||
} | ||
interface InstanceAssociationItem_HasMany extends InstanceAssociationItem { | ||
props: ResolvedModelPropertyDefinitionHash | ||
hooks: Hooks | ||
field?: ModelPropertyDefinitionHash | ||
mergeTable: string | ||
mergeId: string | ||
mergeAssocId: string | ||
getAccessor: string | ||
setAccessor: string | ||
hasAccessor: string | ||
delAccessor: string | ||
addAccessor: string | ||
} | ||
interface InnerInstanceOptions extends ModelOptions { | ||
one_associations: InstanceAssociationItem_HasOne[] | ||
many_associations: InstanceAssociationItem_HasMany[] | ||
extend_associations: InstanceAssociationItem_ExtendTos[] | ||
association_properties: any | ||
fieldToPropertyMap: any | ||
associations?: InnerInstanceOptionsAssociationInfoItem[] | ||
} | ||
// for compability | ||
type InstanceOptions = InnerInstanceOptions | ||
interface InnerInstanceOptionsAssociationInfoItem { | ||
value: any | ||
changed: boolean | ||
} | ||
interface PatchedSyncfiedModelOrInstance { | ||
/** | ||
* @important | ||
* | ||
* methods patchSyncfied by 'fib-orm' | ||
*/ | ||
countSync: Function; | ||
firstSync: Function; | ||
lastSync: Function; | ||
allSync: Function; | ||
whereSync: Function; | ||
findSync: Function; | ||
removeSync: Function; | ||
runSync: Function; | ||
} | ||
interface PatchedSyncfiedInstanceWithDbWriteOperation extends PatchedSyncfiedModelOrInstance { | ||
saveSync: Function; | ||
removeSync: Function; | ||
validateSync: Function; | ||
modelSync: Function; | ||
} | ||
interface PatchedSyncfiedInstanceWithAssociations { | ||
/** | ||
* generated by association, but you don't know what it is | ||
*/ | ||
/* getXxx: Function; */ | ||
/* setXxx: Function; */ | ||
/* removeXxx: Function; */ | ||
/* findByXxx: Function; */ | ||
[associationFunc: string]: Function; | ||
} | ||
interface ModelPropertyDefinition { | ||
// ? | ||
name?: string | ||
/** | ||
* text | number | integer | boolean | date | enum | object | <del>point</del> | binary | serial | ||
* view details in https://github.com/dresende/node-orm2/wiki/Model-Properties | ||
*/ | ||
type: string | ||
// has unique constrain | ||
unique?: boolean | ||
// is primary key | ||
key?: boolean | ||
// is required | ||
required?: boolean | ||
// whether building index for this field | ||
index?: boolean | ||
defaultValue?: any | ||
unsigned?: boolean | ||
size?: number | ||
values?: any[] | ||
time?: boolean | ||
big?: boolean | ||
mapsTo?: string | ||
alwaysValidate?: boolean | ||
enumerable?: boolean | ||
} | ||
type OrigDetailedModelProperty = ModelPropertyDefinition | ||
interface OrigDetailedModelPropertyHash { | ||
[key: string]: OrigDetailedModelProperty | ||
} | ||
// TODO: finish that | ||
interface InstanceProperty extends ModelPropertyDefinition { | ||
} | ||
type ComplexModelPropertyDefinition = ModelPropertyDefinition | | ||
String | Boolean | Number | Date | Class_Buffer | any[] | ||
// for compatibility | ||
type OrigModelPropertyDefinition = ComplexModelPropertyDefinition | ||
interface ModelPropertyDefinitionHash { | ||
[key: string]: ComplexModelPropertyDefinition | ||
} | ||
interface ResolvedModelPropertyDefinitionHash { | ||
[key: string]: ModelPropertyDefinition | ||
} | ||
type OrigAggreteGenerator = (...args: any[]) => IAggregated | ||
interface OrigHooks extends Hooks { | ||
afterAutoFetch?: (next?) => void | ||
} | ||
export interface ExtendModelWrapper { | ||
// 'hasOne', 'hasMany' | ||
type: string; | ||
reversed?: boolean; | ||
model: FibOrmFixedExtendModel; | ||
} | ||
export interface FibOrmFixedExtendModel extends Model { | ||
model_name: string; | ||
} | ||
export interface FibOrmFindLikeQueryObject { | ||
[key: string]: any; | ||
} | ||
export interface FibOrmFixedModelInstanceFn { | ||
(model: Model, opts: object): Instance | ||
new(model: Model, opts: object): Instance | ||
} | ||
export interface FibOrmPatchedSyncfiedInstantce extends PatchedSyncfiedInstanceWithDbWriteOperation, PatchedSyncfiedInstanceWithAssociations { | ||
} | ||
export interface IChainFibORMFind extends PatchedSyncfiedModelOrInstance, FxOrmNSSqlQueryNS.SelectQuery { | ||
only(args: string | string[]): IChainFibORMFind; | ||
only(...args: string[]): IChainFibORMFind; | ||
order(...order: string[]): IChainFibORMFind; | ||
} | ||
/* Orm About Patch :end */ | ||
/* instance/model computation/transform about :start */ | ||
export interface ModelAutoFetchOptions { | ||
autoFetchLimit?: number | ||
autoFetch?: boolean | ||
} | ||
export interface InstanceAutoFetchOptions extends ModelAutoFetchOptions { | ||
} | ||
export interface ModelExtendOptions { | ||
} | ||
export interface InstanceExtendOptions extends ModelExtendOptions { | ||
} | ||
/* instance/model computation/transform about :end */ | ||
/* query conditions :start */ | ||
type QueryConditionInTypeType = string | number | ||
type QueryCondition_SimpleEq = { [key: string]: any } | ||
type QueryCondition_eq = QueryCondition_SimpleEq | { [key: string]: { "eq": any } } | ||
type QueryCondition_ne = { [key: string]: { "ne": any } } | ||
type QueryCondition_gt = { [key: string]: { "gt": number } } | ||
type QueryCondition_gte = { [key: string]: { "gte": number } } | ||
type QueryCondition_lt = { [key: string]: { "lt": number } } | ||
type QueryCondition_lte = { [key: string]: { "lte": number } } | ||
type QueryCondition_like = { [key: string]: { "like": string } } | ||
type QueryCondition_not_like = { [key: string]: { "not_like": string } } | ||
type QueryCondition_between = { [key: string]: { "between": [number, number] } } | ||
type QueryCondition_not_between = { [key: string]: { "not_between": [number, number] } } | ||
type QueryCondition_in = { [key: string]: { "in": QueryConditionInTypeType[] } } | ||
type QueryCondition_not_in = { [key: string]: { "not_in": QueryConditionInTypeType[] } } | ||
type QueryConditionAtomicType = | ||
QueryCondition_eq | | ||
QueryCondition_ne | | ||
QueryCondition_gt | | ||
QueryCondition_gte | | ||
QueryCondition_lt | | ||
QueryCondition_lte | | ||
QueryCondition_like | | ||
QueryCondition_not_like | | ||
QueryCondition_between | | ||
QueryCondition_not_between | | ||
QueryCondition_in | | ||
QueryCondition_not_in | ||
interface QueryConditions { | ||
or?: QueryConditionAtomicType[] | ||
[query_field: string]: QueryConditionAtomicType | ||
} | ||
/* query conditions :end */ | ||
/** | ||
* Parameter Type Interfaces | ||
**/ | ||
interface ModelAssociationMethod__ComputationPayload__Merge { | ||
from: { table: string, field: string | string[] } | ||
to: { table: string, field: string | string[] } | ||
where: [string, ModelMethod__FindConditions] | ||
table?: string | ||
} | ||
export interface ModelMethod__FindOptions { | ||
limit?: number; | ||
order?: any; | ||
only? | ||
offset?: number; | ||
} | ||
export interface ModelAssociationMethod__Options { | ||
autoFetch: boolean | ||
cascadeRemove: boolean | ||
autoSave: boolean | ||
identityCache: boolean | ||
autoFetchLimit: number | ||
__merge: ModelAssociationMethod__ComputationPayload__Merge | ||
extra: ModelPropertyDefinitionHash | any[] | ||
extra_info: { | ||
table: string | ||
id: any | ||
id_prop | ||
assoc_prop | ||
} | ||
} | ||
export interface ModelAssociationMethod__FindOptions extends ModelMethod__FindOptions, ModelAssociationMethod__Options { | ||
} | ||
export interface ModelAssociationMethod__GetOptions extends ModelMethod__FindOptions, ModelAssociationMethod__Options { | ||
} | ||
export interface ModelMethod__FindConditions { | ||
[property: string]: any | ||
} | ||
export interface ModelMethod__CommonCallback { | ||
(err: Error, results: Instance[]): void | ||
} | ||
export interface ModelMethod__CountCallback { | ||
(err: Error, count?: number): void | ||
} | ||
export interface Model extends OrigHooks, PatchedSyncfiedModelOrInstance { | ||
(): Instance; | ||
(...ids: any[]): Instance; | ||
new(): Instance; | ||
new(...ids: any[]): Instance; | ||
properties: { [property: string]: OrigDetailedModelProperty }; | ||
settings: SettingInstance; | ||
drop(callback?: (err: Error) => void): Model; | ||
sync(callback?: (err: Error) => void): Model; | ||
get(...args: any[]): Model; | ||
find(): any /* Model|IChainFind */; | ||
find(conditions: ModelMethod__FindConditions, callback?: ModelMethod__CommonCallback): Model; | ||
find(conditions: ModelMethod__FindConditions, options: ModelMethod__FindOptions, callback?: ModelMethod__CommonCallback): Model; | ||
find(conditions: ModelMethod__FindConditions, limit: number, order: string[], callback?: ModelMethod__CommonCallback): Model; | ||
find(conditions: ModelMethod__FindConditions): IChainFind; | ||
all(conditions: ModelMethod__FindConditions, callback?: ModelMethod__CommonCallback): Model; | ||
all(conditions: ModelMethod__FindConditions, options: ModelMethod__FindOptions, callback?: ModelMethod__CommonCallback): Model; | ||
all(conditions: ModelMethod__FindConditions, limit: number, order: string[], callback?: ModelMethod__CommonCallback): Model; | ||
one(conditions: ModelMethod__FindConditions, callback: (err: Error, result: Instance) => void): Model; | ||
one(conditions: ModelMethod__FindConditions, options: ModelMethod__FindOptions, callback: (err: Error, result: Instance) => void): Model; | ||
one(conditions: ModelMethod__FindConditions, limit: number, order: string[], callback: (err: Error, result: Instance) => void): Model; | ||
count(callback: ModelMethod__CountCallback): Model; | ||
count(conditions: ModelMethod__FindConditions, callback: ModelMethod__CountCallback): Model; | ||
aggregate(conditions: ModelMethod__FindConditions): IAggregated; | ||
aggregate(properties: string[]): IAggregated; | ||
aggregate(conditions: ModelMethod__FindConditions, properties: string[]): IAggregated; | ||
exists(id: any, callback: (err: Error, exists: boolean) => void): Model; | ||
exists(...args: any[]): Model; | ||
create(data: { [property: string]: any; }, callback: (err: Error, instance: Instance) => void): Model; | ||
create(...args: any[]): Model; | ||
clear(...args: any): Model; | ||
table: string; | ||
// id: string[]; | ||
id: string; | ||
/* fix or patch :start */ | ||
allProperties: { [key: string]: OrigDetailedModelProperty } | ||
/** | ||
* methods used to add associations | ||
*/ | ||
// hasOne: (...args: any[]) => any; | ||
hasOne: { | ||
(assoc_name: string, ext_model: Model, assoc_options?: AssociationDefinitionOptions_HasOne): FibOrmFixedExtendModel | ||
(assoc_name: string, assoc_options?: AssociationDefinitionOptions_HasOne): FibOrmFixedExtendModel | ||
} | ||
hasMany: { | ||
(assoc_name: string, ext_model: Model, assoc_options?: AssociationDefinitionOptions_HasMany): FibOrmFixedExtendModel | ||
(assoc_name: string, ext_model: Model, assoc_props?: ModelPropertyDefinitionHash, assoc_options?: AssociationDefinitionOptions_HasMany): FibOrmFixedExtendModel | ||
} | ||
extendsTo: (...args: any[]) => Model; | ||
extends: { [extendModel: string]: ExtendModelWrapper }; | ||
/* fix or patch :end */ | ||
[property: string]: any; | ||
} | ||
// just for compatible | ||
type FibOrmFixedModel = Model | ||
export interface Instance { | ||
on(event: string, callback): Instance; | ||
save(): Instance; | ||
save(data: { [property: string]: any; }, callback: (err: Error) => void): Instance; | ||
save(data: { [property: string]: any; }, options: any, callback: (err: Error) => void): Instance; | ||
saved(): boolean; | ||
remove(callback: (err: Error) => void): Instance; | ||
isInstance(): boolean; | ||
isPersisted(): boolean; | ||
isShell(): boolean; | ||
validate(callback: (errors: Error[]) => void); | ||
/* all fixed: start */ | ||
on(event: string, callback): Instance; | ||
save(callback?: ORMMethod__CommonCallback): Instance; | ||
save(data: { [property: string]: any; }, callback?: ORMMethod__CommonCallback): Instance; | ||
save(data: { [property: string]: any; }, options: any, callback?: ORMMethod__CommonCallback): Instance; | ||
saved(): boolean; | ||
remove(callback?: ORMMethod__CommonCallback): Instance; | ||
/** | ||
* @noenum | ||
*/ | ||
isInstance(): boolean; | ||
/** | ||
* @noenum | ||
*/ | ||
isPersisted(): boolean; | ||
/** | ||
* @noenum | ||
*/ | ||
isShell(): boolean; | ||
validate(callback: (errors: Error[]) => void); | ||
/* all fixed: end */ | ||
/* missing fix: start */ | ||
/** | ||
* @noenum | ||
*/ | ||
set: Function; | ||
markAsDirty: (propName?) => void; | ||
dirtyProperties: {[key: string]: any}; | ||
/** | ||
* @noenum | ||
*/ | ||
__singleton_uid(): string | number; | ||
/** | ||
* @noenum | ||
*/ | ||
__opts?: InstanceOptions; | ||
/** | ||
* @noenum | ||
*/ | ||
// model: Model; | ||
model(): Model; | ||
/* missing fix: end */ | ||
[extraProperty: string]: any; | ||
} | ||
// patch the missing field defined in orm/lib/Instance.js (such as defined by Object.defineProperty) | ||
type FibOrmFixedModelInstance = Instance | ||
interface ValidationOptionHash { | ||
[validation: string]: enforce.IValidator | enforce.IValidator[] | ||
} | ||
export interface ModelOptions { | ||
id?: string[]; | ||
autoFetch?: boolean; | ||
autoFetchLimit?: number; | ||
cacheFetch?: boolean; | ||
hooks?: Hooks; | ||
validations?: ValidationOptionHash | ||
methods?: { [name: string]: Function }; | ||
[extensibleProperty: string]: any; | ||
} | ||
// just for compatible | ||
type FibOrmFixedModelOptions = ModelOptions | ||
export interface Hooks { | ||
beforeValidation?: (next?) => void; | ||
beforeCreate?: (next?) => void; | ||
afterCreate?: (next?) => void; | ||
beforeSave?: (next?) => void; | ||
afterSave?: (success?: boolean) => void; | ||
afterLoad?: (success?: boolean) => void; | ||
afterAutoFetch?: (next?) => void; | ||
beforeRemove?: (next?) => void; | ||
afterRemove?: (success?: boolean) => void; | ||
} | ||
export interface HasManyHooks { | ||
beforeSave?: { | ||
(next?: Function): void; | ||
(extra, next: Function): void; | ||
} | ||
} | ||
export interface IConnectionOptions { | ||
protocol: string; | ||
host?: string; | ||
port?: number; | ||
auth?: string; | ||
username?: string; | ||
password?: string; | ||
database?: string; | ||
pool?: boolean; | ||
debug?: boolean; | ||
} | ||
export interface IAggregated { | ||
groupBy(...columns: string[]): IAggregated; | ||
limit(limit: number): IAggregated; | ||
limit(offset: number, limit: number): IAggregated; | ||
order(...order: string[]): IAggregated; | ||
select(columns: string[]): IAggregated; | ||
select(...columns: string[]): IAggregated; | ||
as(alias: string): IAggregated; | ||
call(fun: string, args: any[]): IAggregated; | ||
get(callback: (err: Error, instance: Instance) => void); | ||
} | ||
export interface IChainFind { | ||
find(conditions: ModelMethod__FindConditions): IChainFind; | ||
only(...args: string[]): IChainFind; | ||
limit(limit: number): IChainFind; | ||
offset(offset: number): IChainFind; | ||
run(callback?: ModelMethod__CommonCallback): void; | ||
count(callback: ModelMethod__CountCallback): void; | ||
remove(callback: (err: Error) => void): void; | ||
save(callback: (err: Error) => void): void; | ||
each(callback: (result: Instance) => void): void; | ||
each(): IChainFind; | ||
filter(callback: (result: Instance) => boolean): IChainFind; | ||
sort(callback: (a: Instance, b: Instance) => boolean): IChainFind; | ||
get(callback: (results: Instance[]) => void): IChainFind; | ||
} | ||
export interface IChainFindInstance { | ||
all(conditions: ModelMethod__FindConditions): IChainFindInstance; | ||
where(conditions: ModelMethod__FindConditions): IChainFindInstance; | ||
find(conditions: ModelMethod__FindConditions): IChainFindInstance; | ||
only(...args: string[]): IChainFindInstance; | ||
omit(): IChainFindInstance; | ||
skip(offset: number): IChainFindInstance; | ||
offset(offset: number): IChainFindInstance; | ||
order(propertyOrderDesc: string, order?: string | "Z" | "A"): IChainFindInstance; | ||
orderRaw(str: string, args: any[]): IChainFindInstance; | ||
limit(limit: number): IChainFindInstance; | ||
count(callback: ModelMethod__CountCallback): void; | ||
remove(callback: (err: Error) => void): void; | ||
run(callback?: ModelMethod__CommonCallback): void; | ||
// removed in commit 717ee65a7a23ed6762856cf3c187700e36c9ba70 | ||
// success(callback?: ModelMethod__CommonCallback): void; | ||
// fail(callback?: ModelMethod__CommonCallback): void; | ||
first(callback?: ModelMethod__CommonCallback): void; | ||
last(callback?: ModelMethod__CommonCallback): void; | ||
each(callback: (result: Instance) => void): void; | ||
each(): IChainFindInstance; | ||
eager(): IChainFindInstance; | ||
model: Model; | ||
options: ChainFindInstanceOptions | ||
[extraProperty: string]: any; | ||
} | ||
export interface ChainFindOptions { | ||
conditions | ||
properties | ||
order | ||
driver | ||
only | ||
table | ||
limit | ||
merge | ||
offset | ||
keys | ||
newInstance: { | ||
(data: InstanceDataPayload, cb: Function): void | ||
} | ||
keyProperties | ||
associations | ||
/* in instance */ | ||
exists? | ||
__eager? | ||
} | ||
export interface ChainFindInstanceOptions extends ChainFindOptions { | ||
} | ||
interface Plugin { | ||
(connection: FibORM, proto: any, opts: any, cb: Function): any | ||
} | ||
/* | ||
* Classes | ||
*/ | ||
export class ORM extends Class_EventEmitter { | ||
validators: FxOrmValidators.ValidatorModules; | ||
enforce: FxOrmValidators.FibjsEnforce; | ||
settings: SettingInstance; | ||
driver_name: string; | ||
driver: any; | ||
tools: any; | ||
models: { [key: string]: Model }; | ||
plugins: Plugin[]; | ||
use(plugin: string, options?: any): ORM; | ||
use(plugin: Plugin, options?: any): ORM; | ||
define(name: string, properties: ModelPropertyDefinitionHash, opts?: ModelOptions): Model; | ||
ping(callback: (err: Error) => void): ORM; | ||
close(callback: (err: Error) => void): ORM; | ||
load(file: string, callback: (err: Error) => void): any; | ||
sync(callback: (err: Error) => void): ORM; | ||
drop(callback: (err: Error) => void): ORM; | ||
} | ||
export interface SingletonOptions { | ||
identityCache?: any; | ||
saveCheck?: boolean; | ||
} | ||
export class singleton { | ||
static clear(key?: string): singleton; | ||
static get(key, opts: SingletonOptions, createCb: Function, returnCb: Function); | ||
} | ||
interface SettingsContainerGenerator { | ||
(options: object): SettingInstance | ||
} | ||
interface SettingInstance { | ||
set(key, value): SettingInstance | ||
get(key: string, def?: Function): any | ||
unset(): SettingInstance | ||
} | ||
export class Settings { | ||
constructor(settings: any); | ||
static Container: any; | ||
static defaults(): { | ||
properties: { | ||
primary_key: string; | ||
association_key: string; | ||
required: boolean; | ||
}; | ||
instance: { | ||
identityCache: boolean; | ||
identityCacheSaveCheck: boolean; | ||
autoSave: boolean; | ||
autoFetch: boolean; | ||
autoFetchLimit: number; | ||
cascadeRemove: boolean; | ||
returnAllErrors: boolean; | ||
}; | ||
connection: { | ||
reconnect: boolean; | ||
poll: boolean; | ||
debug: boolean; | ||
}; | ||
}; | ||
} | ||
export var settings: SettingInstance; | ||
export class PropertyModule { | ||
static normalize(property: string, settings: SettingInstance): any; | ||
static validate(value: any, property: string): any; | ||
} | ||
interface ConnectFunction { | ||
(uri: string): FxOrmNS.ORM; | ||
(uri: string, callback: (err: Error, db: FxOrmNS.ORM) => void): FxOrmNS.ORM; | ||
(options: FxOrmNS.IConnectionOptions): FxOrmNS.ORM; | ||
(options: FxOrmNS.IConnectionOptions, callback: (err: Error, db: FxOrmNS.ORM) => void): FxOrmNS.ORM; | ||
} | ||
interface ExportModule extends | ||
/* deprecated :start */ | ||
// just use require('@fxjs/sql-query').comparators.xxx plz | ||
FxSqlQuery.ComparatorHash | ||
/* deprecated :end */ | ||
{ | ||
validators: FxOrmValidators.ValidatorModules | ||
Settings: Settings | ||
settings: SettingInstance | ||
singleton: any | ||
Property: PropertyModule | ||
enforce: FxOrmValidators.FibjsEnforce | ||
ErrorCodes: FxOrmNS.PredefineErrorCodes | ||
addAdapter: FxOrmNS.AddAdapatorFunction | ||
/* deprecated :start */ | ||
Text: FxSqlQuery.TypedQueryObjectWrapper<'text'>; | ||
/* deprecated :end */ | ||
use(connection: Class_DbConnection, protocol: string, options: IConnectionOptions, callback: (err: Error, db?: FxOrmNS.ORM) => void): any; | ||
connect: ConnectFunction; | ||
connectSync(opts: FibORMIConnectionOptions | string): FibORM; | ||
[extra: string]: any | ||
} | ||
} | ||
import FibOrmNS = FxOrmNS | ||
@@ -842,0 +4,0 @@ |
@@ -22,2 +22,7 @@ /// <reference types="@fibjs/enforce" /> | ||
} | ||
interface ValidationOptionHash { | ||
[validation: string]: enforce.IValidator | enforce.IValidator[] | ||
// [validation: string]: enforce.ValidationCallback | enforce.ValidationCallback[] | ||
} | ||
} |
v1.7.3 / 2018-12-21 | ||
v1.8.0 / 2019-01-08 | ||
================== | ||
* remove some comments. | ||
* build next minor version's typo. | ||
* remove unstandard interface. | ||
* typo fix. | ||
v1.7.3 / 2018-12-21 | ||
=================== | ||
* Release v1.7.3 | ||
* typo fix. | ||
v1.7.2 / 2018-12-18 | ||
@@ -8,0 +17,0 @@ =================== |
@@ -0,1 +1,2 @@ | ||
/// <reference path="../../../@types/DMLDriver.d.ts" /> | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
@@ -2,0 +3,0 @@ const aliases = require("./Drivers/aliases"); |
@@ -1,15 +0,4 @@ | ||
var ORMError = require("./Error"); | ||
var Utilities = require("./Utilities"); | ||
function addAggregate(proto, fun, builder) { | ||
if (Array.isArray(fun)) { | ||
proto[fun[0].toLowerCase()] = builder((fun[1] || fun[0]).toLowerCase()); | ||
} | ||
else { | ||
proto[fun.toLowerCase()] = builder(fun.toLowerCase()); | ||
} | ||
} | ||
function aggregateAlias(fun, fields) { | ||
return fun + (fields && fields.length ? "_" + fields.join("_") : ""); | ||
} | ||
module.exports = function AggregateFunctions(opts) { | ||
const ORMError = require("./Error"); | ||
const Utilities = require("./Utilities"); | ||
const AggregateFunctions = function (opts) { | ||
if (typeof opts.driver.getQuery !== "function") { | ||
@@ -21,7 +10,8 @@ throw new ORMError('NO_SUPPORT', "This driver does not support aggregate functions"); | ||
} | ||
var aggregates = [[]]; | ||
var group_by = null; | ||
var used_distinct = false; | ||
var appendFunction = function (fun) { | ||
const aggregates = [[]]; | ||
let group_by = null; | ||
let used_distinct = false; | ||
const appendFunction = function (fun) { | ||
return function () { | ||
// select 1st array as aargs | ||
var args = (arguments.length && Array.isArray(arguments[0]) ? arguments[0] : Array.prototype.slice.apply(arguments)); | ||
@@ -41,5 +31,5 @@ if (args.length > 0) { | ||
}; | ||
var proto = { | ||
groupBy: function () { | ||
group_by = Array.prototype.slice.apply(arguments); | ||
const proto = { | ||
groupBy: function (...columns) { | ||
group_by = columns; | ||
return this; | ||
@@ -56,12 +46,12 @@ }, | ||
}, | ||
order: function () { | ||
opts.order = Utilities.standardizeOrder(Array.prototype.slice.apply(arguments)); | ||
order: function (...orders) { | ||
opts.order = Utilities.standardizeOrder(orders); | ||
return this; | ||
}, | ||
select: function () { | ||
if (arguments.length === 0) { | ||
select: function (...columns) { | ||
if (columns.length === 0) { | ||
throw new ORMError('PARAM_MISMATCH', "When using append you must at least define one property"); | ||
} | ||
if (Array.isArray(arguments[0])) { | ||
opts.propertyList = opts.propertyList.concat(arguments[0]); | ||
if (Array.isArray(columns[0])) { | ||
opts.propertyList = opts.propertyList.concat(columns[0]); | ||
} | ||
@@ -74,3 +64,3 @@ else { | ||
as: function (alias) { | ||
if (aggregates.length === 0 || (aggregates.length === 1 && aggregates[0].length === 0)) { | ||
if (!aggregates.length || (aggregates.length === 1 && aggregates[0].length === 0)) { | ||
throw new ORMError('PARAM_MISMATCH', "No aggregate functions defined yet"); | ||
@@ -102,9 +92,11 @@ } | ||
} | ||
if (aggregates.length === 0) { | ||
if (!aggregates.length) { | ||
throw new ORMError('PARAM_MISMATCH', "Missing aggregate functions"); | ||
} | ||
var query = opts.driver.getQuery().select().from(opts.table).select(opts.propertyList); | ||
var i, j; | ||
for (i = 0; i < aggregates.length; i++) { | ||
for (j = 0; j < aggregates[i].length; j++) { | ||
const query = opts.driver.getQuery() | ||
.select() | ||
.from(opts.table) | ||
.select(opts.propertyList); | ||
for (let i = 0; i < aggregates.length; i++) { | ||
for (let j = 0; j < aggregates[i].length; j++) { | ||
query.fun(aggregates[i][j].f, aggregates[i][j].a, aggregates[i][j].alias); | ||
@@ -118,3 +110,3 @@ } | ||
if (opts.order) { | ||
for (i = 0; i < opts.order.length; i++) { | ||
for (let i = 0; i < opts.order.length; i++) { | ||
query.order(opts.order[i][0], opts.order[i][1]); | ||
@@ -126,4 +118,4 @@ } | ||
} | ||
query = query.build(); | ||
opts.driver.execQuery(query, function (err, data) { | ||
const q_str = query.build(); | ||
opts.driver.execQuery(q_str, function (err, data) { | ||
if (err) { | ||
@@ -135,5 +127,5 @@ return cb(err); | ||
} | ||
var items = [], i; | ||
var items = []; | ||
if (used_distinct && aggregates.length === 1) { | ||
for (i = 0; i < data.length; i++) { | ||
for (let i = 0; i < data.length; i++) { | ||
items.push(data[i][Object.keys(data[i]).pop()]); | ||
@@ -143,4 +135,4 @@ } | ||
} | ||
for (i = 0; i < aggregates.length; i++) { | ||
for (var j = 0; j < aggregates[i].length; j++) { | ||
for (let i = 0; i < aggregates.length; i++) { | ||
for (let j = 0; j < aggregates[i].length; j++) { | ||
items.push(data[0][aggregates[i][j].alias] || null); | ||
@@ -154,3 +146,3 @@ } | ||
}; | ||
for (var i = 0; i < opts.driver.aggregate_functions.length; i++) { | ||
for (let i = 0; i < opts.driver.aggregate_functions.length; i++) { | ||
addAggregate(proto, opts.driver.aggregate_functions[i], appendFunction); | ||
@@ -160,1 +152,13 @@ } | ||
}; | ||
function addAggregate(proto, fun, builder) { | ||
if (Array.isArray(fun)) { | ||
proto[fun[0].toLowerCase()] = builder((fun[1] || fun[0]).toLowerCase()); | ||
} | ||
else { | ||
proto[fun.toLowerCase()] = builder(fun.toLowerCase()); | ||
} | ||
} | ||
function aggregateAlias(fun, fields) { | ||
return fun + (fields && fields.length ? "_" + fields.join("_") : ""); | ||
} | ||
module.exports = AggregateFunctions; |
@@ -24,3 +24,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); | ||
autoFetchLimit: opts.autoFetchLimit || 2, | ||
field: Utilities.wrapFieldObject({ field: opts.field, model: Model, altName: Model.table }) || Utilities.formatField(Model, Model.table, false, false), | ||
field: Utilities.wrapFieldObject({ | ||
field: opts.field, | ||
model: Model, | ||
altName: Model.table | ||
}) || Utilities.formatField(Model, Model.table, false, false), | ||
getAccessor: opts.getAccessor || _utils_1.defineAssociationAccessorMethodName('get', assocName), | ||
@@ -89,3 +93,3 @@ setAccessor: opts.setAccessor || _utils_1.defineAssociationAccessorMethodName('set', assocName), | ||
if (associations.length === 0) { | ||
return cb(); | ||
return cb(null); | ||
} | ||
@@ -96,3 +100,3 @@ var pending = associations.length; | ||
if (pending === 0) { | ||
return cb(); | ||
return cb(null); | ||
} | ||
@@ -109,3 +113,3 @@ }; | ||
value: function (cb) { | ||
if (!Instance[Model.id]) { | ||
if (!Instance[Model.id + '']) { | ||
cb(new ORMError("Instance not saved, cannot get extension", 'NOT_DEFINED', { model: Model.table })); | ||
@@ -128,3 +132,3 @@ } | ||
} | ||
if (!Instance[Model.id]) { | ||
if (!Instance[Model.id + '']) { | ||
cb(new ORMError("Instance not saved, cannot get extension", 'NOT_DEFINED', { model: Model.table })); | ||
@@ -165,3 +169,3 @@ } | ||
value: function (cb) { | ||
if (!Instance[Model.id]) { | ||
if (!Instance[Model.id + '']) { | ||
cb(new ORMError("Instance not saved, cannot get extension", 'NOT_DEFINED', { model: Model.table })); | ||
@@ -184,3 +188,3 @@ } | ||
if (--pending === 0) { | ||
return cb(); | ||
return cb(null); | ||
} | ||
@@ -190,3 +194,3 @@ }); | ||
if (pending === 0) { | ||
return cb(); | ||
return cb(null); | ||
} | ||
@@ -202,3 +206,3 @@ }); | ||
if (!Instance.saved()) { | ||
return cb(); | ||
return cb(null); | ||
} | ||
@@ -209,3 +213,3 @@ if (!opts.hasOwnProperty("autoFetchLimit") || typeof opts.autoFetchLimit == "undefined") { | ||
if (opts.autoFetchLimit === 0 || (!opts.autoFetch && !association.autoFetch)) { | ||
return cb(); | ||
return cb(null); | ||
} | ||
@@ -217,7 +221,7 @@ if (Instance.isPersisted()) { | ||
} | ||
return cb(); | ||
return cb(null); | ||
}); | ||
} | ||
else { | ||
return cb(); | ||
return cb(null); | ||
} | ||
@@ -224,0 +228,0 @@ } |
@@ -15,3 +15,3 @@ Object.defineProperty(exports, "__esModule", { value: true }); | ||
let opts = {}; | ||
for (var i = 0; i < arguments.length; i++) { | ||
for (let i = 0; i < arguments.length; i++) { | ||
switch (typeof arguments[i]) { | ||
@@ -55,2 +55,3 @@ case 'string': | ||
var assocTemplateName = opts.accessor || assocName; | ||
const fieldhash = Utilities.wrapFieldObject({ field: opts.field, model: OtherModel, altName: Model.table }) || Utilities.formatField(Model, name, true, opts.reversed); | ||
var association = { | ||
@@ -64,3 +65,3 @@ name: name, | ||
// I'm not sure the next key is used.. | ||
field: Utilities.wrapFieldObject({ field: opts.field, model: OtherModel, altName: Model.table }) || Utilities.formatField(Model, name, true, opts.reversed), | ||
field: fieldhash, | ||
mergeTable: opts.mergeTable || (Model.table + "_" + name), | ||
@@ -83,3 +84,3 @@ mergeId: mergeId, | ||
mergeAssocId: association.mergeId, | ||
field: association.field, | ||
field: fieldhash, | ||
autoFetch: association.autoFetch, | ||
@@ -103,3 +104,3 @@ autoFetchLimit: association.autoFetchLimit | ||
if (associations.length === 0) { | ||
return cb(); | ||
return cb(null); | ||
} | ||
@@ -110,3 +111,3 @@ var pending = associations.length; | ||
if (pending === 0) { | ||
return cb(); | ||
return cb(null); | ||
} | ||
@@ -137,4 +138,4 @@ }; | ||
Object.defineProperty(Instance, association.hasAccessor, { | ||
value: function () { | ||
var Instances = Array.prototype.slice.apply(arguments); | ||
value: function (...Instances) { | ||
// var Instances = Array.prototype.slice.apply(arguments); | ||
var cb = Instances.pop(); | ||
@@ -148,3 +149,4 @@ var conditions = {}, options = {}; | ||
if (Driver.hasMany) { | ||
return Driver.hasMany(Model, association).has(Instance, Instances, conditions, cb); | ||
return Driver.hasMany(Model, association) | ||
.has(Instance, Instances, conditions, cb); | ||
} | ||
@@ -335,4 +337,25 @@ options.autoFetchLimit = 0; | ||
var cb = noOperation; | ||
for (var i = 0; i < arguments.length; i++) { | ||
switch (typeof arguments[i]) { | ||
case "function": | ||
cb = arguments[i]; | ||
break; | ||
case "object": | ||
if (Array.isArray(arguments[i])) { | ||
Associations = Associations.concat(arguments[i]); | ||
} | ||
else if (arguments[i].isInstance) { | ||
Associations.push(arguments[i]); | ||
} | ||
else { | ||
opts = arguments[i]; | ||
} | ||
break; | ||
} | ||
} | ||
if (Associations.length === 0) { | ||
throw new ORMError("No associations defined", 'PARAM_MISMATCH', { model: Model.name }); | ||
} | ||
var run = function () { | ||
var savedAssociations = []; | ||
const savedAssociations = []; | ||
var saveNextAssociation = function () { | ||
@@ -389,23 +412,2 @@ if (Associations.length === 0) { | ||
}; | ||
for (var i = 0; i < arguments.length; i++) { | ||
switch (typeof arguments[i]) { | ||
case "function": | ||
cb = arguments[i]; | ||
break; | ||
case "object": | ||
if (Array.isArray(arguments[i])) { | ||
Associations = Associations.concat(arguments[i]); | ||
} | ||
else if (arguments[i].isInstance) { | ||
Associations.push(arguments[i]); | ||
} | ||
else { | ||
opts = arguments[i]; | ||
} | ||
break; | ||
} | ||
} | ||
if (Associations.length === 0) { | ||
throw new ORMError("No associations defined", 'PARAM_MISMATCH', { model: Model.name }); | ||
} | ||
if (this.saved()) { | ||
@@ -440,3 +442,3 @@ run(); | ||
if (!Instance.saved()) { | ||
return cb(); | ||
return cb(null); | ||
} | ||
@@ -447,3 +449,3 @@ if (!opts.hasOwnProperty("autoFetchLimit") || typeof opts.autoFetchLimit == "undefined") { | ||
if (opts.autoFetchLimit === 0 || (!opts.autoFetch && !association.autoFetch)) { | ||
return cb(); | ||
return cb(null); | ||
} | ||
@@ -455,3 +457,3 @@ Instance[association.getAccessor]({}, { autoFetchLimit: opts.autoFetchLimit - 1 }, function (err, Assoc) { | ||
} | ||
return cb(); | ||
return cb(null); | ||
}); | ||
@@ -458,0 +460,0 @@ } |
@@ -111,3 +111,5 @@ Object.defineProperty(exports, "__esModule", { value: true }); | ||
; | ||
function extend(Model, Instance, Driver, associations) { | ||
function extend(Model, Instance, Driver, | ||
// extend target | ||
associations) { | ||
for (var i = 0; i < associations.length; i++) { | ||
@@ -121,3 +123,3 @@ extendInstance(Model, Instance, Driver, associations[i]); | ||
if (associations.length === 0) { | ||
return cb(); | ||
return cb(null); | ||
} | ||
@@ -128,3 +130,3 @@ var pending = associations.length; | ||
if (pending === 0) { | ||
return cb(); | ||
return cb(null); | ||
} | ||
@@ -138,3 +140,5 @@ }; | ||
; | ||
function extendInstance(Model, Instance, Driver, association) { | ||
function extendInstance(Model, Instance, Driver, | ||
// extend target | ||
association) { | ||
Object.defineProperty(Instance, association.hasAccessor, { | ||
@@ -171,8 +175,10 @@ value: function (opts, cb) { | ||
}; | ||
// process get reversed instance's original instance | ||
if (association.reversed) { | ||
if (Utilities.hasValues(Instance, Model.id)) { | ||
const query_conds = Utilities.getConditions(Model, Object.keys(association.field), Instance); | ||
if (typeof cb !== "function") { | ||
return association.model.find(Utilities.getConditions(Model, Object.keys(association.field), Instance), opts); | ||
return association.model.find(query_conds, opts); | ||
} | ||
association.model.find(Utilities.getConditions(Model, Object.keys(association.field), Instance), opts, saveAndReturn); | ||
association.model.find(query_conds, opts, saveAndReturn); | ||
} | ||
@@ -218,3 +224,3 @@ else { | ||
if (!associations.length) { | ||
return cb(); | ||
return cb(null); | ||
} | ||
@@ -234,3 +240,5 @@ var other = associations.pop(); | ||
else { | ||
OtherInstance.save({}, { saveAssociations: false }, function (err) { | ||
OtherInstance.save({}, { | ||
saveAssociations: false | ||
}, function (err) { | ||
if (err) { | ||
@@ -249,2 +257,3 @@ return cb(err); | ||
}); | ||
// non-reversed could delete associated instance | ||
if (!association.reversed) { | ||
@@ -262,3 +271,3 @@ Object.defineProperty(Instance, association.delAccessor, { | ||
} | ||
return cb(); | ||
return cb(null); | ||
}); | ||
@@ -274,3 +283,3 @@ return this; | ||
if (!Instance.saved()) { | ||
return cb(); | ||
return cb(null); | ||
} | ||
@@ -281,8 +290,10 @@ if (!opts.hasOwnProperty("autoFetchLimit") || typeof opts.autoFetchLimit === "undefined") { | ||
if (opts.autoFetchLimit === 0 || (!opts.autoFetch && !association.autoFetch)) { | ||
return cb(); | ||
return cb(null); | ||
} | ||
// When we have a new non persisted instance for which the association field (eg owner_id) | ||
// is set, we don't want to auto fetch anything, since `new Model(owner_id: 12)` takes no | ||
// callback, and hence this lookup would complete at an arbitrary point in the future. | ||
// The associated entity should probably be fetched when the instance is persisted. | ||
/** | ||
* When we have a new non persisted instance for which the association field (eg owner_id) | ||
* is set, we don't want to auto fetch anything, since `new Model(owner_id: 12)` takes no | ||
* callback, and hence this lookup would complete at an arbitrary point in the future. | ||
* The associated entity should probably be fetched when the instance is persisted. | ||
*/ | ||
if (Instance.isPersisted()) { | ||
@@ -292,3 +303,3 @@ Instance[association.getAccessor]({ autoFetchLimit: opts.autoFetchLimit - 1 }, cb); | ||
else { | ||
return cb(); | ||
return cb(null); | ||
} | ||
@@ -295,0 +306,0 @@ } |
@@ -5,50 +5,17 @@ const util = require("util"); | ||
const ChainInstance = require("./ChainInstance"); | ||
function addChainMethod(chain, association, opts) { | ||
chain[association.hasAccessor] = function (value) { | ||
if (!opts.exists) { | ||
opts.exists = []; | ||
} | ||
var conditions = {}; | ||
var assocIds = Object.keys(association.mergeAssocId); | ||
var ids = association.model.id; | ||
function mergeConditions(source) { | ||
for (var i = 0; i < assocIds.length; i++) { | ||
if (typeof conditions[assocIds[i]] === "undefined") { | ||
conditions[assocIds[i]] = source[ids[i]]; | ||
} | ||
else if (Array.isArray(conditions[assocIds[i]])) { | ||
conditions[assocIds[i]].push(source[ids[i]]); | ||
} | ||
else { | ||
conditions[assocIds[i]] = [conditions[assocIds[i]], source[ids[i]]]; | ||
} | ||
} | ||
} | ||
if (Array.isArray(value)) { | ||
for (var i = 0; i < value.length; i++) { | ||
mergeConditions(value[i]); | ||
} | ||
} | ||
else { | ||
mergeConditions(value); | ||
} | ||
opts.exists.push({ | ||
table: association.mergeTable, | ||
link: [Object.keys(association.mergeId), association.model.id], | ||
conditions: conditions | ||
}); | ||
return chain; | ||
}; | ||
} | ||
module.exports = function ChainFind(Model, opts) { | ||
var prepareConditions = function () { | ||
return Utilities.transformPropertyNames(opts.conditions, opts.properties); | ||
}; | ||
var prepareOrder = function () { | ||
return Utilities.transformOrderPropertyNames(opts.order, opts.properties); | ||
}; | ||
var prepareConditions = function (opts) { | ||
return Utilities.transformPropertyNames(opts.conditions, opts.properties); | ||
}; | ||
var prepareOrder = function (opts) { | ||
return Utilities.transformOrderPropertyNames(opts.order, opts.properties); | ||
}; | ||
const MODEL_FUNCS = [ | ||
"hasOne", "hasMany", | ||
"drop", "sync", "get", "clear", "create", | ||
"exists", "settings", "aggregate" | ||
]; | ||
const ChainFind = function (Model, opts) { | ||
var chainRun = function (done) { | ||
var order, conditions; | ||
conditions = Utilities.transformPropertyNames(opts.conditions, opts.properties); | ||
order = Utilities.transformOrderPropertyNames(opts.order, opts.properties); | ||
const conditions = Utilities.transformPropertyNames(opts.conditions, opts.properties); | ||
const order = Utilities.transformOrderPropertyNames(opts.order, opts.properties); | ||
opts.driver.find(opts.only, opts.table, conditions, { | ||
@@ -116,5 +83,4 @@ limit: opts.limit, | ||
where: null, | ||
find: function () { | ||
find: function (...args) { | ||
var cb = null; | ||
var args = Array.prototype.slice.call(arguments); | ||
opts.conditions = opts.conditions || {}; | ||
@@ -128,3 +94,3 @@ if (typeof util.last(args) === "function") { | ||
else if (typeof args[0] === "string") { | ||
opts.conditions.__sql = opts.conditions.__sql || []; | ||
opts.conditions.__sql = (opts.conditions.__sql || []); | ||
opts.conditions.__sql.push(args); | ||
@@ -188,3 +154,3 @@ } | ||
count: function (cb) { | ||
opts.driver.count(opts.table, prepareConditions(), { | ||
opts.driver.count(opts.table, prepareConditions(opts), { | ||
merge: opts.merge | ||
@@ -200,6 +166,6 @@ }, function (err, data) { | ||
remove: function (cb) { | ||
var keys = opts.keyProperties.map(x => x.mapsTo); // util.map(opts.keyProperties, 'mapsTo'); | ||
opts.driver.find(keys, opts.table, prepareConditions(), { | ||
var keys = opts.keyProperties.map((x) => x.mapsTo); // util.map(opts.keyProperties, 'mapsTo'); | ||
opts.driver.find(keys, opts.table, prepareConditions(opts), { | ||
limit: opts.limit, | ||
order: prepareOrder(), | ||
order: prepareOrder(opts), | ||
merge: opts.merge, | ||
@@ -215,3 +181,3 @@ offset: opts.offset, | ||
} | ||
var ids = [], conditions = {}; | ||
var conditions = {}; | ||
var or; | ||
@@ -267,7 +233,3 @@ conditions.or = []; | ||
for (var k in Model) { | ||
if ([ | ||
"hasOne", "hasMany", | ||
"drop", "sync", "get", "clear", "create", | ||
"exists", "settings", "aggregate" | ||
].indexOf(k) >= 0) { | ||
if (MODEL_FUNCS.indexOf(k) >= 0) { | ||
continue; | ||
@@ -284,1 +246,39 @@ } | ||
}; | ||
function addChainMethod(chain, association, opts) { | ||
chain[association.hasAccessor] = function (value) { | ||
if (!opts.exists) { | ||
opts.exists = []; | ||
} | ||
var conditions = {}; | ||
var assocIds = Object.keys(association.mergeAssocId); | ||
var ids = association.model.id; | ||
function mergeConditions(source) { | ||
for (var i = 0; i < assocIds.length; i++) { | ||
if (typeof conditions[assocIds[i]] === "undefined") { | ||
conditions[assocIds[i]] = source[ids[i]]; | ||
} | ||
else if (Array.isArray(conditions[assocIds[i]])) { | ||
conditions[assocIds[i]].push(source[ids[i]]); | ||
} | ||
else { | ||
conditions[assocIds[i]] = [conditions[assocIds[i]], source[ids[i]]]; | ||
} | ||
} | ||
} | ||
if (Array.isArray(value)) { | ||
for (var i = 0; i < value.length; i++) { | ||
mergeConditions(value[i]); | ||
} | ||
} | ||
else { | ||
mergeConditions(value); | ||
} | ||
opts.exists.push({ | ||
table: association.mergeTable, | ||
link: [Object.keys(association.mergeId), association.model.id], | ||
conditions: conditions | ||
}); | ||
return chain; | ||
}; | ||
} | ||
module.exports = ChainFind; |
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const db = require("db"); | ||
class Database { | ||
constructor(connOpts) { | ||
this.opts = connOpts; | ||
constructor(conn_opts) { | ||
this.opts = conn_opts; | ||
} | ||
@@ -17,11 +17,11 @@ on(ev) { } | ||
that.conn = conn; | ||
cb(e); | ||
cb(e, conn); | ||
}); | ||
} | ||
execute(sql, ...args) { | ||
return this.conn.execute(sql, ...args); | ||
} | ||
query(sql, cb) { | ||
this.conn.execute(sql, cb); | ||
} | ||
execute(sql) { | ||
return this.conn.execute(sql); | ||
} | ||
end(cb) { | ||
@@ -31,4 +31,6 @@ this.conn.close(cb); | ||
} | ||
exports.createConnection = function (connOpts) { | ||
return new Database(connOpts); | ||
exports.createConnection = function (conn_opts) { | ||
return new Database(conn_opts); | ||
}; | ||
exports.createPool = function (conn_opts) { | ||
}; |
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const _merge = require('lodash.merge'); | ||
const Sync = require("@fxjs/sql-ddl-sync").Sync; | ||
function sync(opts, cb) { | ||
var sync = new Sync({ | ||
const _merge = require("lodash.merge"); | ||
const sql_ddl_sync_1 = require("@fxjs/sql-ddl-sync"); | ||
exports.sync = function (opts, cb) { | ||
var sync = new sql_ddl_sync_1.Sync({ | ||
driver: this, | ||
debug: false //function (text) { console.log(text); } | ||
debug: false // function (text) { console.log(text); } | ||
}); | ||
@@ -30,13 +30,11 @@ var setIndex = function (p, v, k) { | ||
return this; | ||
} | ||
exports.sync = sync; | ||
; | ||
function drop(opts, cb) { | ||
var i, queries = [], pending; | ||
}; | ||
exports.drop = function (opts, cb) { | ||
var queries = [], pending; | ||
queries.push("DROP TABLE IF EXISTS " + this.query.escapeId(opts.table)); | ||
for (i = 0; i < opts.many_associations.length; i++) { | ||
for (let i = 0; i < opts.many_associations.length; i++) { | ||
queries.push("DROP TABLE IF EXISTS " + this.query.escapeId(opts.many_associations[i].mergeTable)); | ||
} | ||
pending = queries.length; | ||
for (i = 0; i < queries.length; i++) { | ||
for (let i = 0; i < queries.length; i++) { | ||
this.execQuery(queries[i], function (err) { | ||
@@ -49,4 +47,2 @@ if (--pending === 0) { | ||
return this; | ||
} | ||
exports.drop = drop; | ||
; | ||
}; |
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var util = require("util"); | ||
var mysql = require("../DB/mysql"); | ||
var Query = require("@fxjs/sql-query").Query; | ||
var shared = require("./_shared"); | ||
var DDL = require("../DDL/SQL"); | ||
function Driver(config, connection, opts) { | ||
const util = require("util"); | ||
const sql_query_1 = require("@fxjs/sql-query"); | ||
const mysql = require("../DB/mysql"); | ||
const shared = require("./_shared"); | ||
const DDL = require("../DDL/SQL"); | ||
exports.Driver = function (config, connection, opts) { | ||
this.dialect = 'mysql'; | ||
@@ -15,3 +15,3 @@ this.config = config || {}; | ||
} | ||
this.query = new Query({ dialect: this.dialect, timezone: this.config.timezone }); | ||
this.query = new sql_query_1.Query({ dialect: this.dialect, timezone: this.config.timezone }); | ||
this.reconnect(null, connection); | ||
@@ -25,10 +25,9 @@ this.aggregate_functions = ["ABS", "CEIL", "FLOOR", "ROUND", | ||
"DISTINCT"]; | ||
} | ||
exports.Driver = Driver; | ||
util.extend(Driver.prototype, shared, DDL); | ||
Driver.prototype.ping = function (cb) { | ||
}; | ||
util.extend(exports.Driver.prototype, shared, DDL); | ||
exports.Driver.prototype.ping = function (cb) { | ||
this.db.ping(cb); | ||
return this; | ||
}; | ||
Driver.prototype.on = function (ev, cb) { | ||
exports.Driver.prototype.on = function (ev, cb) { | ||
if (ev == "error") { | ||
@@ -40,3 +39,3 @@ this.db.on("error", cb); | ||
}; | ||
Driver.prototype.connect = function (cb) { | ||
exports.Driver.prototype.connect = function (cb) { | ||
if (this.opts.pool) { | ||
@@ -57,3 +56,3 @@ return this.db.pool.getConnection(function (err, con) { | ||
}; | ||
Driver.prototype.reconnect = function (cb, connection) { | ||
exports.Driver.prototype.reconnect = function (cb, connection) { | ||
var connOpts = this.config.href || this.config; | ||
@@ -75,3 +74,3 @@ // Prevent noisy mysql driver output | ||
}; | ||
Driver.prototype.close = function (cb) { | ||
exports.Driver.prototype.close = function (cb) { | ||
if (this.opts.pool) { | ||
@@ -84,6 +83,6 @@ this.db.pool.end(cb); | ||
}; | ||
Driver.prototype.getQuery = function () { | ||
exports.Driver.prototype.getQuery = function () { | ||
return this.query; | ||
}; | ||
Driver.prototype.execSimpleQuery = function (query, cb) { | ||
exports.Driver.prototype.execSimpleQuery = function (query, cb) { | ||
if (this.opts.debug) { | ||
@@ -99,5 +98,6 @@ require("../../Debug").sql('mysql', query); | ||
}; | ||
Driver.prototype.find = function (fields, table, conditions, opts, cb) { | ||
exports.Driver.prototype.find = function (fields, table, conditions, opts, cb) { | ||
var q = this.query.select() | ||
.from(table).select(fields); | ||
.from(table) | ||
.select(fields); | ||
if (opts.offset) { | ||
@@ -114,3 +114,3 @@ q.offset(opts.offset); | ||
if (opts.order) { | ||
for (var i = 0; i < opts.order.length; i++) { | ||
for (let i = 0; i < opts.order.length; i++) { | ||
q.order(opts.order[i][0], opts.order[i][1]); | ||
@@ -120,3 +120,4 @@ } | ||
if (opts.merge) { | ||
q.from(opts.merge.from.table, opts.merge.from.field, opts.merge.to.field).select(opts.merge.select); | ||
q.from(opts.merge.from.table, opts.merge.from.field, opts.merge.to.field) | ||
.select(opts.merge.select); | ||
// for hasMany | ||
@@ -134,10 +135,9 @@ if (opts.merge.where && Object.keys(opts.merge.where[1]).length) { | ||
if (opts.exists) { | ||
for (var k in opts.exists) { | ||
for (let k in opts.exists) { | ||
q.whereExists(opts.exists[k].table, table, opts.exists[k].link, opts.exists[k].conditions); | ||
} | ||
} | ||
q = q.build(); | ||
this.execSimpleQuery(q, cb); | ||
this.execSimpleQuery(q.build(), cb); | ||
}; | ||
Driver.prototype.count = function (table, conditions, opts, cb) { | ||
exports.Driver.prototype.count = function (table, conditions, opts, cb) { | ||
var q = this.query.select() | ||
@@ -166,3 +166,3 @@ .from(table) | ||
}; | ||
Driver.prototype.insert = function (table, data, keyProperties, cb) { | ||
exports.Driver.prototype.insert = function (table, data, keyProperties, cb) { | ||
var q = this.query.insert() | ||
@@ -175,3 +175,3 @@ .into(table) | ||
return cb(err); | ||
var i, ids = {}, prop; | ||
var ids = {}, prop; | ||
if (keyProperties) { | ||
@@ -182,3 +182,3 @@ if (keyProperties.length == 1 && info.hasOwnProperty("insertId") && info.insertId !== 0) { | ||
else { | ||
for (i = 0; i < keyProperties.length; i++) { | ||
for (let i = 0; i < keyProperties.length; i++) { | ||
prop = keyProperties[i]; | ||
@@ -192,3 +192,3 @@ ids[prop.name] = data[prop.mapsTo]; | ||
}; | ||
Driver.prototype.update = function (table, changes, conditions, cb) { | ||
exports.Driver.prototype.update = function (table, changes, conditions, cb) { | ||
var q = this.query.update() | ||
@@ -201,3 +201,3 @@ .into(table) | ||
}; | ||
Driver.prototype.remove = function (table, conditions, cb) { | ||
exports.Driver.prototype.remove = function (table, conditions, cb) { | ||
var q = this.query.remove() | ||
@@ -209,7 +209,7 @@ .from(table) | ||
}; | ||
Driver.prototype.clear = function (table, cb) { | ||
exports.Driver.prototype.clear = function (table, cb) { | ||
var q = "TRUNCATE TABLE " + this.query.escapeId(table); | ||
this.execSimpleQuery(q, cb); | ||
}; | ||
Driver.prototype.poolQuery = function (query, cb) { | ||
exports.Driver.prototype.poolQuery = function (query, cb) { | ||
this.db.pool.getConnection(function (err, con) { | ||
@@ -230,3 +230,3 @@ if (err) { | ||
}; | ||
Driver.prototype.valueToProperty = function (value, property) { | ||
exports.Driver.prototype.valueToProperty = function (value, property) { | ||
var customType; | ||
@@ -256,3 +256,3 @@ switch (property.type) { | ||
}; | ||
Driver.prototype.propertyToValue = function (value, property) { | ||
exports.Driver.prototype.propertyToValue = function (value, property) { | ||
var customType; | ||
@@ -279,4 +279,4 @@ switch (property.type) { | ||
}; | ||
Object.defineProperty(Driver.prototype, "isSql", { | ||
Object.defineProperty(exports.Driver.prototype, "isSql", { | ||
value: true | ||
}); |
@@ -7,3 +7,3 @@ Object.defineProperty(exports, "__esModule", { value: true }); | ||
var DDL = require("../DDL/SQL"); | ||
function Driver(config, connection, opts) { | ||
exports.Driver = function (config, connection, opts) { | ||
this.dialect = 'sqlite'; | ||
@@ -36,10 +36,9 @@ this.config = config || {}; | ||
"DISTINCT"]; | ||
} | ||
exports.Driver = Driver; | ||
util.extend(Driver.prototype, shared, DDL); | ||
Driver.prototype.ping = function (cb) { | ||
}; | ||
util.extend(exports.Driver.prototype, shared, DDL); | ||
exports.Driver.prototype.ping = function (cb) { | ||
process.nextTick(cb); | ||
return this; | ||
}; | ||
Driver.prototype.on = function (ev, cb) { | ||
exports.Driver.prototype.on = function (ev, cb) { | ||
if (ev == "error") { | ||
@@ -50,6 +49,6 @@ this.db.on("error", cb); | ||
}; | ||
Driver.prototype.connect = function (cb) { | ||
exports.Driver.prototype.connect = function (cb) { | ||
process.nextTick(cb); | ||
}; | ||
Driver.prototype.close = function (cb) { | ||
exports.Driver.prototype.close = function (cb) { | ||
this.db.close(); | ||
@@ -59,6 +58,6 @@ if (typeof cb == "function") | ||
}; | ||
Driver.prototype.getQuery = function () { | ||
exports.Driver.prototype.getQuery = function () { | ||
return this.query; | ||
}; | ||
Driver.prototype.execSimpleQuery = function (query, cb) { | ||
exports.Driver.prototype.execSimpleQuery = function (query, cb) { | ||
if (this.opts.debug) { | ||
@@ -69,3 +68,3 @@ require("../../Debug").sql('sqlite', query); | ||
}; | ||
Driver.prototype.find = function (fields, table, conditions, opts, cb) { | ||
exports.Driver.prototype.find = function (fields, table, conditions, opts, cb) { | ||
var q = this.query.select() | ||
@@ -105,9 +104,9 @@ .from(table).select(fields); | ||
} | ||
q = q.build(); | ||
const qstr = q.build(); | ||
if (this.opts.debug) { | ||
require("../../Debug").sql('sqlite', q); | ||
require("../../Debug").sql('sqlite', qstr); | ||
} | ||
this.db.all(q, cb); | ||
this.db.all(qstr, cb); | ||
}; | ||
Driver.prototype.count = function (table, conditions, opts, cb) { | ||
exports.Driver.prototype.count = function (table, conditions, opts, cb) { | ||
var q = this.query.select() | ||
@@ -133,9 +132,9 @@ .from(table) | ||
} | ||
q = q.build(); | ||
const qstr = q.build(); | ||
if (this.opts.debug) { | ||
require("../../Debug").sql('sqlite', q); | ||
require("../../Debug").sql('sqlite', qstr); | ||
} | ||
this.db.all(q, cb); | ||
this.db.all(qstr, cb); | ||
}; | ||
Driver.prototype.insert = function (table, data, keyProperties, cb) { | ||
exports.Driver.prototype.insert = function (table, data, keyProperties, cb) { | ||
var q = this.query.insert() | ||
@@ -172,3 +171,3 @@ .into(table) | ||
}; | ||
Driver.prototype.update = function (table, changes, conditions, cb) { | ||
exports.Driver.prototype.update = function (table, changes, conditions, cb) { | ||
var q = this.query.update() | ||
@@ -184,3 +183,3 @@ .into(table) | ||
}; | ||
Driver.prototype.remove = function (table, conditions, cb) { | ||
exports.Driver.prototype.remove = function (table, conditions, cb) { | ||
var q = this.query.remove() | ||
@@ -195,3 +194,3 @@ .from(table) | ||
}; | ||
Driver.prototype.clear = function (table, cb) { | ||
exports.Driver.prototype.clear = function (table, cb) { | ||
var debug = this.opts.debug; | ||
@@ -204,3 +203,3 @@ this.execQuery("DELETE FROM ??", [table], function (err) { | ||
}; | ||
Driver.prototype.valueToProperty = function (value, property) { | ||
exports.Driver.prototype.valueToProperty = function (value, property) { | ||
var v, customType; | ||
@@ -273,3 +272,3 @@ switch (property.type) { | ||
}; | ||
Driver.prototype.propertyToValue = function (value, property) { | ||
exports.Driver.prototype.propertyToValue = function (value, property) { | ||
var customType; | ||
@@ -334,3 +333,3 @@ switch (property.type) { | ||
}; | ||
Object.defineProperty(Driver.prototype, "isSql", { | ||
Object.defineProperty(exports.Driver.prototype, "isSql", { | ||
value: true | ||
@@ -337,0 +336,0 @@ }); |
@@ -1,2 +0,1 @@ | ||
// Moved to 'Error.js' | ||
module.exports = require('./error').codes; |
Object.defineProperty(exports, "__esModule", { value: true }); | ||
function trigger() { | ||
exports.trigger = function () { | ||
var args = Array.prototype.slice.apply(arguments); | ||
@@ -9,6 +9,4 @@ var self = args.shift(); | ||
} | ||
} | ||
exports.trigger = trigger; | ||
; | ||
function wait() { | ||
}; | ||
exports.wait = function () { | ||
var args = Array.prototype.slice.apply(arguments); | ||
@@ -28,4 +26,2 @@ var self = args.shift(); | ||
} | ||
} | ||
exports.wait = wait; | ||
; | ||
}; |
@@ -0,10 +1,12 @@ | ||
/// <reference types="fibjs" /> | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const util = require("util"); | ||
const Utilities = require("./Utilities"); | ||
const Hook = require("./Hook"); | ||
const enforce = require("@fibjs/enforce"); | ||
function Instance(Model, opts) { | ||
opts = opts || {}; | ||
exports.Instance = function (Model, _opts) { | ||
const opts = util.extend({}, _opts); | ||
opts.data = opts.data || {}; | ||
opts.extra = opts.extra || {}; | ||
opts.keys = opts.keys || "id"; | ||
opts.keys = (opts.keys || "id"); | ||
opts.changes = (opts.is_new ? Object.keys(opts.data) : []); | ||
@@ -27,5 +29,4 @@ opts.extrachanges = []; | ||
var rememberKeys = function () { | ||
var i, prop; | ||
for (i = 0; i < opts.keyProperties.length; i++) { | ||
prop = opts.keyProperties[i]; | ||
for (let i = 0; i < opts.keyProperties.length; i++) { | ||
const prop = opts.keyProperties[i]; | ||
opts.originalKeyValues[prop.name] = opts.data[prop.name]; | ||
@@ -43,5 +44,5 @@ } | ||
var handleValidations = function (cb) { | ||
var pending = [], errors = [], required, alwaysValidate; | ||
// var pending = [], errors = []; | ||
var required, alwaysValidate; | ||
Hook.wait(instance, opts.hooks.beforeValidation, function (err) { | ||
var k, i; | ||
if (err) { | ||
@@ -53,3 +54,3 @@ return saveError(cb, err); | ||
}); | ||
for (k in opts.validations) { | ||
for (let k in opts.validations) { | ||
required = false; | ||
@@ -61,3 +62,3 @@ if (Model.allProperties[k]) { | ||
else { | ||
for (i = 0; i < opts.one_associations.length; i++) { | ||
for (let i = 0; i < opts.one_associations.length; i++) { | ||
if (opts.one_associations[i].field === k) { | ||
@@ -72,3 +73,3 @@ required = opts.one_associations[i].required; | ||
} | ||
for (i = 0; i < opts.validations[k].length; i++) { | ||
for (let i = 0; i < opts.validations[k].length; i++) { | ||
checks.add(k, opts.validations[k][i]); | ||
@@ -196,3 +197,3 @@ } | ||
var savePersisted = function (saveOptions, data, cb) { | ||
var changes = {}, conditions = {}, i, prop; | ||
var changes = {}, conditions = {}; | ||
var next = function (saved) { | ||
@@ -231,7 +232,7 @@ var finish = function () { | ||
else { | ||
for (i = 0; i < opts.changes.length; i++) { | ||
for (let i = 0; i < opts.changes.length; i++) { | ||
changes[opts.changes[i]] = data[opts.changes[i]]; | ||
} | ||
for (i = 0; i < opts.keyProperties.length; i++) { | ||
prop = opts.keyProperties[i]; | ||
for (let i = 0; i < opts.keyProperties.length; i++) { | ||
const prop = opts.keyProperties[i]; | ||
conditions[prop.mapsTo] = opts.originalKeyValues[prop.name]; | ||
@@ -251,3 +252,3 @@ } | ||
var saveAssociations = function (cb) { | ||
var pending = 1, errored = false, i, j; | ||
var pending = 1, errored = false, i; | ||
var saveAssociation = function (accessor, instances) { | ||
@@ -275,3 +276,3 @@ pending += 1; | ||
} | ||
for (var i = 0; i < instance[assoc.name].length; i++) { | ||
for (let i = 0; i < instance[assoc.name].length; i++) { | ||
if (!instance[assoc.name][i].isInstance) { | ||
@@ -289,3 +290,3 @@ instance[assoc.name][i] = new assoc.model(instance[assoc.name][i]); | ||
}; | ||
for (i = 0; i < opts.one_associations.length; i++) { | ||
for (let i = 0; i < opts.one_associations.length; i++) { | ||
_saveOneAssociation(opts.one_associations[i]); | ||
@@ -299,3 +300,3 @@ } | ||
return; | ||
for (j = 0; j < assocVal.length; j++) { | ||
for (let j = 0; j < assocVal.length; j++) { | ||
if (!assocVal[j].isInstance) { | ||
@@ -307,3 +308,3 @@ assocVal[j] = new assoc.model(assocVal[j]); | ||
}; | ||
for (i = 0; i < opts.many_associations.length; i++) { | ||
for (let i = 0; i < opts.many_associations.length; i++) { | ||
_saveManyAssociation(opts.many_associations[i]); | ||
@@ -324,3 +325,3 @@ } | ||
var conditions = {}; | ||
for (var i = 0; i < opts.extrachanges.length; i++) { | ||
for (let i = 0; i < opts.extrachanges.length; i++) { | ||
if (!opts.data.hasOwnProperty(opts.extrachanges[i])) | ||
@@ -338,3 +339,3 @@ continue; | ||
} | ||
for (i = 0; i < opts.extra_info.id.length; i++) { | ||
for (let i = 0; i < opts.extra_info.id.length; i++) { | ||
conditions[opts.extra_info.id_prop[i]] = opts.extra_info.id[i]; | ||
@@ -352,3 +353,3 @@ conditions[opts.extra_info.assoc_prop[i]] = opts.data[opts.keys[i]]; | ||
var conditions = {}; | ||
for (var i = 0; i < opts.keys.length; i++) { | ||
for (let i = 0; i < opts.keys.length; i++) { | ||
conditions[opts.keys[i]] = opts.data[opts.keys[i]]; | ||
@@ -383,3 +384,3 @@ } | ||
} | ||
for (var i = 0; i < opts.keys.length; i++) { | ||
for (let i = 0; i < opts.keys.length; i++) { | ||
conditions[opts.keys[i]] = opts.data[opts.keys[i]]; | ||
@@ -452,3 +453,3 @@ } | ||
if (instance.hasOwnProperty(key)) | ||
console.log("Overwriting instance property"); | ||
global.console.log("Overwriting instance property"); | ||
if (key in opts.data) { | ||
@@ -638,3 +639,3 @@ defaultValue = opts.data[key]; | ||
Object.defineProperty(instance, "__singleton_uid", { | ||
value: function (cb) { | ||
value: function () { | ||
return opts.uid; | ||
@@ -649,3 +650,3 @@ }, | ||
Object.defineProperty(instance, "model", { | ||
value: function (cb) { | ||
value: function () { | ||
return Model; | ||
@@ -703,3 +704,2 @@ }, | ||
return instance; | ||
} | ||
exports.Instance = Instance; | ||
}; |
@@ -16,4 +16,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); | ||
var conditions = {}; | ||
conditions[Model.id] = Instance[Model.id]; | ||
Model.find(conditions, { identityCache: false }).only(Model.id.concat(property)).first(function (err, item) { | ||
conditions[Model.id + ''] = Instance[Model.id + '']; | ||
Model | ||
.find(conditions, { identityCache: false }) | ||
.only(Model.id.concat(property)) | ||
.first(function (err, item) { | ||
return cb(err, item ? item[property] : null); | ||
@@ -28,4 +31,7 @@ }); | ||
var conditions = {}; | ||
conditions[Model.id] = Instance[Model.id]; | ||
Model.find(conditions, { identityCache: false }).only(Model.id.concat(property)).first(function (err, item) { | ||
conditions[Model.id + ''] = Instance[Model.id + '']; | ||
Model | ||
.find(conditions, { identityCache: false }) | ||
.only(Model.id.concat(property)) | ||
.first(function (err, item) { | ||
if (err) { | ||
@@ -47,4 +53,6 @@ return cb(err); | ||
var conditions = {}; | ||
conditions[Model.id] = Instance[Model.id]; | ||
Model.find(conditions, { identityCache: false }).first(function (err, item) { | ||
conditions[Model.id + ''] = Instance[Model.id + '']; | ||
Model | ||
.find(conditions, { identityCache: false }) | ||
.first(function (err, item) { | ||
if (err) { | ||
@@ -51,0 +59,0 @@ return cb(err); |
@@ -26,13 +26,15 @@ /// <reference lib="es2017" /> | ||
]; | ||
function noOp() { } | ||
; | ||
exports.Model = function (opts) { | ||
opts = util.extend(opts || {}, { keys: opts.keys || [] }); | ||
opts.keys = Array.isArray(opts.keys) ? opts.keys : [opts.keys]; | ||
var one_associations = []; | ||
var many_associations = []; | ||
var extend_associations = []; | ||
var association_properties = []; | ||
var model_fields = []; | ||
var fieldToPropertyMap = {}; | ||
var allProperties = {}; | ||
var keyProperties = []; | ||
const one_associations = []; | ||
const many_associations = []; | ||
const extend_associations = []; | ||
const association_properties = []; | ||
const model_fields = []; | ||
const fieldToPropertyMap = {}; | ||
const allProperties = {}; | ||
const keyProperties = []; | ||
var createHookHelper = function (hook) { | ||
@@ -53,4 +55,4 @@ return function (cb) { | ||
} | ||
var found_assoc = false, i, k; | ||
for (k in data) { | ||
var found_assoc = false; | ||
for (let k in data) { | ||
if (k === "extra_field") | ||
@@ -66,3 +68,3 @@ continue; | ||
continue; | ||
for (i = 0; i < one_associations.length; i++) { | ||
for (let i = 0; i < one_associations.length; i++) { | ||
if (one_associations[i].name === k) { | ||
@@ -74,3 +76,3 @@ found_assoc = true; | ||
if (!found_assoc) { | ||
for (i = 0; i < many_associations.length; i++) { | ||
for (let i = 0; i < many_associations.length; i++) { | ||
if (many_associations[i].name === k) { | ||
@@ -148,9 +150,8 @@ found_assoc = true; | ||
}; | ||
const model = function () { | ||
var instance, i; | ||
var data = arguments.length > 1 ? arguments : arguments[0]; | ||
const model = function (..._data) { | ||
let data = _data.length > 1 ? _data : _data[0]; | ||
if (Array.isArray(opts.keys) && Array.isArray(data)) { | ||
if (data.length == opts.keys.length) { | ||
var data2 = {}; | ||
for (i = 0; i < opts.keys.length; i++) { | ||
for (let i = 0; i < opts.keys.length; i++) { | ||
data2[opts.keys[i]] = data[i++]; | ||
@@ -175,3 +176,3 @@ } | ||
var isNew = false; | ||
for (i = 0; i < opts.keys.length; i++) { | ||
for (let i = 0; i < opts.keys.length; i++) { | ||
if (!data.hasOwnProperty(opts.keys[i])) { | ||
@@ -197,3 +198,3 @@ isNew = true; | ||
if (arguments.length === 0) { | ||
cb = function () { }; | ||
cb = noOp; | ||
} | ||
@@ -237,8 +238,8 @@ if (typeof opts.driver.drop === "function") { | ||
}; | ||
model.get = function () { | ||
var conditions = {}; | ||
var options = {}; | ||
var ids = Array.prototype.slice.apply(arguments); | ||
var cb = ids.pop(); | ||
var prop; | ||
model.get = function (cb) { | ||
const conditions = {}; | ||
let options = {}; | ||
let ids = Array.prototype.slice.apply(arguments); | ||
let prop; | ||
cb = ids.pop(); | ||
if (typeof cb !== "function") { | ||
@@ -256,3 +257,3 @@ throw new ORMError("Missing Model.get() callback", 'MISSING_CALLBACK', { model: opts.table }); | ||
} | ||
for (var i = 0; i < keyProperties.length; i++) { | ||
for (let i = 0; i < keyProperties.length; i++) { | ||
prop = keyProperties[i]; | ||
@@ -295,4 +296,4 @@ conditions[prop.mapsTo] = ids[i]; | ||
model.find = function () { | ||
var conditions = null; | ||
var options = {}; | ||
var conditions = null; | ||
var cb = null; | ||
@@ -409,4 +410,3 @@ var order = null; | ||
model.where = model.all = model.find; | ||
model.one = function () { | ||
var args = Array.prototype.slice.apply(arguments); | ||
model.one = function (...args) { | ||
var cb = null; | ||
@@ -464,3 +464,3 @@ // extract callback | ||
for (var i = 0; i < arguments.length; i++) { | ||
if (typeof arguments[i] === "object") { | ||
if (typeof arguments[i] === 'object') { | ||
if (Array.isArray(arguments[i])) { | ||
@@ -486,4 +486,3 @@ propertyList = arguments[i]; | ||
}; | ||
model.exists = function () { | ||
var ids = Array.prototype.slice.apply(arguments); | ||
model.exists = function (...ids) { | ||
var cb = ids.pop(); | ||
@@ -493,10 +492,34 @@ if (typeof cb !== "function") { | ||
} | ||
var conditions = {}, i; | ||
var conditions = {}; | ||
/** | ||
* assign keys' id columns comparator-eq value | ||
* as its order in `opts.keys` | ||
* | ||
* @example | ||
* define('test', { | ||
* key_1: { | ||
* type: 'integer', key: true | ||
* }, | ||
* key_2: { | ||
* type: 'integer', key: true | ||
* } | ||
* }) | ||
*/ | ||
if (ids.length === 1 && typeof ids[0] === "object") { | ||
if (Array.isArray(ids[0])) { | ||
for (i = 0; i < opts.keys.length; i++) { | ||
conditions[opts.keys[i]] = ids[0][i]; | ||
/** | ||
* @example | ||
* Person.exists([1, 7]) | ||
*/ | ||
const col_values = ids[0]; | ||
for (let i = 0; i < opts.keys.length; i++) { | ||
conditions[opts.keys[i]] = col_values[i]; | ||
} | ||
} | ||
else { | ||
/** | ||
* @access general usage | ||
* @example | ||
* Person.exists({key_1: 1, key_2: 7}) | ||
*/ | ||
conditions = ids[0]; | ||
@@ -506,3 +529,7 @@ } | ||
else { | ||
for (i = 0; i < opts.keys.length; i++) { | ||
/** | ||
* @example | ||
* Person.exists(1, 7) | ||
*/ | ||
for (let i = 0; i < opts.keys.length; i++) { | ||
conditions[opts.keys[i]] = ids[i]; | ||
@@ -525,3 +552,3 @@ } | ||
var items = []; | ||
var options = {}; | ||
// var options = {}; | ||
var done = null; | ||
@@ -541,3 +568,3 @@ var create_err = null; | ||
else { | ||
options = arguments[i]; | ||
// options = arguments[i]; | ||
} | ||
@@ -557,2 +584,3 @@ break; | ||
autoSave: opts.autoSave, | ||
// not fetch associated instance on its creation. | ||
autoFetch: false | ||
@@ -595,3 +623,4 @@ }, function (err, item) { | ||
}; | ||
var currFields = {}; | ||
// control current owned fields | ||
const currFields = {}; | ||
model.addProperty = function (propIn, options) { | ||
@@ -598,0 +627,0 @@ var cType; |
@@ -5,3 +5,3 @@ const util = require("util"); | ||
const uuid = require("uuid"); | ||
const Query = require("@fxjs/sql-query"); | ||
const SqlQuery = require("@fxjs/sql-query"); | ||
const _cloneDeep = require('lodash.clonedeep'); | ||
@@ -20,3 +20,3 @@ const Model_1 = require("./Model"); | ||
const Property = require("./Property"); | ||
function use(connection, proto, opts, cb) { | ||
const use = function (connection, proto, opts, cb) { | ||
if (DriverAliases[proto]) { | ||
@@ -30,5 +30,5 @@ proto = DriverAliases[proto]; | ||
try { | ||
var Driver = adapters.get(proto); | ||
var settings = Settings.Container(SettingsInstance.get('*')); | ||
var driver = new Driver(null, connection, { | ||
const Driver = adapters.get(proto); | ||
const settings = Settings.Container(SettingsInstance.get('*')); | ||
const driver = new Driver(null, connection, { | ||
debug: (opts.query && opts.query.debug === 'true'), | ||
@@ -39,8 +39,7 @@ settings: settings | ||
} | ||
catch (ex) { | ||
return cb(ex); | ||
catch (err) { | ||
return cb(err); | ||
} | ||
} | ||
; | ||
function connect() { | ||
}; | ||
const connect = function () { | ||
let opts = arguments[0], cb = arguments[1]; | ||
@@ -94,8 +93,9 @@ if (arguments.length === 0 || !opts) { | ||
} | ||
const cfg = opts; | ||
try { | ||
var Driver = adapters.get(proto); | ||
var settings = Settings.Container(SettingsInstance.get('*')); | ||
var driver = new Driver(opts, null, { | ||
debug: 'debug' in opts.query ? opts.query.debug : settings.get("connection.debug"), | ||
pool: 'pool' in opts.query ? opts.query.pool : settings.get("connection.pool"), | ||
var driver = new Driver(cfg, null, { | ||
debug: 'debug' in cfg.query ? cfg.query.debug : settings.get("connection.debug"), | ||
pool: 'pool' in cfg.query ? cfg.query.pool : settings.get("connection.pool"), | ||
settings: settings | ||
@@ -123,5 +123,4 @@ }); | ||
return db; | ||
} | ||
; | ||
function ORM(driver_name, driver, settings) { | ||
}; | ||
const ORM = function (driver_name, driver, settings) { | ||
this.validators = validators; | ||
@@ -133,3 +132,3 @@ this.enforce = Enforces; | ||
this.driver.uid = uuid.node().hex(); | ||
this.tools = Object.assign({}, Query.comparators); | ||
this.tools = Object.assign({}, SqlQuery.comparators); | ||
this.models = {}; | ||
@@ -156,3 +155,3 @@ this.plugins = []; | ||
driver.on("error", onError); | ||
} | ||
}; | ||
util.inherits(ORM, events.EventEmitter); | ||
@@ -171,3 +170,3 @@ ORM.prototype.use = function (plugin_const, opts) { | ||
for (var k in this.models) { | ||
plugin.define(this.models[k]); | ||
plugin.define(this.models[k], this); | ||
} | ||
@@ -179,6 +178,5 @@ } | ||
ORM.prototype.define = function (name, properties, opts) { | ||
var i; | ||
properties = properties || {}; | ||
opts = opts || {}; | ||
for (i = 0; i < this.plugins.length; i++) { | ||
for (let i = 0; i < this.plugins.length; i++) { | ||
if (typeof this.plugins[i].beforeDefine === "function") { | ||
@@ -194,2 +192,3 @@ this.plugins[i].beforeDefine(name, properties, opts); | ||
table: opts.table || opts.collection || ((this.settings.get("model.namePrefix") || "") + name), | ||
// not standard FxOrmProperty.NormalizedPropertyHash here, but we should pass it firstly | ||
properties: properties, | ||
@@ -208,3 +207,3 @@ extension: opts.extension || false, | ||
}); | ||
for (i = 0; i < this.plugins.length; i++) { | ||
for (let i = 0; i < this.plugins.length; i++) { | ||
if (typeof this.plugins[i].define === "function") { | ||
@@ -237,3 +236,3 @@ this.plugins[i].define(this.models[name], this); | ||
if (files.length === 0) { | ||
return cb(); | ||
return cb(null); | ||
} | ||
@@ -258,3 +257,3 @@ var file = files.shift(); | ||
if (modelIds.length === 0) { | ||
return cb(); | ||
return cb(null); | ||
} | ||
@@ -280,3 +279,3 @@ var modelId = modelIds.shift(); | ||
if (modelIds.length === 0) { | ||
return cb(); | ||
return cb(null); | ||
} | ||
@@ -298,4 +297,3 @@ var modelId = modelIds.shift(); | ||
}; | ||
ORM.prototype.serial = function () { | ||
var chains = Array.prototype.slice.apply(arguments); | ||
ORM.prototype.serial = function (...chains) { | ||
return { | ||
@@ -351,4 +349,4 @@ get: function (cb) { | ||
singleton, | ||
Property, Text: Query.Text }, Query.comparators, { enforce: Enforces, settings: SettingsInstance, ErrorCodes: ORMError.codes, addAdapter: adapters.add, use, | ||
Property, Text: SqlQuery.Text }, SqlQuery.comparators, { enforce: Enforces, settings: SettingsInstance, ErrorCodes: ORMError.codes, addAdapter: adapters.add, use, | ||
connect, connectSync: Patch(connect) }); | ||
module.exports = ORM_Module; |
@@ -20,2 +20,3 @@ Object.defineProperty(exports, "__esModule", { value: true }); | ||
var m = o.model || o; | ||
// keyof FxSqlQuerySql.DetailedQueryWhereCondition | ||
var comps = ['val', 'from', 'to']; | ||
@@ -91,4 +92,4 @@ if (old_func.is_new) | ||
]; | ||
function enum_associations(assoc) { | ||
assoc.forEach(function (item) { | ||
function enum_associations(assocs) { | ||
assocs.forEach(function (item) { | ||
if (item.getAccessor) | ||
@@ -112,3 +113,8 @@ methods.push(item.getAccessor); | ||
enum_associations(opts.extend_associations); | ||
enum_associations(opts.association_properties); | ||
/** | ||
* leave it here just due to historical reason, | ||
* maybe useless here, its's all string in it | ||
*/ | ||
// enum_associations(opts.association_properties); | ||
// patch lazyload's accessor | ||
for (var f in opts.fieldToPropertyMap) { | ||
@@ -154,2 +160,7 @@ if (opts.fieldToPropertyMap[f].lazyload) { | ||
_afterAutoFetch = opts.hooks.afterAutoFetch; | ||
/** | ||
* use `afterAutoFetch` rather than `afterLoad`, | ||
* because patch in `afterLoad` only process instance's basic(exclude lazyload) fields' accessors, | ||
* as patch in `afterAutoFetch` would process instance's basic/lazyload/associated fields' accessors | ||
*/ | ||
m.afterAutoFetch(function (next) { | ||
@@ -195,3 +206,3 @@ patchObject(this); | ||
return cb(null); | ||
var i, ids = {}, prop; | ||
var ids = {}, prop; | ||
if (keyProperties.length == 1 && keyProperties[0].type == 'serial') { | ||
@@ -202,3 +213,3 @@ ids[keyProperties[0].name] = info.insertId; | ||
else { | ||
for (i = 0; i < keyProperties.length; i++) { | ||
for (let i = 0; i < keyProperties.length; i++) { | ||
prop = keyProperties[i]; | ||
@@ -214,2 +225,5 @@ // Zero is a valid value for an ID column | ||
; | ||
/** | ||
* @description patch `date` type property's transform | ||
*/ | ||
function patchDriver(driver) { | ||
@@ -216,0 +230,0 @@ if (driver.dialect === 'sqlite') |
@@ -8,22 +8,24 @@ Object.defineProperty(exports, "__esModule", { value: true }); | ||
]; | ||
function normalize(opts) { | ||
exports.normalize = function (opts) { | ||
let result_prop = opts.prop; | ||
if (typeof opts.prop === "function") { | ||
switch (opts.prop.name) { | ||
const primitiveProp = opts.prop; | ||
switch (primitiveProp.name) { | ||
case "String": | ||
opts.prop = { type: "text" }; | ||
result_prop = { type: "text" }; | ||
break; | ||
case "Number": | ||
opts.prop = { type: "number" }; | ||
result_prop = { type: "number" }; | ||
break; | ||
case "Boolean": | ||
opts.prop = { type: "boolean" }; | ||
result_prop = { type: "boolean" }; | ||
break; | ||
case "Date": | ||
opts.prop = { type: "date" }; | ||
result_prop = { type: "date" }; | ||
break; | ||
case "Object": | ||
opts.prop = { type: "object" }; | ||
result_prop = { type: "object" }; | ||
break; | ||
case "Buffer": | ||
opts.prop = { type: "binary" }; | ||
result_prop = { type: "binary" }; | ||
break; | ||
@@ -33,37 +35,36 @@ } | ||
else if (typeof opts.prop === "string") { | ||
var tmp = opts.prop; | ||
opts.prop = {}; | ||
opts.prop.type = tmp; | ||
result_prop = { | ||
type: opts.prop | ||
}; | ||
} | ||
else if (Array.isArray(opts.prop)) { | ||
opts.prop = { type: "enum", values: opts.prop }; | ||
result_prop = { type: "enum", values: opts.prop }; | ||
} | ||
else { | ||
opts.prop = _cloneDeep(opts.prop); | ||
result_prop = _cloneDeep(opts.prop); | ||
} | ||
if (KNOWN_TYPES.indexOf(opts.prop.type) === -1 && !(opts.prop.type in opts.customTypes)) { | ||
throw new ORMError("Unknown property type: " + opts.prop.type, 'NO_SUPPORT'); | ||
if (KNOWN_TYPES.indexOf(result_prop.type) === -1 && !(result_prop.type in opts.customTypes)) { | ||
throw new ORMError("Unknown property type: " + result_prop.type, 'NO_SUPPORT'); | ||
} | ||
if (!opts.prop.hasOwnProperty("required") && opts.settings.get("properties.required")) { | ||
opts.prop.required = true; | ||
if (!result_prop.hasOwnProperty("required") && opts.settings.get("properties.required")) { | ||
result_prop.required = true; | ||
} | ||
// Defaults to true. Setting to false hides properties from JSON.stringify(modelInstance). | ||
if (!opts.prop.hasOwnProperty("enumerable") || opts.prop.enumerable === true) { | ||
opts.prop.enumerable = true; | ||
if (!result_prop.hasOwnProperty("enumerable") || result_prop.enumerable === true) { | ||
result_prop.enumerable = true; | ||
} | ||
// Defaults to true. Rational means floating point here. | ||
if (opts.prop.type == "number" && opts.prop.rational === undefined) { | ||
opts.prop.rational = true; | ||
if (result_prop.type == "number" && result_prop.rational === undefined) { | ||
result_prop.rational = true; | ||
} | ||
if (!('mapsTo' in opts.prop)) { | ||
opts.prop.mapsTo = opts.name; | ||
if (!('mapsTo' in result_prop)) { | ||
result_prop.mapsTo = opts.name; | ||
} | ||
if (opts.prop.type == "number" && opts.prop.rational === false) { | ||
opts.prop.type = "integer"; | ||
delete opts.prop.rational; | ||
if (result_prop.type == "number" && result_prop.rational === false) { | ||
result_prop.type = "integer"; | ||
delete result_prop.rational; | ||
} | ||
opts.prop.name = opts.name; | ||
return opts.prop; | ||
} | ||
exports.normalize = normalize; | ||
; | ||
result_prop.name = opts.name; | ||
return result_prop; | ||
// return opts.prop; | ||
}; |
@@ -0,1 +1,2 @@ | ||
/// <reference path="../../../@types/index.d.ts" /> | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
@@ -2,0 +3,0 @@ const _cloneDeep = require('lodash.clonedeep'); |
Object.defineProperty(exports, "__esModule", { value: true }); | ||
let map = {}; | ||
function clear(key) { | ||
exports.clear = function (key) { | ||
if (typeof key === "string") { | ||
@@ -11,9 +11,9 @@ delete map[key]; | ||
return this; | ||
} | ||
exports.clear = clear; | ||
; | ||
function get(key, opts, createCb, returnCb) { | ||
if (opts && opts.identityCache === false) { | ||
}; | ||
exports.get = function (key, opts, createCb, returnCb) { | ||
/** | ||
* @description when dont identity cache | ||
*/ | ||
if (opts && opts.identityCache === false) | ||
return createCb(returnCb); | ||
} | ||
if (map.hasOwnProperty(key)) { | ||
@@ -35,2 +35,3 @@ if (opts && opts.saveCheck && typeof map[key].o.saved === "function" && !map[key].o.saved()) { | ||
map[key] = { | ||
// object , timeout | ||
o: value, | ||
@@ -41,4 +42,2 @@ t: (opts && typeof opts.identityCache === "number" ? Date.now() + (opts.identityCache * 1000) : null) | ||
}); | ||
} | ||
exports.get = get; | ||
; | ||
}; |
@@ -51,42 +51,39 @@ Object.defineProperty(exports, "__esModule", { value: true }); | ||
/** | ||
* Operations | ||
* A) Build an index of associations, with their name as the key | ||
* B) Check for any conditions with a key in the association index | ||
* C) Ensure that our condition supports array values | ||
* D) Remove original condition (not DB compatible) | ||
* E) Convert our association fields into an array, indexes are the same as model.id | ||
* F) Itterate through values for the condition, only accept instances of the same type as the association | ||
* @description filtered out FxOrmInstance.Instance in mixed FxSqlQuerySubQuery.SubQueryConditions | { [k: string]: FxOrmInstance.Instance } | ||
*/ | ||
function checkConditions(conditions, one_associations) { | ||
var k, i, j; | ||
// A) | ||
function checkConditions(conditions, | ||
// one_associations: ( FxOrmAssociation.AssociationDefinitionOptions_HasOne | FxOrmAssociation.InstanceAssociationItem_HasOne )[] | ||
one_associations) { | ||
// A) Build an index of associations, with their name as the key | ||
var associations = {}; | ||
for (i = 0; i < one_associations.length; i++) { | ||
for (let i = 0; i < one_associations.length; i++) { | ||
associations[one_associations[i].name] = one_associations[i]; | ||
} | ||
for (k in conditions) { | ||
// B) | ||
for (let k in conditions) { | ||
// B) Check for any conditions with a key in the association index | ||
if (!associations.hasOwnProperty(k)) | ||
continue; | ||
// C) | ||
// C) Ensure that our condition supports array values | ||
var values = conditions[k]; | ||
if (!Array.isArray(values)) | ||
values = [values]; | ||
// D) | ||
// D) Remove original condition (it's instance rather conditon, we would replace it later; not DB compatible) | ||
delete conditions[k]; | ||
// E) | ||
var association_fields = Object.keys(associations[k].field); | ||
var model = associations[k].model; | ||
// F) | ||
for (i = 0; i < values.length; i++) { | ||
if (values[i].isInstance && values[i].model().uid === model.uid) { | ||
// E) Convert our association fields into an array, indexes are the same as model.id | ||
const association_fields = Object.keys(associations[k].field); | ||
const model = associations[k].model; | ||
// F) Iterate through values for the condition, only accept instances of the same type as the association | ||
for (let i = 0; i < values.length; i++) { | ||
const instance = (values[i].isInstance && values[i]); | ||
if (instance && instance.model().uid === model.uid) { | ||
if (association_fields.length === 1) { | ||
if (typeof conditions[association_fields[0]] === 'undefined') { | ||
conditions[association_fields[0]] = values[i][model.id[0]]; | ||
const cond_k = association_fields[0]; | ||
if (conditions[cond_k] === undefined) { | ||
conditions[cond_k] = instance[model.id[0]]; | ||
} | ||
else if (Array.isArray(conditions[association_fields[0]])) { | ||
conditions[association_fields[0]].push(values[i][model.id[0]]); | ||
else if (Array.isArray(conditions[cond_k])) { | ||
conditions[cond_k].push(instance[model.id[0]]); | ||
} | ||
else { | ||
conditions[association_fields[0]] = [conditions[association_fields[0]], values[i][model.id[0]]]; | ||
conditions[cond_k] = [conditions[cond_k], instance[model.id[0]]]; | ||
} | ||
@@ -96,4 +93,4 @@ } | ||
var _conds = {}; | ||
for (j = 0; j < association_fields.length; i++) { | ||
_conds[association_fields[j]] = values[i][model.id[j]]; | ||
for (let j = 0; j < association_fields.length; i++) { | ||
_conds[association_fields[j]] = instance[model.id[j]]; | ||
} | ||
@@ -115,5 +112,5 @@ conditions.or = conditions.or || []; | ||
function values(obj, keys) { | ||
var i, k, vals = []; | ||
var vals = []; | ||
if (keys) { | ||
for (i = 0; i < keys.length; i++) { | ||
for (let i = 0; i < keys.length; i++) { | ||
vals.push(obj[keys[i]]); | ||
@@ -123,3 +120,3 @@ } | ||
else if (Array.isArray(obj)) { | ||
for (i = 0; i < obj.length; i++) { | ||
for (let i = 0; i < obj.length; i++) { | ||
vals.push(obj[i]); | ||
@@ -129,3 +126,3 @@ } | ||
else { | ||
for (k in obj) { | ||
for (let k in obj) { | ||
if (!/[0-9]+/.test(k)) { | ||
@@ -158,3 +155,4 @@ vals.push(obj[k]); | ||
else if (Array.isArray(target[fields[i]])) { | ||
target[fields[i]].push(source[model.id[i]]); | ||
target[fields[i]] | ||
.push(source[model.id[i]]); | ||
} | ||
@@ -193,4 +191,5 @@ else { | ||
} | ||
const field_str = params.field; | ||
var newObj = {}, newProp, propPreDefined, propFromKey; | ||
propPreDefined = params.model.properties[params.field]; | ||
propPreDefined = params.model.properties[field_str]; | ||
propFromKey = params.model.properties[params.model.id[0]]; | ||
@@ -201,6 +200,7 @@ newProp = { type: 'integer' }; | ||
util.extend(prop, { | ||
name: params.field, mapsTo: params.mapsTo || params.field | ||
name: field_str, | ||
mapsTo: params.mapsTo || field_str | ||
}); | ||
} | ||
newObj[params.field] = prop; | ||
newObj[field_str] = prop; | ||
return newObj; | ||
@@ -207,0 +207,0 @@ } |
@@ -42,5 +42,4 @@ Object.defineProperty(exports, "__esModule", { value: true }); | ||
function unique(opts = {}, msg = null) { | ||
var arg, k; | ||
for (k in arguments) { | ||
arg = arguments[k]; | ||
for (let k in arguments) { | ||
const arg = arguments[k]; | ||
if (typeof arg === "string") { | ||
@@ -54,3 +53,2 @@ msg = arg; | ||
return function (v, next, ctx) { | ||
var s, scopeProp; | ||
if (typeof v === "undefined" || v === null) { | ||
@@ -90,4 +88,4 @@ return next(); | ||
if (opts.scope) { | ||
for (s in opts.scope) { | ||
scopeProp = opts.scope[s]; | ||
for (let s in opts.scope) { | ||
let scopeProp = opts.scope[s]; | ||
// In SQL unique index land, NULL values are not considered equal. | ||
@@ -94,0 +92,0 @@ if (typeof ctx.instance[scopeProp] == 'undefined' || ctx.instance[scopeProp] === null) { |
{ | ||
"name": "@fxjs/orm", | ||
"version": "1.7.3", | ||
"version": "1.8.0", | ||
"description": "Object Relational Mapping for fibjs", | ||
@@ -42,4 +42,4 @@ "main": "lib", | ||
"@fibjs/enforce": "0.0.7", | ||
"@fxjs/sql-ddl-sync": "0.0.1", | ||
"@fxjs/sql-query": "0.0.2", | ||
"@fxjs/sql-ddl-sync": "^0.1.0", | ||
"@fxjs/sql-query": "^0.1.1", | ||
"fib-typify": "^0.4.1", | ||
@@ -55,3 +55,7 @@ "lodash.clonedeep": "^4.5.0", | ||
"semver": "^5.6.0" | ||
}, | ||
"peerDependencies": { | ||
"@fxjs/sql-query": "0.1.x", | ||
"@fxjs/sql-ddl-syn": "0.1.x" | ||
} | ||
} |
294253
60
7242
9
+ Added@fxjs/sql-ddl-sync@0.1.2(transitive)
+ Added@fxjs/sql-query@0.1.4(transitive)
- Removed@fxjs/sql-ddl-sync@0.0.1(transitive)
- Removed@fxjs/sql-query@0.0.2(transitive)
- Removedshould@13.2.3(transitive)
- Removedshould-equal@2.0.0(transitive)
- Removedshould-format@3.0.3(transitive)
- Removedshould-type@1.4.0(transitive)
- Removedshould-type-adaptors@1.1.0(transitive)
- Removedshould-util@1.0.1(transitive)
Updated@fxjs/sql-ddl-sync@^0.1.0
Updated@fxjs/sql-query@^0.1.1