diff --git a/.env b/.env index a468954d..c2504c93 100644 --- a/.env +++ b/.env @@ -6,7 +6,7 @@ MYSQL_PORT=3306 MYSQL_USER=virk MYSQL_PASSWORD=password -PG_HOST=0.0.0.0 +PG_HOST=pg PG_PORT=5432 -PG_USER=relay +PG_USER=virk PG_PASSWORD=password diff --git a/adonis-typings/model.ts b/adonis-typings/model.ts index 9af1f2dc..60d05698 100644 --- a/adonis-typings/model.ts +++ b/adonis-typings/model.ts @@ -82,7 +82,7 @@ declare module '@ioc:Adonis/Lucid/Model' { */ export type ColumnOptions = { castAs: string, - serializeAs: string | null, + serializeAs: string | null, // null means do not serialize column isPrimary: boolean, hasGetter: boolean, hasSetter: boolean, @@ -101,8 +101,11 @@ declare module '@ioc:Adonis/Lucid/Model' { */ export type ColumnDecorator = ( options?: Partial>, - ) => (target, property) => void - export type ComputedDecorator = (options?: Partial) => (target, property) => void + ) => (target: any, property: any) => void + + export type ComputedDecorator = ( + options?: Partial, + ) => (target: any, property: any) => void /** * ------------------------------------------------------ @@ -160,7 +163,7 @@ declare module '@ioc:Adonis/Lucid/Model' { * Reference to query client used for making queries */ client: QueryClientContract - knexQuery: knex.QueryBuilder, + knexQuery: knex.QueryBuilder /** * A custom set of sideloaded properties defined on the query @@ -169,11 +172,6 @@ declare module '@ioc:Adonis/Lucid/Model' { */ sideload (value: ModelObject): this - /** - * The connection name used by the model query builder - */ - connection: string - /** * Execute and get first result */ @@ -214,18 +212,20 @@ declare module '@ioc:Adonis/Lucid/Model' { $attributes: ModelObject $extras: ModelObject $original: ModelObject - $dirty: ModelObject - $isPersisted: boolean - $isNew: boolean - $isLocal: boolean - $isDirty: boolean - $isDeleted: boolean $preloaded: { [relation: string]: ModelContract | ModelContract[] } - $sideloaded: ModelObject - $primaryKeyValue?: number | string - $options?: ModelOptions - $trx?: TransactionClientContract, + sideloaded: ModelObject + + primaryKeyValue?: number | string + isPersisted: boolean + isNew: boolean + isLocal: boolean + dirty: ModelObject + isDirty: boolean + isDeleted: boolean + + options?: ModelOptions + trx?: TransactionClientContract, $setOptionsAndTrx (options?: ModelAdapterOptions): void /** @@ -290,6 +290,7 @@ declare module '@ioc:Adonis/Lucid/Model' { */ $consumeAdapterResult (adapterResult: ModelObject, sideloadAttributes?: ModelObject): void + hydrateOriginals(): void fill (value: ModelObject): void merge (value: ModelObject): void save (): Promise @@ -297,9 +298,7 @@ declare module '@ioc:Adonis/Lucid/Model' { serialize (): ModelObject toJSON (): ModelObject refresh (): Promise - preload: ModelBuilderPreloadFn - related< Name extends keyof ExtractRelations, RelationType extends TypedRelations = this[Name] extends TypedRelations ? this[Name] : never @@ -323,7 +322,7 @@ declare module '@ioc:Adonis/Lucid/Model' { * Whether or not model has been booted. After this model configurations * are ignored */ - $booted: boolean + readonly booted: boolean /** * A map of defined columns @@ -344,12 +343,12 @@ declare module '@ioc:Adonis/Lucid/Model' { * The primary key for finding unique referencing to a * model */ - $primaryKey: string + readonly primaryKey: string /** * Custom database connection to use */ - $connection?: string + readonly connection?: string /** * Adapter to work as a bridge between query builder and the model @@ -365,38 +364,18 @@ declare module '@ioc:Adonis/Lucid/Model' { * Whether primary key is auto incrementing or not. If not, then * end user must provide the value for the primary key */ - $increments: boolean + readonly increments: boolean /** * Database table to use */ - $table: string + readonly table: string /** * Refs are named value pair on model used mainly for autocompleting * the query constraints */ - $refs: { [key: string]: string } - - $boot (): void - - /** - * Register a before hook - */ - $before ( - this: T, - event: EventsList, - handler: HooksHandler>, - ): void - - /** - * Register an after hook - */ - $after ( - this: T, - event: EventsList, - handler: HooksHandler>, - ): void + readonly $refs: { [key: string]: string } /** * Creating model from adapter results @@ -463,6 +442,26 @@ declare module '@ioc:Adonis/Lucid/Model' { $resolveCastKey (key: string): string $mapKeysToCastKeys (values: ModelObject): ModelObject + boot (): void + + /** + * Register a before hook + */ + before ( + this: T, + event: EventsList, + handler: HooksHandler>, + ): void + + /** + * Register an after hook + */ + after ( + this: T, + event: EventsList, + handler: HooksHandler>, + ): void + /** * Creating model */ @@ -640,32 +639,55 @@ declare module '@ioc:Adonis/Lucid/Model' { * defaults */ export type OrmConfigContract = { + /** + * Return the default table name for a given model + */ getTableName (model: ModelConstructorContract): string + + /** + * Return the `castAs` key (database column name) for a given model + * property. + */ getCastAsKey (model: ModelConstructorContract, key: string): string + + /** + * Return the `serializeAs` key for a given model property + */ getSerializeAsKey (model: ModelConstructorContract, key: string): string - serialize (model: ModelConstructorContract, key: string): boolean + /** + * Return the local key property name for a given relationship + */ getLocalKey ( relation: TypedRelations['type'], model: ModelConstructorContract, relatedModel: ModelConstructorContract, ): string + /** + * Return the foreign key property name for a given relationship + */ getForeignKey ( relation: TypedRelations['type'], model: ModelConstructorContract, relatedModel: ModelConstructorContract, ): string + /** + * Return the pivot table name for many to many relationship + */ getPivotTableName ( - relation: TypedRelations['type'], + relation: 'manyToMany', model: ModelConstructorContract, relatedModel: ModelConstructorContract, relationName: string, ): string + /** + * Return the pivot foreign key for many to many relationship + */ getPivotForeignKey ( - relation: TypedRelations['type'], + relation: 'manyToMany', model: ModelConstructorContract, relatedModel: ModelConstructorContract, relationName: string, diff --git a/adonis-typings/relations.ts b/adonis-typings/relations.ts index f85a7ab0..e308afe3 100644 --- a/adonis-typings/relations.ts +++ b/adonis-typings/relations.ts @@ -15,11 +15,7 @@ declare module '@ioc:Adonis/Lucid/Relations' { ModelQueryBuilderContract, } from '@ioc:Adonis/Lucid/Model' - import { - QueryClientContract, - ExcutableQueryBuilderContract, - } from '@ioc:Adonis/Lucid/Database' - + import { QueryClientContract } from '@ioc:Adonis/Lucid/Database' import { StrictValues, QueryCallback, @@ -72,7 +68,7 @@ declare module '@ioc:Adonis/Lucid/Relations' { export type HasOneDecorator = ( model: RelationOptions['relatedModel'], options?: Omit, - ) => (target, property) => void + ) => (target: any, property: string | Symbol) => void /** * Decorator signature to define has many relationship @@ -80,7 +76,7 @@ declare module '@ioc:Adonis/Lucid/Relations' { export type HasManyDecorator = ( model: RelationOptions['relatedModel'], options?: Omit, - ) => (target, property) => void + ) => (target: any, property: string | Symbol) => void /** * Decorator signature to define belongs to relationship @@ -88,7 +84,7 @@ declare module '@ioc:Adonis/Lucid/Relations' { export type BelongsToDecorator = ( model: RelationOptions['relatedModel'], options?: Omit, - ) => (target, property) => void + ) => (target: any, property: string | Symbol) => void /** * Decorator signature to define many to many relationship @@ -96,7 +92,7 @@ declare module '@ioc:Adonis/Lucid/Relations' { export type ManyToManyDecorator = ( model: ManyToManyRelationOptions['relatedModel'], column?: Omit, - ) => (target, property) => void + ) => (target: any, property: string | Symbol) => void /** * Decorator signature to define has many through relationship @@ -104,7 +100,7 @@ declare module '@ioc:Adonis/Lucid/Relations' { export type HasManyThroughDecorator = ( model: [ThroughRelationOptions['relatedModel'], ThroughRelationOptions['throughModel']], column?: Omit, - ) => (target, property) => void + ) => (target: any, property: string | Symbol) => void /** * ------------------------------------------------------ @@ -193,8 +189,7 @@ declare module '@ioc:Adonis/Lucid/Relations' { */ export type ExtractRelationModel< Relation extends TypedRelations, - > = - Relation['type'] extends 'hasOne' | 'belongsTo' ? Relation['instance'] : Relation['instance'][] + > = Relation['type'] extends 'hasOne' | 'belongsTo' ? Relation['instance'] : Relation['instance'][] /** * ------------------------------------------------------ @@ -209,15 +204,13 @@ declare module '@ioc:Adonis/Lucid/Relations' { Model extends ModelConstructorContract, RelatedModel extends ModelConstructorContract > { - $type: TypedRelations['type'] - $relationName: string - $serializeAs: string - $booted: boolean - $model: Model - $profilerData: { [key: string]: any }, - - $boot (): void - $relatedModel (): RelatedModel + readonly type: TypedRelations['type'] + readonly relationName: string + readonly serializeAs: string + readonly booted: boolean + readonly model: Model + relatedModel (): RelatedModel + boot (): void } /** @@ -227,7 +220,7 @@ declare module '@ioc:Adonis/Lucid/Relations' { Model extends ModelConstructorContract, RelatedModel extends ModelConstructorContract > extends BaseRelationContract { - $type: 'hasOne' + type: 'hasOne' $setRelated ( parent: InstanceType, @@ -260,7 +253,7 @@ declare module '@ioc:Adonis/Lucid/Relations' { Model extends ModelConstructorContract, RelatedModel extends ModelConstructorContract > extends BaseRelationContract { - $type: 'hasMany' + type: 'hasMany' $setRelated ( parent: InstanceType, @@ -293,7 +286,7 @@ declare module '@ioc:Adonis/Lucid/Relations' { Model extends ModelConstructorContract, RelatedModel extends ModelConstructorContract > extends BaseRelationContract { - $type: 'belongsTo' + type: 'belongsTo' $setRelated ( parent: InstanceType, @@ -326,7 +319,7 @@ declare module '@ioc:Adonis/Lucid/Relations' { Model extends ModelConstructorContract, RelatedModel extends ModelConstructorContract > extends BaseRelationContract { - $type: 'manyToMany' + type: 'manyToMany' $setRelated ( parent: InstanceType, @@ -359,7 +352,7 @@ declare module '@ioc:Adonis/Lucid/Relations' { Model extends ModelConstructorContract, RelatedModel extends ModelConstructorContract > extends BaseRelationContract { - $type: 'hasManyThrough' + type: 'hasManyThrough' $setRelated ( parent: InstanceType, @@ -404,15 +397,16 @@ declare module '@ioc:Adonis/Lucid/Relations' { Model extends ModelConstructorContract, RelatedModel extends ModelConstructorContract > { + /** + * Return a query builder instance of the relationship + */ query (): RelationBaseQueryBuilderContract> - & ExcutableQueryBuilderContract[]> /** * Eager query only works when client instance is created using multiple * parent model instances */ eagerQuery (): RelationBaseQueryBuilderContract> - & ExcutableQueryBuilderContract[]> } /** @@ -424,7 +418,6 @@ declare module '@ioc:Adonis/Lucid/Relations' { > extends RelationBaseQueryClientContract { save (related: InstanceType): Promise create (values: ModelObject): Promise> - firstOrCreate (search: ModelObject, savePayload?: ModelObject): Promise> updateOrCreate (search: ModelObject, updatePayload: ModelObject): Promise> } @@ -461,31 +454,52 @@ declare module '@ioc:Adonis/Lucid/Relations' { RelatedModel extends ModelConstructorContract > { query (): ManyToManyQueryBuilderContract> - & ExcutableQueryBuilderContract[]> /** * Eager query only works when client instance is created using multiple * parent model instances */ eagerQuery (): ManyToManyQueryBuilderContract> - & ExcutableQueryBuilderContract[]> /** * Pivot query just targets the pivot table without any joins */ pivotQuery (): ManyToManyQueryBuilderContract> - & ExcutableQueryBuilderContract[]> - save (related: InstanceType, checkExisting?: boolean): Promise + /** + * Save related model instance. + */ + save (related: InstanceType): Promise + + /** + * Create related model instance + */ create (values: ModelObject): Promise> + /** + * Save many of related model instance. + */ saveMany (related: InstanceType[]): Promise + + /** + * Create many of related model instances + */ createMany (values: ModelObject[]): Promise[]> + /** + * Attach new pivot rows + */ attach (ids: (string | number)[] | { [key: string]: ModelObject }): Promise + + /** + * Detach existing pivot rows + */ detach (ids: (string | number)[]): Promise - sync (ids: (string | number)[] | { [key: string]: ModelObject }, checkExisting?: boolean): Promise + /** + * Sync pivot rows. + */ + sync (ids: (string | number)[] | { [key: string]: ModelObject }): Promise } /** @@ -501,8 +515,7 @@ declare module '@ioc:Adonis/Lucid/Relations' { Related extends ModelConstructorContract, Result extends any = InstanceType > extends ModelQueryBuilderContract { - applyConstraints (): void - selectRelationKeys (): this + $selectRelationKeys (): this } /** @@ -579,8 +592,8 @@ declare module '@ioc:Adonis/Lucid/Relations' { * Shape of the preloader to preload relationships */ export interface PreloaderContract { - processAllForOne (parent: Model, client: QueryClientContract): Promise - processAllForMany (parent: Model[], client: QueryClientContract): Promise + $processAllForOne (parent: Model, client: QueryClientContract): Promise + $processAllForMany (parent: Model[], client: QueryClientContract): Promise preload: QueryBuilderPreloadFn sideload (values: ModelObject): this } diff --git a/adonis-typings/schema.ts b/adonis-typings/schema.ts index af962dca..1ff4e6a4 100644 --- a/adonis-typings/schema.ts +++ b/adonis-typings/schema.ts @@ -8,7 +8,7 @@ */ declare module '@ioc:Adonis/Lucid/Schema' { - import { QueryClientContract, ExcutableQueryBuilderContract } from '@ioc:Adonis/Lucid/Database' + import { QueryClientContract } from '@ioc:Adonis/Lucid/Database' import { RawContract } from '@ioc:Adonis/Lucid/DatabaseQueryBuilder' import { SchemaBuilder, Raw } from 'knex' diff --git a/src/Database/QueryBuilder/Chainable.ts b/src/Database/QueryBuilder/Chainable.ts index c94fae71..4a9688f0 100644 --- a/src/Database/QueryBuilder/Chainable.ts +++ b/src/Database/QueryBuilder/Chainable.ts @@ -39,7 +39,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { throw new Error('Invalid array for whereBetween value') } - return [this.$transformValue(lhs), this.$transformValue(rhs)] + return [this.transformValue(lhs), this.transformValue(rhs)] } /** @@ -49,7 +49,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { private normalizeAggregateColumns (columns: any, alias?: any): any { if (columns.constructor === Object) { return Object.keys(columns).reduce((result, key) => { - result[key] = this.$transformValue(columns[key]) + result[key] = this.transformValue(columns[key]) return result }, {}) } @@ -58,7 +58,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { return columns } - return { [alias]: this.$transformValue(columns) } + return { [alias]: this.transformValue(columns) } } /** @@ -70,23 +70,23 @@ export abstract class Chainable extends Macroable implements ChainableContract { * 3. Wrapping callbacks, so that the end user receives an instance Lucid query * builder and not knex query builder. */ - protected $transformValue (value: any) { + protected transformValue (value: any) { if (value instanceof Chainable) { return value.knexQuery } if (typeof (value) === 'function') { - return this.$transformCallback(value) + return this.transformCallback(value) } - return this.$transformRaw(value) + return this.transformRaw(value) } /** * Transforms the user callback to something that knex * can internally process */ - protected $transformCallback (value: any) { + protected transformCallback (value: any) { if (typeof (value) === 'function') { return this.queryCallback(value) } @@ -98,7 +98,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Returns the underlying knex raw query builder for Lucid raw * query builder */ - protected $transformRaw (value: any) { + protected transformRaw (value: any) { if (value instanceof RawQueryBuilder) { return value['knexQuery'] } @@ -119,7 +119,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * use the last selected table */ public from (table: any): this { - this.knexQuery.from(this.$transformCallback(table)) + this.knexQuery.from(this.transformCallback(table)) return this } @@ -128,15 +128,15 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public where (key: any, operator?: any, value?: any): this { if (value !== undefined) { - this.knexQuery.where(key, operator, this.$transformValue(value)) + this.knexQuery.where(key, operator, this.transformValue(value)) } else if (operator) { - this.knexQuery.where(key, this.$transformValue(operator)) + this.knexQuery.where(key, this.transformValue(operator)) } else { /** * Only callback is allowed as a standalone param. One must use `whereRaw` * for raw/sub queries. This is our limitation to have consistent API */ - this.knexQuery.where(this.$transformCallback(key)) + this.knexQuery.where(this.transformCallback(key)) } return this @@ -147,11 +147,11 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public orWhere (key: any, operator?: any, value?: any): this { if (value !== undefined) { - this.knexQuery.orWhere(key, operator, this.$transformValue(value)) + this.knexQuery.orWhere(key, operator, this.transformValue(value)) } else if (operator) { - this.knexQuery.orWhere(key, this.$transformValue(operator)) + this.knexQuery.orWhere(key, this.transformValue(operator)) } else { - this.knexQuery.orWhere(this.$transformCallback(key)) + this.knexQuery.orWhere(this.transformCallback(key)) } return this @@ -169,11 +169,11 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public whereNot (key: any, operator?: any, value?: any): this { if (value !== undefined) { - this.knexQuery.whereNot(key, operator, this.$transformValue(value)) + this.knexQuery.whereNot(key, operator, this.transformValue(value)) } else if (operator) { - this.knexQuery.whereNot(key, this.$transformValue(operator)) + this.knexQuery.whereNot(key, this.transformValue(operator)) } else { - this.knexQuery.whereNot(this.$transformCallback(key)) + this.knexQuery.whereNot(this.transformCallback(key)) } return this @@ -184,11 +184,11 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public orWhereNot (key: any, operator?: any, value?: any): this { if (value !== undefined) { - this.knexQuery.orWhereNot(key, operator, this.$transformValue(value)) + this.knexQuery.orWhereNot(key, operator, this.transformValue(value)) } else if (operator) { - this.knexQuery.orWhereNot(key, this.$transformValue(operator)) + this.knexQuery.orWhereNot(key, this.transformValue(operator)) } else { - this.knexQuery.orWhereNot(this.$transformCallback(key)) + this.knexQuery.orWhereNot(this.transformCallback(key)) } return this @@ -206,8 +206,8 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public whereIn (key: any, value: any): this { value = Array.isArray(value) - ? value.map((one) => this.$transformValue(one)) - : this.$transformValue(value) + ? value.map((one) => this.transformValue(one)) + : this.transformValue(value) this.knexQuery.whereIn(key, value) return this @@ -218,8 +218,8 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public orWhereIn (key: any, value: any): this { value = Array.isArray(value) - ? value.map((one) => this.$transformValue(one)) - : this.$transformValue(value) + ? value.map((one) => this.transformValue(one)) + : this.transformValue(value) this.knexQuery.orWhereIn(key, value) return this @@ -237,8 +237,8 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public whereNotIn (key: any, value: any): this { value = Array.isArray(value) - ? value.map((one) => this.$transformValue(one)) - : this.$transformValue(value) + ? value.map((one) => this.transformValue(one)) + : this.transformValue(value) this.knexQuery.whereNotIn(key, value) return this @@ -249,8 +249,8 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public orWhereNotIn (key: any, value: any): this { value = Array.isArray(value) - ? value.map((one) => this.$transformValue(one)) - : this.$transformValue(value) + ? value.map((one) => this.transformValue(one)) + : this.transformValue(value) this.knexQuery.orWhereNotIn(key, value) return this @@ -313,7 +313,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Add a `where exists` clause */ public whereExists (value: any) { - this.knexQuery.whereExists(this.$transformValue(value)) + this.knexQuery.whereExists(this.transformValue(value)) return this } @@ -321,7 +321,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Add a `or where exists` clause */ public orWhereExists (value: any) { - this.knexQuery.orWhereExists(this.$transformValue(value)) + this.knexQuery.orWhereExists(this.transformValue(value)) return this } @@ -336,7 +336,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Add a `where not exists` clause */ public whereNotExists (value: any) { - this.knexQuery.whereNotExists(this.$transformValue(value)) + this.knexQuery.whereNotExists(this.transformValue(value)) return this } @@ -344,7 +344,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Add a `or where not exists` clause */ public orWhereNotExists (value: any) { - this.knexQuery.orWhereNotExists(this.$transformValue(value)) + this.knexQuery.orWhereNotExists(this.transformValue(value)) return this } @@ -408,7 +408,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { if (bindings) { this.knexQuery.whereRaw(sql, bindings) } else { - this.knexQuery.whereRaw(this.$transformRaw(sql)) + this.knexQuery.whereRaw(this.transformRaw(sql)) } return this @@ -421,7 +421,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { if (bindings) { this.knexQuery.orWhereRaw(sql, bindings) } else { - this.knexQuery.orWhereRaw(this.$transformRaw(sql)) + this.knexQuery.orWhereRaw(this.transformRaw(sql)) } return this } @@ -438,11 +438,11 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public join (table: any, first: any, operator?: any, second?: any): this { if (second) { - this.knexQuery.join(table, first, operator, this.$transformRaw(second)) + this.knexQuery.join(table, first, operator, this.transformRaw(second)) } else if (operator) { - this.knexQuery.join(table, first, this.$transformRaw(operator)) + this.knexQuery.join(table, first, this.transformRaw(operator)) } else { - this.knexQuery.join(table, this.$transformRaw(first)) + this.knexQuery.join(table, this.transformRaw(first)) } return this @@ -453,11 +453,11 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public innerJoin (table: any, first: any, operator?: any, second?: any): this { if (second !== undefined) { - this.knexQuery.innerJoin(table, first, operator, this.$transformRaw(second)) + this.knexQuery.innerJoin(table, first, operator, this.transformRaw(second)) } else if (operator) { - this.knexQuery.innerJoin(table, first, this.$transformRaw(operator)) + this.knexQuery.innerJoin(table, first, this.transformRaw(operator)) } else { - this.knexQuery.innerJoin(table, this.$transformRaw(first)) + this.knexQuery.innerJoin(table, this.transformRaw(first)) } return this @@ -468,11 +468,11 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public leftJoin (table: any, first: any, operator?: any, second?: any): this { if (second !== undefined) { - this.knexQuery.leftJoin(table, first, operator, this.$transformRaw(second)) + this.knexQuery.leftJoin(table, first, operator, this.transformRaw(second)) } else if (operator) { - this.knexQuery.leftJoin(table, first, this.$transformRaw(operator)) + this.knexQuery.leftJoin(table, first, this.transformRaw(operator)) } else { - this.knexQuery.leftJoin(table, this.$transformRaw(first)) + this.knexQuery.leftJoin(table, this.transformRaw(first)) } return this @@ -483,11 +483,11 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public leftOuterJoin (table: any, first: any, operator?: any, second?: any): this { if (second !== undefined) { - this.knexQuery.leftOuterJoin(table, first, operator, this.$transformRaw(second)) + this.knexQuery.leftOuterJoin(table, first, operator, this.transformRaw(second)) } else if (operator) { - this.knexQuery.leftOuterJoin(table, first, this.$transformRaw(operator)) + this.knexQuery.leftOuterJoin(table, first, this.transformRaw(operator)) } else { - this.knexQuery.leftOuterJoin(table, this.$transformRaw(first)) + this.knexQuery.leftOuterJoin(table, this.transformRaw(first)) } return this @@ -498,11 +498,11 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public rightJoin (table: any, first: any, operator?: any, second?: any): this { if (second !== undefined) { - this.knexQuery.rightJoin(table, first, operator, this.$transformRaw(second)) + this.knexQuery.rightJoin(table, first, operator, this.transformRaw(second)) } else if (operator) { - this.knexQuery.rightJoin(table, first, this.$transformRaw(operator)) + this.knexQuery.rightJoin(table, first, this.transformRaw(operator)) } else { - this.knexQuery.rightJoin(table, this.$transformRaw(first)) + this.knexQuery.rightJoin(table, this.transformRaw(first)) } return this @@ -513,11 +513,11 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public rightOuterJoin (table: any, first: any, operator?: any, second?: any): this { if (second !== undefined) { - this.knexQuery.rightOuterJoin(table, first, operator, this.$transformRaw(second)) + this.knexQuery.rightOuterJoin(table, first, operator, this.transformRaw(second)) } else if (operator) { - this.knexQuery.rightOuterJoin(table, first, this.$transformRaw(operator)) + this.knexQuery.rightOuterJoin(table, first, this.transformRaw(operator)) } else { - this.knexQuery.rightOuterJoin(table, this.$transformRaw(first)) + this.knexQuery.rightOuterJoin(table, this.transformRaw(first)) } return this @@ -528,11 +528,11 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public fullOuterJoin (table: any, first: any, operator?: any, second?: any): this { if (second !== undefined) { - this.knexQuery.fullOuterJoin(table, first, operator, this.$transformRaw(second)) + this.knexQuery.fullOuterJoin(table, first, operator, this.transformRaw(second)) } else if (operator) { - this.knexQuery.fullOuterJoin(table, first, this.$transformRaw(operator)) + this.knexQuery.fullOuterJoin(table, first, this.transformRaw(operator)) } else { - this.knexQuery.fullOuterJoin(table, this.$transformRaw(first)) + this.knexQuery.fullOuterJoin(table, this.transformRaw(first)) } return this @@ -543,11 +543,11 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public crossJoin (table: any, first: any, operator?: any, second?: any): this { if (second !== undefined) { - this.knexQuery.crossJoin(table, first, operator, this.$transformRaw(second)) + this.knexQuery.crossJoin(table, first, operator, this.transformRaw(second)) } else if (operator) { - this.knexQuery.crossJoin(table, first, this.$transformRaw(operator)) + this.knexQuery.crossJoin(table, first, this.transformRaw(operator)) } else { - this.knexQuery.crossJoin(table, this.$transformRaw(first)) + this.knexQuery.crossJoin(table, this.transformRaw(first)) } return this @@ -560,7 +560,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { if (bindings) { this.knexQuery.joinRaw(sql, bindings) } else { - this.knexQuery.joinRaw(this.$transformRaw(sql)) + this.knexQuery.joinRaw(this.transformRaw(sql)) } return this @@ -574,11 +574,11 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public having (key: any, operator?: any, value?: any): this { if (value !== undefined) { - this.knexQuery.having(key, operator, this.$transformValue(value)) + this.knexQuery.having(key, operator, this.transformValue(value)) } else if (operator) { - this.knexQuery.having(key, this.$transformValue(operator)) + this.knexQuery.having(key, this.transformValue(operator)) } else { - this.knexQuery.having(this.$transformCallback(key)) + this.knexQuery.having(this.transformCallback(key)) } return this @@ -592,11 +592,11 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public orHaving (key: any, operator?: any, value?: any): this { if (value !== undefined) { - this.knexQuery.orHaving(key, operator, this.$transformValue(value)) + this.knexQuery.orHaving(key, operator, this.transformValue(value)) } else if (operator) { - this.knexQuery.orHaving(key, this.$transformValue(operator)) + this.knexQuery.orHaving(key, this.transformValue(operator)) } else { - this.knexQuery.orHaving(this.$transformCallback(key)) + this.knexQuery.orHaving(this.transformCallback(key)) } return this @@ -614,8 +614,8 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public havingIn (key: any, value: any): this { value = Array.isArray(value) - ? value.map((one) => this.$transformValue(one)) - : this.$transformValue(value) + ? value.map((one) => this.transformValue(one)) + : this.transformValue(value) this.knexQuery.havingIn(key, value) return this @@ -626,8 +626,8 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public orHavingIn (key: any, value: any): this { value = Array.isArray(value) - ? value.map((one) => this.$transformValue(one)) - : this.$transformValue(value) + ? value.map((one) => this.transformValue(one)) + : this.transformValue(value) this.knexQuery['orHavingIn'](key, value) return this @@ -645,8 +645,8 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public havingNotIn (key: any, value: any): this { value = Array.isArray(value) - ? value.map((one) => this.$transformValue(one)) - : this.$transformValue(value) + ? value.map((one) => this.transformValue(one)) + : this.transformValue(value) this.knexQuery['havingNotIn'](key, value) return this @@ -657,8 +657,8 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public orHavingNotIn (key: any, value: any): this { value = Array.isArray(value) - ? value.map((one) => this.$transformValue(one)) - : this.$transformValue(value) + ? value.map((one) => this.transformValue(one)) + : this.transformValue(value) this.knexQuery['orHavingNotIn'](key, value) return this @@ -721,7 +721,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Adding `having exists` clause */ public havingExists (value: any): this { - this.knexQuery['havingExists'](this.$transformValue(value)) + this.knexQuery['havingExists'](this.transformValue(value)) return this } @@ -729,7 +729,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Adding `or having exists` clause */ public orHavingExists (value: any): this { - this.knexQuery['orHavingExists'](this.$transformValue(value)) + this.knexQuery['orHavingExists'](this.transformValue(value)) return this } @@ -744,7 +744,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Adding `having not exists` clause */ public havingNotExists (value: any): this { - this.knexQuery['havingNotExists'](this.$transformValue(value)) + this.knexQuery['havingNotExists'](this.transformValue(value)) return this } @@ -752,7 +752,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { * Adding `or having not exists` clause */ public orHavingNotExists (value: any): this { - this.knexQuery['orHavingNotExists'](this.$transformValue(value)) + this.knexQuery['orHavingNotExists'](this.transformValue(value)) return this } @@ -816,7 +816,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { if (bindings) { this.knexQuery.havingRaw(sql, bindings) } else { - this.knexQuery.havingRaw(this.$transformRaw(sql)) + this.knexQuery.havingRaw(this.transformRaw(sql)) } return this @@ -829,7 +829,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { if (bindings) { this.knexQuery.orHavingRaw(sql, bindings) } else { - this.knexQuery.orHavingRaw(this.$transformRaw(sql)) + this.knexQuery.orHavingRaw(this.transformRaw(sql)) } return this @@ -865,7 +865,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { if (bindings) { this.knexQuery.groupByRaw(sql, bindings) } else { - this.knexQuery.groupByRaw(this.$transformRaw(sql)) + this.knexQuery.groupByRaw(this.transformRaw(sql)) } return this @@ -886,7 +886,7 @@ export abstract class Chainable extends Macroable implements ChainableContract { if (bindings) { this.knexQuery.orderByRaw(sql, bindings) } else { - this.knexQuery.orderByRaw(this.$transformRaw(sql)) + this.knexQuery.orderByRaw(this.transformRaw(sql)) } return this @@ -913,8 +913,8 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public union (queries: any, wrap?: boolean): this { queries = Array.isArray(queries) - ? queries.map((one) => this.$transformValue(one)) - : this.$transformValue(queries) + ? queries.map((one) => this.transformValue(one)) + : this.transformValue(queries) wrap ? this.knexQuery.union(queries, wrap) : this.knexQuery.union(queries) return this @@ -925,8 +925,8 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public unionAll (queries: any, wrap?: boolean): this { queries = Array.isArray(queries) - ? queries.map((one) => this.$transformValue(one)) - : this.$transformValue(queries) + ? queries.map((one) => this.transformValue(one)) + : this.transformValue(queries) wrap ? this.knexQuery.unionAll(queries, wrap) : this.knexQuery.unionAll(queries) return this @@ -937,8 +937,8 @@ export abstract class Chainable extends Macroable implements ChainableContract { */ public intersect (queries: any, wrap?: boolean): this { queries = Array.isArray(queries) - ? queries.map((one) => this.$transformValue(one)) - : this.$transformValue(queries) + ? queries.map((one) => this.transformValue(one)) + : this.transformValue(queries) wrap ? this.knexQuery.intersect(queries, wrap) : this.knexQuery.intersect(queries) return this diff --git a/src/Orm/Adapter/index.ts b/src/Orm/Adapter/index.ts index 2beccb6a..48740e17 100644 --- a/src/Orm/Adapter/index.ts +++ b/src/Orm/Adapter/index.ts @@ -36,7 +36,7 @@ export class Adapter implements AdapterContract { return options.client } - const connection = options && options.connection || modelConstructor.$connection + const connection = options && options.connection || modelConstructor.connection const profiler = options && options.profiler return this.db.connection(connection, { profiler }) } @@ -54,7 +54,7 @@ export class Adapter implements AdapterContract { */ public modelClient (instance: ModelContract): any { const modelConstructor = instance.constructor as unknown as ModelConstructorContract - return instance.$trx ? instance.$trx : this.modelConstructorClient(modelConstructor, instance.$options) + return instance.trx ? instance.trx : this.modelConstructorClient(modelConstructor, instance.options) } /** @@ -65,8 +65,8 @@ export class Adapter implements AdapterContract { const query = instance.$getQueryFor('insert', this.modelClient(instance)) const result = await query.insert(attributes) - if (modelConstructor.$increments) { - instance.$consumeAdapterResult({ [modelConstructor.$refs[modelConstructor.$primaryKey]]: result[0] }) + if (modelConstructor.increments) { + instance.$consumeAdapterResult({ [modelConstructor.$refs[modelConstructor.primaryKey]]: result[0] }) } } diff --git a/src/Orm/BaseModel/index.ts b/src/Orm/BaseModel/index.ts index 0d79b1b2..4fe50f3d 100644 --- a/src/Orm/BaseModel/index.ts +++ b/src/Orm/BaseModel/index.ts @@ -82,13 +82,13 @@ export class BaseModel implements ModelContract { /** * Primary key is required to build relationships across models */ - public static $primaryKey: string + public static primaryKey: string /** * Whether or not the model has been booted. Booting the model initializes it's * static properties. Base models must not be initialized. */ - public static $booted: boolean + public static booted: boolean /** * A set of properties marked as computed. Computed properties are included in @@ -114,13 +114,13 @@ export class BaseModel implements ModelContract { * value. If this is set to false, then the user must provide * the `$primaryKeyValue` themselves. */ - public static $increments: boolean + public static increments: boolean /** * The name of database table. It is auto generated from the model name, unless * specified */ - public static $table: string + public static table: string /** * Refs are helpful of autocompleting the model props @@ -131,7 +131,7 @@ export class BaseModel implements ModelContract { * A custom connection to use for queries. The connection defined on * query builder is preferred over the model connection */ - public static $connection?: string + public static connection?: string /** * Mappings are required, so that we can quickly lookup @@ -146,22 +146,6 @@ export class BaseModel implements ModelContract { */ private static hooks: Hooks - /** - * Register before hooks - */ - public static $before (event: EventsList, handler: HooksHandler) { - this.hooks.add('before', event, handler) - return this - } - - /** - * Register after hooks - */ - public static $after (event: EventsList, handler: HooksHandler) { - this.hooks.add('after', event, handler) - return this - } - /** * Returns the model query instance for the given model */ @@ -184,11 +168,11 @@ export class BaseModel implements ModelContract { const instance = new this() instance.$consumeAdapterResult(adapterResult, sideloadAttributes) - instance.$hydrateOriginals() + instance.hydrateOriginals() instance.$setOptionsAndTrx(options) - instance.$isPersisted = true - instance.$isLocal = false + instance.isPersisted = true + instance.isLocal = false return instance } @@ -218,29 +202,6 @@ export class BaseModel implements ModelContract { }, []) as InstanceType[] } - /** - * Boot the model - */ - public static $boot () { - if (this.$booted) { - return - } - - this.$booted = true - this.$primaryKey = this.$primaryKey || 'id' - - Object.defineProperty(this, '$refs', { value: {} }) - Object.defineProperty(this, '$columns', { value: new Map() }) - Object.defineProperty(this, '$computed', { value: new Map() }) - Object.defineProperty(this, '$relations', { value: new Map() }) - - Object.defineProperty(this, 'hooks', { value: new Hooks(this.$container) }) - Object.defineProperty(this, 'mappings', { value: { cast: new Map() }}) - - this.$increments = this.$increments === undefined ? true : this.$increments - this.$table = this.$table === undefined ? this.$configurator.getTableName(this) : this.$table - } - /** * Define a new column on the model. This is required, so that * we differentiate between plain properties vs model attributes. @@ -263,7 +224,7 @@ export class BaseModel implements ModelContract { * Set column as the primary column, when `primary` is to true */ if (column.isPrimary) { - this.$primaryKey = name + this.primaryKey = name } this.$columns.set(name, column) @@ -370,6 +331,45 @@ export class BaseModel implements ModelContract { }, {}) } + /** + * Boot the model + */ + public static boot () { + if (this.booted) { + return + } + + this.booted = true + this.primaryKey = this.primaryKey || 'id' + + Object.defineProperty(this, '$refs', { value: {} }) + Object.defineProperty(this, '$columns', { value: new Map() }) + Object.defineProperty(this, '$computed', { value: new Map() }) + Object.defineProperty(this, '$relations', { value: new Map() }) + + Object.defineProperty(this, 'hooks', { value: new Hooks(this.$container) }) + Object.defineProperty(this, 'mappings', { value: { cast: new Map() }}) + + this.increments = this.increments === undefined ? true : this.increments + this.table = this.table === undefined ? this.$configurator.getTableName(this) : this.table + } + + /** + * Register before hooks + */ + public static before (event: EventsList, handler: HooksHandler) { + this.hooks.add('before', event, handler) + return this + } + + /** + * Register after hooks + */ + public static after (event: EventsList, handler: HooksHandler) { + this.hooks.add('after', event, handler) + return this + } + /** * Returns a fresh persisted instance of model by applying * attributes to the model instance @@ -404,8 +404,8 @@ export class BaseModel implements ModelContract { const instance = new this() as InstanceType instance.fill(row) - instance.$trx = trx - instance.$options = options + instance.trx = trx + instance.options = options await instance.save() collection.push(instance) @@ -428,7 +428,7 @@ export class BaseModel implements ModelContract { value: any, options?: ModelAdapterOptions, ) { - return this.query(options).where(this.$resolveCastKey(this.$primaryKey), value).first() + return this.query(options).where(this.$resolveCastKey(this.primaryKey), value).first() } /** @@ -439,7 +439,7 @@ export class BaseModel implements ModelContract { value: any, options?: ModelAdapterOptions, ) { - return this.query(options).where(this.$resolveCastKey(this.$primaryKey), value).firstOrFail() + return this.query(options).where(this.$resolveCastKey(this.primaryKey), value).firstOrFail() } /** @@ -452,8 +452,8 @@ export class BaseModel implements ModelContract { ) { return this .query(options) - .whereIn(this.$resolveCastKey(this.$primaryKey), value) - .orderBy(this.$resolveCastKey(this.$primaryKey), 'desc') + .whereIn(this.$resolveCastKey(this.primaryKey), value) + .orderBy(this.$resolveCastKey(this.primaryKey), 'desc') .exec() } @@ -488,7 +488,7 @@ export class BaseModel implements ModelContract { options?: ModelAdapterOptions, ) { const row = await this.firstOrNew(search, savePayload, options) - if (!row.$isPersisted) { + if (!row.isPersisted) { await row.save() } @@ -509,7 +509,7 @@ export class BaseModel implements ModelContract { /** * Update if row was found */ - if (row.$isPersisted) { + if (row.isPersisted) { row.merge(updatedPayload) } @@ -595,9 +595,8 @@ export class BaseModel implements ModelContract { try { await Promise.all(rows.map((row) => { - row.$trx = trx - - if (!row.$isPersisted) { + row.trx = trx + if (!row.isPersisted) { return row.save() } return Promise.resolve() @@ -636,7 +635,7 @@ export class BaseModel implements ModelContract { try { await Promise.all(rows.map((row) => { - row.$trx = trx + row.trx = trx return row.save() })) await trx.commit() @@ -655,7 +654,7 @@ export class BaseModel implements ModelContract { this: T, options?: ModelAdapterOptions, ) { - return this.query(options).orderBy(this.$resolveCastKey(this.$primaryKey), 'desc').exec() + return this.query(options).orderBy(this.$resolveCastKey(this.primaryKey), 'desc').exec() } constructor () { @@ -679,7 +678,7 @@ export class BaseModel implements ModelContract { * cleansup the `$trx` reference */ private transactionListener = function listener () { - this.$trx = undefined + this.modelTrx = undefined }.bind(this) /** @@ -698,7 +697,7 @@ export class BaseModel implements ModelContract { * Raises exception when mutations are performed on a delete model */ private ensureIsntDeleted () { - if (this.$isDeleted) { + if (this.isDeleted) { throw new Exception('Cannot mutate delete model instance', 500, 'E_MODEL_DELETED') } } @@ -708,7 +707,7 @@ export class BaseModel implements ModelContract { * to create the object with the property names to be * used by the adapter. */ - protected $prepareForAdapter (attributes: ModelObject) { + protected prepareForAdapter (attributes: ModelObject) { return (this.constructor as typeof BaseModel).$mapKeysToCastKeys(attributes) } @@ -728,6 +727,15 @@ export class BaseModel implements ModelContract { */ public $preloaded: { [relation: string]: ModelContract | ModelContract[] } = {} + /** + * Extras are dynamic properties set on the model instance, which + * are not serialized and neither casted for adapter calls. + * + * This is helpful when adapter wants to load some extra data conditionally + * and that data must not be persisted back the adapter. + */ + public $extras: ModelObject = {} + /** * Sideloaded are dynamic properties set on the model instance, which * are not serialized and neither casted for adapter calls. @@ -742,68 +750,59 @@ export class BaseModel implements ModelContract { * - Sideloaded are shared across multiple model instances created via `$createMultipleFromAdapterResult`. * - Sideloaded are passed to the relationships as well. */ - public $sideloaded: ModelObject = {} - - /** - * Extras are dynamic properties set on the model instance, which - * are not serialized and neither casted for adapter calls. - * - * This is helpful when adapter wants to load some extra data conditionally - * and that data must not be persisted back the adapter. - */ - public $extras: ModelObject = {} + public sideloaded: ModelObject = {} /** * Persisted means the model has been persisted with the adapter. This will * also be true, when model instance is created as a result of fetch * call from the adapter. */ - public $isPersisted: boolean = false + public isPersisted: boolean = false /** * Once deleted the model instance cannot make calls to the adapter */ - public $isDeleted: boolean = false + public isDeleted: boolean = false /** * `$isLocal` tells if the model instance was created locally vs * one generated as a result of fetch call from the adapter. */ - public $isLocal: boolean = true + public isLocal: boolean = true /** * Returns the value of primary key. The value must be * set inside attributes object */ - public get $primaryKeyValue (): any | undefined { + public get primaryKeyValue (): any | undefined { const model = this.constructor as typeof BaseModel - const column = model.$getColumn(model.$primaryKey) + const column = model.$getColumn(model.primaryKey) if (column && column.hasGetter) { - return this[model.$primaryKey] + return this[model.primaryKey] } - return this.$getAttribute(model.$primaryKey) + return this.$getAttribute(model.primaryKey) } /** - * Opposite of [[this.$isPersisted]] + * Opposite of [[this.isPersisted]] */ - public get $isNew (): boolean { - return !this.$isPersisted + public get isNew (): boolean { + return !this.isPersisted } /** * Returns dirty properties of a model by doing a diff * between original values and current attributes */ - public get $dirty (): any { + public get dirty (): any { const processedKeys: string[] = [] /** * Do not compute diff, when model has never been persisted */ - if (!this.$isPersisted) { + if (!this.isPersisted) { return this.$attributes } @@ -840,21 +839,21 @@ export class BaseModel implements ModelContract { /** * Finding if model is dirty with changes or not */ - public get $isDirty () { - return Object.keys(this.$dirty).length > 0 + public get isDirty () { + return Object.keys(this.dirty).length > 0 } /** * Returns the transaction */ - public get $trx (): TransactionClientContract | undefined { + public get trx (): TransactionClientContract | undefined { return this.modelTrx } /** * Set the trx to be used by the model to executing queries */ - public set $trx (trx: TransactionClientContract | undefined) { + public set trx (trx: TransactionClientContract | undefined) { if (!trx) { this.modelTrx = undefined return @@ -863,9 +862,9 @@ export class BaseModel implements ModelContract { /** * Remove old listeners */ - if (this.$trx) { - this.$trx.removeListener('commit', this.transactionListener) - this.$trx.removeListener('rollback', this.transactionListener) + if (this.modelTrx) { + this.modelTrx.removeListener('commit', this.transactionListener) + this.modelTrx.removeListener('rollback', this.transactionListener) } /** @@ -879,14 +878,14 @@ export class BaseModel implements ModelContract { /** * Get options */ - public get $options (): ModelOptions | undefined { + public get options (): ModelOptions | undefined { return this.modelOptions } /** * Set options */ - public set $options (options: ModelOptions | undefined) { + public set options (options: ModelOptions | undefined) { if (!options) { return } @@ -910,9 +909,9 @@ export class BaseModel implements ModelContract { } if (options.client && options.client.isTransaction) { - this.$trx = options.client as TransactionClientContract + this.trx = options.client as TransactionClientContract } - this.$options = options + this.options = options } /** @@ -1000,10 +999,10 @@ export class BaseModel implements ModelContract { /** * Reset array before invoking $pushRelated */ - if (MANY_RELATIONS.includes(relation.$type)) { + if (MANY_RELATIONS.includes(relation.type)) { if (!Array.isArray(models)) { throw new Exception( - `"${Model.name}.${key}" must be an array when setting "${relation.$type}" relationship`, + `"${Model.name}.${key}" must be an array when setting "${relation.type}" relationship`, ) } this.$preloaded[key] = [] @@ -1029,7 +1028,7 @@ export class BaseModel implements ModelContract { /** * Create multiple for `hasMany` `manyToMany` and `hasManyThrough` */ - if (MANY_RELATIONS.includes(relation.$type)) { + if (MANY_RELATIONS.includes(relation.type)) { this.$preloaded[key] = ((this.$preloaded[key] || []) as ModelContract[]).concat(models) return } @@ -1039,7 +1038,7 @@ export class BaseModel implements ModelContract { */ if (Array.isArray(models)) { throw new Error( - `"${Model.name}.${key}" cannot reference more than one instance of "${relation.$relatedModel().name}" model` + `"${Model.name}.${key}" cannot reference more than one instance of "${relation.relatedModel().name}" model` ) } @@ -1058,7 +1057,7 @@ export class BaseModel implements ModelContract { * on the model instance */ if (sideloadedAttributes) { - this.$sideloaded = Object.assign({}, this.$sideloaded, sideloadedAttributes) + this.sideloaded = Object.assign({}, this.sideloaded, sideloadedAttributes) } /** @@ -1099,7 +1098,7 @@ export class BaseModel implements ModelContract { * Sync originals with the attributes. After this `isDirty` will * return false */ - public $hydrateOriginals () { + public hydrateOriginals () { this.$original = Object.assign({}, this.$attributes) } @@ -1151,8 +1150,8 @@ export class BaseModel implements ModelContract { } await preloader - .sideload(this.$sideloaded) - .processAllForOne(this, constructor.$adapter.modelClient(this)) + .sideload(this.sideloaded) + .$processAllForOne(this, constructor.$adapter.modelClient(this)) } /** @@ -1165,21 +1164,21 @@ export class BaseModel implements ModelContract { /** * Persit the model when it's not persisted already */ - if (!this.$isPersisted) { + if (!this.isPersisted) { await Model.hooks.execute('before', 'create', this) await Model.hooks.execute('before', 'save', this) - await Model.$adapter.insert(this, this.$prepareForAdapter(this.$attributes)) + await Model.$adapter.insert(this, this.prepareForAdapter(this.$attributes)) - this.$hydrateOriginals() - this.$isPersisted = true + this.hydrateOriginals() + this.isPersisted = true await Model.hooks.execute('after', 'create', this) await Model.hooks.execute('after', 'save', this) return } - const dirty = this.$dirty + const dirty = this.dirty /** * Do not issue updates when model doesn't have any mutations @@ -1194,9 +1193,9 @@ export class BaseModel implements ModelContract { /** * Perform update */ - await Model.$adapter.update(this, this.$prepareForAdapter(dirty)) - this.$hydrateOriginals() - this.$isPersisted = true + await Model.$adapter.update(this, this.prepareForAdapter(dirty)) + this.hydrateOriginals() + this.isPersisted = true await Model.hooks.execute('after', 'update', this) await Model.hooks.execute('after', 'save', this) @@ -1212,7 +1211,7 @@ export class BaseModel implements ModelContract { await Model.hooks.execute('before', 'delete', this) await Model.$adapter.delete(this) - this.$isDeleted = true + this.isDeleted = true await Model.hooks.execute('after', 'delete', this) } @@ -1244,12 +1243,12 @@ export class BaseModel implements ModelContract { */ Object.keys(this.$preloaded).forEach((key) => { const relation = Model.$getRelation(key as any)! as RelationshipsContract - if (!relation.$serializeAs) { + if (!relation.serializeAs) { return } const value = this.$preloaded[key] - results[relation.$serializeAs] = Array.isArray(value) + results[relation.serializeAs] = Array.isArray(value) ? value.map((one) => one.toJSON()) : value.toJSON() }) @@ -1291,10 +1290,10 @@ export class BaseModel implements ModelContract { * Returning insert query for the inserts */ if (action === 'insert') { - const insertQuery = client.insertQuery().table(modelConstructor.$table) + const insertQuery = client.insertQuery().table(modelConstructor.table) - if (modelConstructor.$increments) { - insertQuery.returning(modelConstructor.$resolveCastKey(modelConstructor.$primaryKey)) + if (modelConstructor.increments) { + insertQuery.returning(modelConstructor.$resolveCastKey(modelConstructor.primaryKey)) } return insertQuery } @@ -1304,8 +1303,8 @@ export class BaseModel implements ModelContract { */ return client .query() - .from(modelConstructor.$table) - .where(modelConstructor.$resolveCastKey(modelConstructor.$primaryKey), this.$primaryKeyValue) + .from(modelConstructor.table) + .where(modelConstructor.$resolveCastKey(modelConstructor.primaryKey), this.primaryKeyValue) } /** @@ -1316,7 +1315,7 @@ export class BaseModel implements ModelContract { const relation = Model.$getRelation(relationName as string) ensureRelation(relationName, relation) - relation!.$boot() + relation!.boot() return relation!.client(this, Model.$adapter.modelClient(this)) } @@ -1326,13 +1325,13 @@ export class BaseModel implements ModelContract { public async refresh () { this.ensureIsntDeleted() const modelConstructor = this.constructor as typeof BaseModel - const { $table } = modelConstructor - const primaryAdapterKey = modelConstructor.$resolveCastKey(modelConstructor.$primaryKey) + const { table } = modelConstructor + const primaryAdapterKey = modelConstructor.$resolveCastKey(modelConstructor.primaryKey) /** * Noop when model instance is not persisted */ - if (!this.$isPersisted) { + if (!this.isPersisted) { return } @@ -1340,17 +1339,17 @@ export class BaseModel implements ModelContract { * This will occur, when some other part of the application removes * the row */ - const freshModelInstance = await modelConstructor.find(this.$primaryKeyValue) + const freshModelInstance = await modelConstructor.find(this.primaryKeyValue) if (!freshModelInstance) { throw new Exception( [ '"Model.refresh" failed. ', - `Unable to lookup "${$table}" table where "${primaryAdapterKey}" = ${this.$primaryKeyValue}`, + `Unable to lookup "${table}" table where "${primaryAdapterKey}" = ${this.primaryKeyValue}`, ].join(''), ) } this.fill(freshModelInstance.$attributes) - this.$hydrateOriginals() + this.hydrateOriginals() } } diff --git a/src/Orm/Config/index.ts b/src/Orm/Config/index.ts index 9a153c0c..b1db03ae 100644 --- a/src/Orm/Config/index.ts +++ b/src/Orm/Config/index.ts @@ -38,13 +38,6 @@ export const OrmConfig: OrmConfigContract = { return snakeCase(key) }, - /** - * Return a flag to turn on or off the serialization of a given column. - */ - serialize () { - return true - }, - /** * Returns the local key for a given relationship */ @@ -54,10 +47,10 @@ export const OrmConfig: OrmConfigContract = { related: ModelConstructorContract ): string { if (relation === 'belongsTo') { - return related.$primaryKey + return related.primaryKey } - return model.$primaryKey + return model.primaryKey }, /** @@ -69,17 +62,17 @@ export const OrmConfig: OrmConfigContract = { related: ModelConstructorContract ): string { if (relation === 'belongsTo') { - return camelCase(`${related.name}_${related.$primaryKey}`) + return camelCase(`${related.name}_${related.primaryKey}`) } - return camelCase(`${model.name}_${model.$primaryKey}`) + return camelCase(`${model.name}_${model.primaryKey}`) }, /** * Returns the pivot table name for manyToMany relationship */ getPivotTableName ( - _: TypedRelations['type'], + _: 'manyToMany', model: ModelConstructorContract, relatedModel: ModelConstructorContract, ): string { @@ -90,9 +83,9 @@ export const OrmConfig: OrmConfigContract = { * Returns the pivot foreign key for manyToMany relationship */ getPivotForeignKey ( - _: TypedRelations['type'], + _: 'manyToMany', model: ModelConstructorContract, ): string { - return snakeCase(`${model.name}_${model.$primaryKey}`) + return snakeCase(`${model.name}_${model.primaryKey}`) }, } diff --git a/src/Orm/Decorators/index.ts b/src/Orm/Decorators/index.ts index d17e975d..fb7f6ea9 100644 --- a/src/Orm/Decorators/index.ts +++ b/src/Orm/Decorators/index.ts @@ -31,7 +31,7 @@ import { export const column: ColumnDecorator = (options?) => { return function decorateAsColumn (target, property) { const Model = target.constructor as ModelConstructorContract - Model.$boot() + Model.boot() Model.$addColumn(property, options || {}) } } @@ -44,7 +44,7 @@ export const computed: ComputedDecorator = (options) => { return function decorateAsComputed (target, property) { const Model = target.constructor as ModelConstructorContract - Model.$boot() + Model.boot() Model.$addComputed(property, options || {}) } } @@ -55,7 +55,7 @@ export const computed: ComputedDecorator = (options) => { export const belongsTo: BelongsToDecorator = (relatedModel, relation?) => { return function decorateAsRelation (target, property: string) { const Model = target.constructor as ModelConstructorContract - Model.$boot() + Model.boot() Model.$addRelation(property, 'belongsTo', Object.assign({ relatedModel }, relation)) } } @@ -66,7 +66,7 @@ export const belongsTo: BelongsToDecorator = (relatedModel, relation?) => { export const hasOne: HasOneDecorator = (relatedModel, relation?) => { return function decorateAsRelation (target, property: string) { const Model = target.constructor as ModelConstructorContract - Model.$boot() + Model.boot() Model.$addRelation(property, 'hasOne', Object.assign({ relatedModel }, relation)) } } @@ -77,7 +77,7 @@ export const hasOne: HasOneDecorator = (relatedModel, relation?) => { export const hasMany: HasManyDecorator = (relatedModel, relation?) => { return function decorateAsRelation (target, property: string) { const Model = target.constructor as ModelConstructorContract - Model.$boot() + Model.boot() Model.$addRelation(property, 'hasMany', Object.assign({ relatedModel }, relation)) } } @@ -88,7 +88,7 @@ export const hasMany: HasManyDecorator = (relatedModel, relation?) => { export const manyToMany: ManyToManyDecorator = (relatedModel, relation?) => { return function decorateAsRelation (target, property: string) { const Model = target.constructor as ModelConstructorContract - Model.$boot() + Model.boot() Model.$addRelation(property, 'manyToMany', Object.assign({ relatedModel }, relation)) } } @@ -99,7 +99,7 @@ export const manyToMany: ManyToManyDecorator = (relatedModel, relation?) => { export const hasManyThrough: HasManyThroughDecorator = ([relatedModel, throughModel], relation) => { return function decorateAsRelation (target, property: string) { const Model = target.constructor as ModelConstructorContract - Model.$boot() + Model.boot() Model.$addRelation(property, 'hasManyThrough', Object.assign({ relatedModel, throughModel }, relation)) } } diff --git a/src/Orm/Hooks/index.ts b/src/Orm/Hooks/index.ts index a1e11526..84c971cb 100644 --- a/src/Orm/Hooks/index.ts +++ b/src/Orm/Hooks/index.ts @@ -38,7 +38,7 @@ export class Hooks { public add (lifecycle: 'before' | 'after', event: EventsList, handler: HooksHandler) { this.hooks[event] = this.hooks[event] || { before: new Set(), after: new Set() } - let resolvedHook + let resolvedHook: Exclude, 'string'> | IocResolverLookupNode /** * If hook is a string, then resolve it from the container diff --git a/src/Orm/Preloader/index.ts b/src/Orm/Preloader/index.ts index 404894c0..1fb261ac 100644 --- a/src/Orm/Preloader/index.ts +++ b/src/Orm/Preloader/index.ts @@ -53,12 +53,12 @@ export class Preloader implements PreloaderContract { callback(query) } - const result = await query.selectRelationKeys().exec() + const result = await query.$selectRelationKeys().exec() /** * hasOne and belongsTo will always return an array of a single row (if done right) */ - if (relation.$type === 'hasOne' || relation.$type === 'belongsTo') { + if (relation.type === 'hasOne' || relation.type === 'belongsTo') { relation.$setRelated(parent, result[0]) return } @@ -88,7 +88,7 @@ export class Preloader implements PreloaderContract { callback(query) } - const result = await query.selectRelationKeys().exec() + const result = await query.$selectRelationKeys().exec() /** * Set array of related instances @@ -100,7 +100,7 @@ export class Preloader implements PreloaderContract { * Define a relationship to preload */ public preload (name: any, callback?: any): this { - const relation = this.model.$getRelation(name) + const relation = this.model.$getRelation(name) as RelationshipsContract if (!relation) { throw new Exception( `"${name}" is not defined as a relationship on "${this.model.name}" model`, @@ -109,7 +109,7 @@ export class Preloader implements PreloaderContract { ) } - relation.$boot() + relation.boot() this.preloads[name] = { relation: relation, callback: callback, @@ -130,7 +130,7 @@ export class Preloader implements PreloaderContract { /** * Process of all the preloaded relationships for a single parent */ - public async processAllForOne (parent: ModelContract, client: QueryClientContract) { + public async $processAllForOne (parent: ModelContract, client: QueryClientContract) { await Promise.all(Object.keys(this.preloads).map((relationName) => { return this.processRelation(relationName, parent, client) })) @@ -139,7 +139,7 @@ export class Preloader implements PreloaderContract { /** * Process of all the preloaded relationships for many parents */ - public async processAllForMany (parent: ModelContract[], client: QueryClientContract) { + public async $processAllForMany (parent: ModelContract[], client: QueryClientContract) { await Promise.all(Object.keys(this.preloads).map((relationName) => { return this.processRelationForMany(relationName, parent, client) })) diff --git a/src/Orm/QueryBuilder/index.ts b/src/Orm/QueryBuilder/index.ts index 7256df99..371a0ae5 100644 --- a/src/Orm/QueryBuilder/index.ts +++ b/src/Orm/QueryBuilder/index.ts @@ -68,7 +68,7 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon }, ) { super(builder, customFn) - builder.table(model.$table) + builder.table(model.table) } /** @@ -105,13 +105,6 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon return this } - /** - * Returns the connection name used by the query client - */ - public get connection () { - return this.client!.connectionName - } - /** * Fetch and return first results from the results set. This method * will implicitly set a `limit` on the query @@ -238,7 +231,7 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon /** * Preload for model instances */ - await this.preloader.sideload(this.sideloaded).processAllForMany(modelInstances, this.client) + await this.preloader.sideload(this.sideloaded).$processAllForMany(modelInstances, this.client) return modelInstances } diff --git a/src/Orm/Relations/Base/QueryBuilder.ts b/src/Orm/Relations/Base/QueryBuilder.ts index a5bcf6dc..36d44035 100644 --- a/src/Orm/Relations/Base/QueryBuilder.ts +++ b/src/Orm/Relations/Base/QueryBuilder.ts @@ -22,22 +22,50 @@ export abstract class BaseQueryBuilder extends ModelQueryBuilder implements Rela ModelConstructorContract, ModelConstructorContract > { - protected $appliedConstraints: boolean = false - constructor ( builder: knex.QueryBuilder, client: QueryClientContract, - protected $relation: RelationshipsContract, + relation: RelationshipsContract, private isEager: boolean, dbCallback: DBQueryCallback, ) { - super(builder, $relation.$relatedModel(), client, dbCallback) + super(builder, relation.relatedModel(), client, dbCallback) } + /** + * Returns the profiler action. Protected, since the class is extended + * by relationships + */ + protected getProfilerAction () { + if (!this.client.profiler) { + return null + } + + return this.client.profiler.profile('sql:query', Object.assign(this['toSQL'](), { + connection: this.client.connectionName, + inTransaction: this.client.isTransaction, + model: this.model.name, + relation: this.profilerData(), + })) + } + + protected abstract profilerData (): any + + /** + * The relationship query builder must implement this method + * to apply relationship related constraints + */ + protected abstract applyConstraints (): void + + /** + * Each relationship query builder + */ + public abstract getRelationKeys (): string[] + /** * Returns the name of the query action */ - protected $queryAction (): string { + protected queryAction (): string { let action = this.knexQuery['_method'] if (action === 'del') { action = 'delete' @@ -50,14 +78,11 @@ ModelConstructorContract return action } - public abstract applyConstraints () - public abstract getRelationKeys (): string[] - /** * Selects the relation keys. Invoked by the preloader */ - public selectRelationKeys (): this { - const columns = this.knexQuery['_statements'].find((statement) => { + public $selectRelationKeys (): this { + const columns = this.knexQuery['_statements'].find((statement: any) => { return statement.grouping && statement.grouping === 'columns' }) @@ -78,34 +103,19 @@ ModelConstructorContract return this } - /** - * Adds neccessary where clause to the query to perform the select - */ - public async beforeExecute () { - this.applyConstraints() - } - /** * Get query sql */ public toSQL () { this.applyConstraints() - return super['toSQL']() + return super.toSQL() } /** - * Returns the profiler action + * Execute query */ - protected getProfilerAction () { - if (!this.client.profiler) { - return null - } - - return this.client.profiler.profile('sql:query', Object.assign(this['toSQL'](), { - connection: this.client.connectionName, - inTransaction: this.client.isTransaction, - model: this.model.name, - relation: this.$relation.$profilerData, - })) + public exec () { + this.applyConstraints() + return super.exec() } } diff --git a/src/Orm/Relations/Base/QueryClient.ts b/src/Orm/Relations/Base/QueryClient.ts deleted file mode 100644 index 1edc5b42..00000000 --- a/src/Orm/Relations/Base/QueryClient.ts +++ /dev/null @@ -1,89 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. -*/ - -import { QueryClientContract, TransactionClientContract } from '@ioc:Adonis/Lucid/Database' -import { RelationBaseQueryClientContract, RelationshipsContract } from '@ioc:Adonis/Lucid/Relations' -import { - ModelObject, - ModelConstructorContract, - ModelContract, - ModelAdapterOptions, -} from '@ioc:Adonis/Lucid/Model' - -/** - * Query client for executing queries in scope to the defined - * relationship - */ -export abstract class BaseQueryClient implements RelationBaseQueryClientContract< -ModelConstructorContract, -ModelConstructorContract -> { - constructor ( - protected $client: QueryClientContract, - protected $relation: RelationshipsContract, - ) { - } - - /** - * Client options to be used when persisting related - * models. - */ - protected $clientOptions: ModelAdapterOptions = { - client: this.$client, - connection: this.$client.connectionName, - profiler: this.$client.profiler, - } - - /** - * Perisist a model instance - */ - protected async $persist ( - related: ModelContract, - trx?: TransactionClientContract, - ) { - if (!trx) { - related.$setOptionsAndTrx(this.$clientOptions) - await related.save() - } - - related.$trx = trx - await related.save() - } - - /** - * Creates a persists a single model instance - */ - protected async $createAndPersist ( - values: ModelObject, - trx?: TransactionClientContract, - ): Promise { - if (!trx) { - return this.$relation.$relatedModel().create(values, this.$clientOptions) - } - return this.$relation.$relatedModel().create(values, { client: trx }) - } - - /** - * Creates a persists many of the model instances - */ - protected async $createAndPersistMany (values: ModelObject[]): Promise { - return this.$relation.$relatedModel().createMany(values, this.$clientOptions) - } - - /** - * Returns instance of query builder - */ - public abstract query (): any - - /** - * Returns instance of query builder with `eager=true` - */ - public abstract eagerQuery (): any -} - diff --git a/src/Orm/Relations/Base/index.ts b/src/Orm/Relations/Base/index.ts deleted file mode 100644 index 3028742d..00000000 --- a/src/Orm/Relations/Base/index.ts +++ /dev/null @@ -1,92 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. -*/ - -import { Exception } from '@poppinss/utils' -import { QueryClientContract } from '@ioc:Adonis/Lucid/Database' -import { ModelConstructorContract, ModelContract } from '@ioc:Adonis/Lucid/Model' -import { BaseRelationContract, RelationOptions, TypedRelations } from '@ioc:Adonis/Lucid/Relations' - -import { KeysExtractor } from '../KeysExtractor' - -/** - * Base class for implementing ORM Relationships - */ -export abstract class BaseRelation implements BaseRelationContract< -ModelConstructorContract, -ModelConstructorContract -> { - public $booted: boolean = false - public $serializeAs = this.$options.serializeAs || this.$relationName - public $relatedModel = this.$options.relatedModel - - public get $profilerData () { - return { - model: this.$model.name, - relatedModel: this.$relatedModel().name, - relation: this.$type, - } - } - - constructor ( - public $relationName: string, - protected $options: RelationOptions, - public $model: ModelConstructorContract, - ) { - this.ensureRelatedModel() - } - - /** - * Ensure that relationship model is defined as a function - */ - private ensureRelatedModel () { - if (typeof (this.$options.relatedModel) !== 'function') { - throw new Exception( - `Related model must be returned from a closure on "${this.$model.name}.${this.$relationName}" relation`, - 500, - 'E_MISSING_RELATED_MODEL', - ) - } - } - - /** - * Ensure relationship instance is booted - */ - protected $ensureIsBooted () { - if (!this.$booted) { - throw new Exception( - 'Relationship is not booted. Make sure to call $boot first', - 500, - 'E_RUNTIME_EXCEPTION', - ) - } - } - - /** - * Extract keys for the relationship to work - */ - protected $extractKeys< - Keys extends { [key: string]: { key: string, model: ModelConstructorContract } } - > ( - keys: Keys, - ): ReturnType['extract']> { - return new KeysExtractor(this.$model, this.$relationName, keys).extract() - } - - public abstract $type: TypedRelations['type'] - - /** - * Returns the query client for the relationship - */ - public abstract client ( - models: ModelContract | ModelContract[], - client: QueryClientContract, - ): any - - public abstract $boot () -} diff --git a/src/Orm/Relations/BelongsTo/QueryBuilder.ts b/src/Orm/Relations/BelongsTo/QueryBuilder.ts index 758add45..509c8aa0 100644 --- a/src/Orm/Relations/BelongsTo/QueryBuilder.ts +++ b/src/Orm/Relations/BelongsTo/QueryBuilder.ts @@ -24,38 +24,55 @@ export class BelongsToQueryBuilder extends BaseQueryBuilder implements RelationB ModelConstructorContract, ModelConstructorContract > { + private appliedConstraints: boolean = false + constructor ( builder: knex.QueryBuilder, client: QueryClientContract, private parent: ModelContract | ModelContract[], - protected $relation: BelongsTo, + private relation: BelongsTo, isEager: boolean = false, ) { - super(builder, client, $relation, isEager, (userFn) => { + super(builder, client, relation, isEager, (userFn) => { return (__builder) => { - userFn(new BelongsToQueryBuilder(__builder, this.client, this.parent, this.$relation)) + userFn(new BelongsToQueryBuilder(__builder, this.client, this.parent, this.relation)) } }) } + protected profilerData () { + return { + relation: this.relation.type, + model: this.relation.model.name, + relatedModel: this.relation.relatedModel().name, + } + } + + /** + * The keys for constructing the join query + */ + public getRelationKeys (): string[] { + return [this.relation.localKey] + } + /** * Applies constraint to limit rows to the current relationship * only. */ public applyConstraints () { - if (this.$appliedConstraints) { + if (this.appliedConstraints) { return } - this.$appliedConstraints = true - const queryAction = this.$queryAction() + this.appliedConstraints = true + const queryAction = this.queryAction() /** * Eager query contraints */ if (Array.isArray(this.parent)) { - this.knexQuery.whereIn(this.$relation.$localCastAsKey, unique(this.parent.map((model) => { - return getValue(model, this.$relation.$foreignKey, this.$relation, queryAction) + this.knexQuery.whereIn(this.relation.localCastAsKey, unique(this.parent.map((model) => { + return getValue(model, this.relation.foreignKey, this.relation, queryAction) }))) return } @@ -63,8 +80,8 @@ ModelConstructorContract /** * Query constraints */ - const value = getValue(this.parent, this.$relation.$foreignKey, this.$relation, queryAction) - this.knexQuery.where(this.$relation.$localCastAsKey, value) + const value = getValue(this.parent, this.relation.foreignKey, this.relation, queryAction) + this.knexQuery.where(this.relation.localCastAsKey, value) /** * Do not add limit when updating or deleting @@ -73,11 +90,4 @@ ModelConstructorContract this.knexQuery.limit(1) } } - - /** - * The keys for constructing the join query - */ - public getRelationKeys (): string[] { - return [this.$relation.$localKey] - } } diff --git a/src/Orm/Relations/BelongsTo/QueryClient.ts b/src/Orm/Relations/BelongsTo/QueryClient.ts index 2b73d5a5..20ca87a6 100644 --- a/src/Orm/Relations/BelongsTo/QueryClient.ts +++ b/src/Orm/Relations/BelongsTo/QueryClient.ts @@ -14,23 +14,22 @@ import { ModelConstructorContract, ModelContract } from '@ioc:Adonis/Lucid/Model import { BelongsTo } from './index' import { getValue } from '../../../utils' -import { BaseQueryClient } from '../Base/QueryClient' +// import { BaseQueryClient } from '../Base/QueryClient' import { BelongsToQueryBuilder } from './QueryBuilder' /** * Query client for executing queries in scope to the defined * relationship */ -export class BelongsToQueryClient extends BaseQueryClient implements BelongsToClientContract< +export class BelongsToQueryClient implements BelongsToClientContract< ModelConstructorContract, ModelConstructorContract > { constructor ( private parent: ModelContract | ModelContract[], - protected $client: QueryClientContract, - protected $relation: BelongsTo, + private client: QueryClientContract, + private relation: BelongsTo, ) { - super($client, $relation) } /** @@ -46,7 +45,7 @@ ModelConstructorContract * Returns value for the foreign key from the related model */ private getForeignKeyValue (related: ModelContract, action: string) { - return getValue(related, this.$relation.$localKey, this.$relation, action) + return getValue(related, this.relation.localKey, this.relation, action) } /** @@ -54,10 +53,10 @@ ModelConstructorContract */ public query (): any { return new BelongsToQueryBuilder( - this.$client.knexQuery(), - this.$client, + this.client.knexQuery(), + this.client, this.parent, - this.$relation, + this.relation, ) } @@ -66,10 +65,10 @@ ModelConstructorContract */ public eagerQuery (): any { return new BelongsToQueryBuilder( - this.$client.knexQuery(), - this.$client, + this.client.knexQuery(), + this.client, this.parent, - this.$relation, + this.relation, true, ) } @@ -81,7 +80,7 @@ ModelConstructorContract this.ensureSingleParent(this.parent) await related.save() - this.parent[this.$relation.$foreignKey] = this.getForeignKeyValue(related, 'associate') + this.parent[this.relation.foreignKey] = this.getForeignKeyValue(related, 'associate') await this.parent.save() } @@ -90,7 +89,7 @@ ModelConstructorContract */ public async dissociate () { this.ensureSingleParent(this.parent) - this.parent[this.$relation.$foreignKey] = null + this.parent[this.relation.foreignKey] = null await this.parent.save() } } diff --git a/src/Orm/Relations/BelongsTo/index.ts b/src/Orm/Relations/BelongsTo/index.ts index cd013f92..3b32d6de 100644 --- a/src/Orm/Relations/BelongsTo/index.ts +++ b/src/Orm/Relations/BelongsTo/index.ts @@ -11,81 +11,86 @@ import { QueryClientContract } from '@ioc:Adonis/Lucid/Database' import { ModelConstructorContract, ModelContract } from '@ioc:Adonis/Lucid/Model' import { BelongsToRelationContract, RelationOptions } from '@ioc:Adonis/Lucid/Relations' -import { BaseRelation } from '../Base' +import { KeysExtractor } from '../KeysExtractor' import { BelongsToQueryClient } from './QueryClient' +import { ensureRelationIsBooted } from '../../../utils' /** * Manages loading and persisting belongs to relationship */ -export class BelongsTo extends BaseRelation implements BelongsToRelationContract< +export class BelongsTo implements BelongsToRelationContract< ModelConstructorContract, ModelConstructorContract > { - public $type = 'belongsTo' as const + public type = 'belongsTo' as const + public booted: boolean = false + public relatedModel = this.options.relatedModel + public serializeAs = this.options.serializeAs || this.relationName /** * Available after boot is invoked */ - public $localKey: string - public $localCastAsKey: string - public $foreignKey: string - public $foreignCastAsKey: string + public localKey: string + public foreignKey: string + public localCastAsKey: string + public foreignCastAsKey: string constructor ( - relationName: string, - options: RelationOptions, - model: ModelConstructorContract, + public relationName: string, + private options: RelationOptions, + public model: ModelConstructorContract, ) { - super(relationName, options, model) } /** * Boot the relationship and ensure that all keys are in * place for queries to do their job. */ - public $boot () { - if (this.$booted) { + public boot () { + if (this.booted) { return } + const relatedModel = this.relatedModel() + /** * Extracting keys from the model and the relation model. The keys * extractor ensures all the required columns are defined on * the models for the relationship to work */ - const { localKey, foreignKey } = this.$extractKeys({ + const { localKey, foreignKey } = new KeysExtractor(this.model, this.relationName, { localKey: { - model: this.$relatedModel(), + model: relatedModel, key: ( - this.$options.localKey || - this.$model.$configurator.getLocalKey(this.$type, this.$model, this.$relatedModel()) + this.options.localKey || + this.model.$configurator.getLocalKey(this.type, this.model, relatedModel) ), }, foreignKey: { - model: this.$model, + model: this.model, key: ( - this.$options.foreignKey || - this.$model.$configurator.getForeignKey(this.$type, this.$model, this.$relatedModel()) + this.options.foreignKey || + this.model.$configurator.getForeignKey(this.type, this.model, relatedModel) ), }, - }) + }).extract() /** * Keys on the related model */ - this.$localKey = localKey.attributeName - this.$localCastAsKey = localKey.castAsKey + this.localKey = localKey.attributeName + this.localCastAsKey = localKey.castAsKey /** * Keys on the parent model */ - this.$foreignKey = foreignKey.attributeName - this.$foreignCastAsKey = foreignKey.castAsKey + this.foreignKey = foreignKey.attributeName + this.foreignCastAsKey = foreignKey.castAsKey /** * Booted successfully */ - this.$booted = true + this.booted = true } /** @@ -95,12 +100,12 @@ ModelConstructorContract parent: ModelContract, related: ModelContract | null ): void { - this.$ensureIsBooted() + ensureRelationIsBooted(this) if (!related) { return } - parent.$setRelated(this.$relationName as any, related) + parent.$setRelated(this.relationName as any, related) } /** @@ -110,12 +115,12 @@ ModelConstructorContract parent: ModelContract, related: ModelContract | null ): void { - this.$ensureIsBooted() + ensureRelationIsBooted(this) if (!related) { return } - parent.$setRelated(this.$relationName as any, related) + parent.$setRelated(this.relationName as any, related) } /** @@ -123,12 +128,12 @@ ModelConstructorContract * models. */ public $setRelatedForMany (parent: ModelContract[], related: ModelContract[]): void { - this.$ensureIsBooted() + ensureRelationIsBooted(this) parent.forEach((parentModel) => { const match = related.find((relatedModel) => { - const value = relatedModel[this.$localKey] - return value !== undefined && parentModel[this.$foreignKey] === value + const value = relatedModel[this.localKey] + return value !== undefined && parentModel[this.foreignKey] === value }) this.$setRelated(parentModel, match || null) }) @@ -138,7 +143,7 @@ ModelConstructorContract * Returns an instance of query client for the given relationship */ public client (parent: ModelContract | ModelContract[], client: QueryClientContract): any { - this.$ensureIsBooted() + ensureRelationIsBooted(this) return new BelongsToQueryClient(parent, client, this) } } diff --git a/src/Orm/Relations/HasMany/QueryBuilder.ts b/src/Orm/Relations/HasMany/QueryBuilder.ts index e3509b98..ff4f9752 100644 --- a/src/Orm/Relations/HasMany/QueryBuilder.ts +++ b/src/Orm/Relations/HasMany/QueryBuilder.ts @@ -24,38 +24,48 @@ export class HasManyQueryBuilder extends BaseQueryBuilder implements RelationBas ModelConstructorContract, ModelConstructorContract > { + private appliedConstraints: boolean = false + constructor ( builder: knex.QueryBuilder, client: QueryClientContract, private parent: ModelContract | ModelContract[], - protected $relation: HasMany, + private relation: HasMany, isEager: boolean = false, ) { - super(builder, client, $relation, isEager, (userFn) => { + super(builder, client, relation, isEager, (userFn) => { return (__builder) => { - userFn(new HasManyQueryBuilder(__builder, this.client, this.parent, this.$relation)) + userFn(new HasManyQueryBuilder(__builder, this.client, this.parent, this.relation)) } }) } + protected profilerData () { + return { + relation: this.relation.type, + model: this.relation.model.name, + relatedModel: this.relation.relatedModel().name, + } + } + /** * Applies constraint to limit rows to the current relationship * only. */ public applyConstraints () { - if (this.$appliedConstraints) { + if (this.appliedConstraints) { return } - const queryAction = this.$queryAction() - this.$appliedConstraints = true + const queryAction = this.queryAction() + this.appliedConstraints = true /** * Eager query contraints */ if (Array.isArray(this.parent)) { - this.knexQuery.whereIn(this.$relation.$foreignCastAsKey, unique(this.parent.map((model) => { - return getValue(model, this.$relation.$localKey, this.$relation, queryAction) + this.knexQuery.whereIn(this.relation.foreignCastAsKey, unique(this.parent.map((model) => { + return getValue(model, this.relation.localKey, this.relation, queryAction) }))) return } @@ -63,14 +73,14 @@ ModelConstructorContract /** * Query constraints */ - const value = getValue(this.parent, this.$relation.$localKey, this.$relation, queryAction) - this.knexQuery.where(this.$relation.$foreignCastAsKey, value) + const value = getValue(this.parent, this.relation.localKey, this.relation, queryAction) + this.knexQuery.where(this.relation.foreignCastAsKey, value) } /** * The keys for constructing the join query */ public getRelationKeys (): string[] { - return [this.$relation.$foreignCastAsKey] + return [this.relation.foreignCastAsKey] } } diff --git a/src/Orm/Relations/HasMany/QueryClient.ts b/src/Orm/Relations/HasMany/QueryClient.ts index d4b1f89c..d9c1b939 100644 --- a/src/Orm/Relations/HasMany/QueryClient.ts +++ b/src/Orm/Relations/HasMany/QueryClient.ts @@ -18,23 +18,22 @@ import { HasManyClientContract } from '@ioc:Adonis/Lucid/Relations' import { HasMany } from './index' import { getValue } from '../../../utils' -import { BaseQueryClient } from '../Base/QueryClient' +// import { BaseQueryClient } from '../Base/QueryClient' import { HasManyQueryBuilder } from './QueryBuilder' /** * Query client for executing queries in scope to the defined * relationship */ -export class HasManyQueryClient extends BaseQueryClient implements HasManyClientContract< +export class HasManyQueryClient implements HasManyClientContract< ModelConstructorContract, ModelConstructorContract > { constructor ( private parent: ModelContract | ModelContract[], - protected $client: QueryClientContract, - protected $relation: HasMany, + private client: QueryClientContract, + private relation: HasMany, ) { - super($client, $relation) } /** @@ -50,7 +49,7 @@ ModelConstructorContract * Returns value for the foreign key */ private getForeignKeyValue (parent: ModelContract, action: string) { - return getValue(parent, this.$relation.$localKey, this.$relation, action) + return getValue(parent, this.relation.localKey, this.relation, action) } /** @@ -58,10 +57,10 @@ ModelConstructorContract */ public query (): any { return new HasManyQueryBuilder( - this.$client.knexQuery(), - this.$client, + this.client.knexQuery(), + this.client, this.parent, - this.$relation, + this.relation, ) } @@ -70,10 +69,10 @@ ModelConstructorContract */ public eagerQuery (): any { return new HasManyQueryBuilder( - this.$client.knexQuery(), - this.$client, + this.client.knexQuery(), + this.client, this.parent, - this.$relation, + this.relation, true, ) } @@ -85,7 +84,7 @@ ModelConstructorContract this.ensureSingleParent(this.parent) await this.parent.save() - related[this.$relation.$foreignKey] = this.getForeignKeyValue(this.parent, 'save') + related[this.relation.foreignKey] = this.getForeignKeyValue(this.parent, 'save') await related.save() } @@ -97,7 +96,7 @@ ModelConstructorContract await this.parent.save() const foreignKeyValue = this.getForeignKeyValue(this.parent, 'saveMany') - const trx = await this.$client.transaction() + const trx = await this.client.transaction() try { /** @@ -105,8 +104,8 @@ ModelConstructorContract * inside a transaction */ await Promise.all(related.map((row) => { - row[this.$relation.$foreignKey] = foreignKeyValue - row.$trx = trx + row[this.relation.foreignKey] = foreignKeyValue + row.trx = trx return row.save() })) @@ -124,9 +123,13 @@ ModelConstructorContract this.ensureSingleParent(this.parent) await this.parent.save() - return this.$relation.$relatedModel().create(Object.assign({ - [this.$relation.$foreignKey]: this.getForeignKeyValue(this.parent, 'create'), - }, values), this.$clientOptions) + return this.relation.relatedModel().create(Object.assign({ + [this.relation.foreignKey]: this.getForeignKeyValue(this.parent, 'create'), + }, values), { + client: this.client, + connection: this.client.connectionName, + profiler: this.client.profiler, + }) } /** @@ -137,9 +140,13 @@ ModelConstructorContract await this.parent.save() const foreignKeyValue = this.getForeignKeyValue(this.parent, 'saveMany') - return this.$relation.$relatedModel().createMany(values.map((value) => { - return Object.assign({ [this.$relation.$foreignKey]: foreignKeyValue }, value) - }), this.$clientOptions) + return this.relation.relatedModel().createMany(values.map((value) => { + return Object.assign({ [this.relation.foreignKey]: foreignKeyValue }, value) + }), { + client: this.client, + connection: this.client.connectionName, + profiler: this.client.profiler, + }) } /** @@ -152,9 +159,13 @@ ModelConstructorContract this.ensureSingleParent(this.parent) await this.parent.save() - return this.$relation.$relatedModel().firstOrCreate(Object.assign({ - [this.$relation.$foreignKey]: this.getForeignKeyValue(this.parent, 'firstOrCreate'), - }, search), savePayload, this.$clientOptions) + return this.relation.relatedModel().firstOrCreate(Object.assign({ + [this.relation.foreignKey]: this.getForeignKeyValue(this.parent, 'firstOrCreate'), + }, search), savePayload, { + client: this.client, + connection: this.client.connectionName, + profiler: this.client.profiler, + }) } /** @@ -167,8 +178,12 @@ ModelConstructorContract this.ensureSingleParent(this.parent) await this.parent.save() - return this.$relation.$relatedModel().updateOrCreate(Object.assign({ - [this.$relation.$foreignKey]: this.getForeignKeyValue(this.parent, 'updateOrCreate'), - }, search), updatePayload, this.$clientOptions) + return this.relation.relatedModel().updateOrCreate(Object.assign({ + [this.relation.foreignKey]: this.getForeignKeyValue(this.parent, 'updateOrCreate'), + }, search), updatePayload, { + client: this.client, + connection: this.client.connectionName, + profiler: this.client.profiler, + }) } } diff --git a/src/Orm/Relations/HasMany/index.ts b/src/Orm/Relations/HasMany/index.ts index 8f55dca1..cb43b40f 100644 --- a/src/Orm/Relations/HasMany/index.ts +++ b/src/Orm/Relations/HasMany/index.ts @@ -11,97 +11,103 @@ import { QueryClientContract } from '@ioc:Adonis/Lucid/Database' import { ModelConstructorContract, ModelContract } from '@ioc:Adonis/Lucid/Model' import { HasManyRelationContract, RelationOptions } from '@ioc:Adonis/Lucid/Relations' -import { BaseRelation } from '../Base' +// import { BaseRelation } from '../Base' import { HasManyQueryClient } from './QueryClient' +import { KeysExtractor } from '../KeysExtractor' +import { ensureRelationIsBooted } from '../../../utils' /** * Manages loading and persisting has many relationship */ -export class HasMany extends BaseRelation implements HasManyRelationContract< +export class HasMany implements HasManyRelationContract< ModelConstructorContract, ModelConstructorContract > { - public $type = 'hasMany' as const + public type = 'hasMany' as const + public booted: boolean = false + public relatedModel = this.options.relatedModel + public serializeAs = this.options.serializeAs || this.relationName /** * Available after boot is invoked */ - public $localKey: string - public $localCastAsKey: string - public $foreignKey: string - public $foreignCastAsKey: string + public localKey: string + public localCastAsKey: string + public foreignKey: string + public foreignCastAsKey: string constructor ( - relationName: string, - options: RelationOptions, - model: ModelConstructorContract, + public relationName: string, + private options: RelationOptions, + public model: ModelConstructorContract, ) { - super(relationName, options, model) } /** * Boot the relationship and ensure that all keys are in * place for queries to do their job. */ - public $boot () { - if (this.$booted) { + public boot () { + if (this.booted) { return } + const relatedModel = this.relatedModel() + /** * Extracting keys from the model and the relation model. The keys * extractor ensures all the required columns are defined on * the models for the relationship to work */ - const { localKey, foreignKey } = this.$extractKeys({ + const { localKey, foreignKey } = new KeysExtractor(this.model, this.relationName, { localKey: { - model: this.$model, + model: this.model, key: ( - this.$options.localKey || - this.$model.$configurator.getLocalKey(this.$type, this.$model, this.$relatedModel()) + this.options.localKey || + this.model.$configurator.getLocalKey(this.type, this.model, relatedModel) ), }, foreignKey: { - model: this.$relatedModel(), + model: relatedModel, key: ( - this.$options.foreignKey || - this.$model.$configurator.getForeignKey(this.$type, this.$model, this.$relatedModel()) + this.options.foreignKey || + this.model.$configurator.getForeignKey(this.type, this.model, relatedModel) ), }, - }) + }).extract() /** * Keys on the parent model */ - this.$localKey = localKey.attributeName - this.$localCastAsKey = localKey.castAsKey + this.localKey = localKey.attributeName + this.localCastAsKey = localKey.castAsKey /** * Keys on the related model */ - this.$foreignKey = foreignKey.attributeName - this.$foreignCastAsKey = foreignKey.castAsKey + this.foreignKey = foreignKey.attributeName + this.foreignCastAsKey = foreignKey.castAsKey /** * Booted successfully */ - this.$booted = true + this.booted = true } /** * Set related model instances */ public $setRelated (parent: ModelContract, related: ModelContract[]): void { - this.$ensureIsBooted() - parent.$setRelated(this.$relationName as any, related) + ensureRelationIsBooted(this) + parent.$setRelated(this.relationName as any, related) } /** * Push related model instance(s) */ public $pushRelated (parent: ModelContract, related: ModelContract | ModelContract[]): void { - this.$ensureIsBooted() - parent.$pushRelated(this.$relationName as any, related as any) + ensureRelationIsBooted(this) + parent.$pushRelated(this.relationName as any, related as any) } /** @@ -109,13 +115,13 @@ ModelConstructorContract * models. */ public $setRelatedForMany (parent: ModelContract[], related: ModelContract[]): void { - this.$ensureIsBooted() + ensureRelationIsBooted(this) parent.forEach((parentModel) => { - const value = parentModel[this.$localKey] + const value = parentModel[this.localKey] this.$setRelated( parentModel, related.filter((relatedModel) => { - return value !== undefined && relatedModel[this.$foreignKey] === value + return value !== undefined && relatedModel[this.foreignKey] === value }), ) }) @@ -125,7 +131,7 @@ ModelConstructorContract * Returns an instance of query client for invoking queries */ public client (parent: ModelContract | ModelContract[], client: QueryClientContract): any { - this.$ensureIsBooted() + ensureRelationIsBooted(this) return new HasManyQueryClient(parent, client, this) } } diff --git a/src/Orm/Relations/HasManyThrough/QueryBuilder.ts b/src/Orm/Relations/HasManyThrough/QueryBuilder.ts index c22a6ce9..560bf5db 100644 --- a/src/Orm/Relations/HasManyThrough/QueryBuilder.ts +++ b/src/Orm/Relations/HasManyThrough/QueryBuilder.ts @@ -25,36 +25,46 @@ ModelConstructorContract, ModelConstructorContract > { private cherryPickingKeys: boolean = false + private appliedConstraints: boolean = false constructor ( builder: knex.QueryBuilder, client: QueryClientContract, private parent: ModelContract | ModelContract[], - protected $relation: HasManyThrough, + private relation: HasManyThrough, isEager: boolean = false, ) { - super(builder, client, $relation, isEager, (userFn) => { + super(builder, client, relation, isEager, (userFn) => { return (__builder) => { - userFn(new HasManyThroughQueryBuilder(__builder, this.client, this.parent, this.$relation)) + userFn(new HasManyThroughQueryBuilder(__builder, this.client, this.parent, this.relation)) } }) } + protected profilerData () { + return { + relation: this.relation.type, + model: this.relation.model.name, + throughModel: this.relation.throughModel().name, + relatedModel: this.relation.relatedModel().name, + } + } + /** * Adds where constraint to the pivot table */ private addWhereConstraints (builder: HasManyThroughQueryBuilder) { - const queryAction = this.$queryAction() - const throughTable = this.$relation.$throughModel().$table + const queryAction = this.queryAction() + const throughTable = this.relation.throughModel().table /** * Eager query contraints */ if (Array.isArray(this.parent)) { builder.whereIn( - `${throughTable}.${this.$relation.$foreignCastAsKey}`, + `${throughTable}.${this.relation.foreignCastAsKey}`, unique(this.parent.map((model) => { - return getValue(model, this.$relation.$localKey, this.$relation, queryAction) + return getValue(model, this.relation.localKey, this.relation, queryAction) })), ) return @@ -63,8 +73,8 @@ ModelConstructorContract /** * Query constraints */ - const value = getValue(this.parent, this.$relation.$localKey, this.$relation, queryAction) - builder.where(`${throughTable}.${this.$relation.$foreignCastAsKey}`, value) + const value = getValue(this.parent, this.relation.localKey, this.relation, queryAction) + builder.where(`${throughTable}.${this.relation.foreignCastAsKey}`, value) } /** @@ -72,7 +82,7 @@ ModelConstructorContract * table name */ private transformRelatedTableColumns (columns: any[]) { - const relatedTable = this.$relation.$relatedModel().$table + const relatedTable = this.relation.relatedModel().table return columns.map((column) => { if (typeof (column) === 'string') { @@ -108,17 +118,17 @@ ModelConstructorContract * only. */ public applyConstraints () { - if (this.$appliedConstraints) { + if (this.appliedConstraints) { return } - this.$appliedConstraints = true + this.appliedConstraints = true - const throughTable = this.$relation.$throughModel().$table - const relatedTable = this.$relation.$relatedModel().$table + const throughTable = this.relation.throughModel().table + const relatedTable = this.relation.relatedModel().table - if (['delete', 'update'].includes(this.$queryAction())) { - this.whereIn(`${relatedTable}.${this.$relation.$throughForeignCastAsKey}`, (subQuery) => { + if (['delete', 'update'].includes(this.queryAction())) { + this.whereIn(`${relatedTable}.${this.relation.throughForeignCastAsKey}`, (subQuery) => { subQuery.from(throughTable) this.addWhereConstraints(subQuery) }) @@ -138,7 +148,7 @@ ModelConstructorContract * through table. */ this.knexQuery.select( - `${throughTable}.${this.$relation.$foreignCastAsKey} as ${this.$relation.throughAlias(this.$relation.$foreignCastAsKey)}`, + `${throughTable}.${this.relation.foreignCastAsKey} as ${this.relation.throughAlias(this.relation.foreignCastAsKey)}`, ) /** @@ -146,8 +156,8 @@ ModelConstructorContract */ this.innerJoin( throughTable, - `${throughTable}.${this.$relation.$throughLocalCastAsKey}`, - `${relatedTable}.${this.$relation.$throughForeignCastAsKey}`, + `${throughTable}.${this.relation.throughLocalCastAsKey}`, + `${relatedTable}.${this.relation.throughForeignCastAsKey}`, ) /** @@ -160,6 +170,6 @@ ModelConstructorContract * The keys for constructing the join query */ public getRelationKeys (): string[] { - return [this.$relation.$throughForeignCastAsKey] + return [this.relation.throughForeignCastAsKey] } } diff --git a/src/Orm/Relations/HasManyThrough/index.ts b/src/Orm/Relations/HasManyThrough/index.ts index 187d897a..467a1652 100644 --- a/src/Orm/Relations/HasManyThrough/index.ts +++ b/src/Orm/Relations/HasManyThrough/index.ts @@ -11,65 +11,70 @@ import { QueryClientContract } from '@ioc:Adonis/Lucid/Database' import { ModelConstructorContract, ModelContract } from '@ioc:Adonis/Lucid/Model' import { HasManyThroughRelationContract, ThroughRelationOptions } from '@ioc:Adonis/Lucid/Relations' -import { BaseRelation } from '../Base' +// import { BaseRelation } from '../Base' import { HasManyThroughClient } from './QueryClient' +import { KeysExtractor } from '../KeysExtractor' +import { ensureRelationIsBooted } from '../../../utils' /** * Manages loading and persisting has many through relationship */ -export class HasManyThrough extends BaseRelation implements HasManyThroughRelationContract< +export class HasManyThrough implements HasManyThroughRelationContract< ModelConstructorContract, ModelConstructorContract > { - public $type = 'hasManyThrough' as const + public type = 'hasManyThrough' as const + public booted: boolean = false + public serializeAs = this.options.serializeAs || this.relationName - public $throughModel = this.throughOptions.throughModel + public relatedModel = this.options.relatedModel + public throughModel = this.options.throughModel /** * Available after boot is invoked */ - public $localKey: string - public $localCastAsKey: string + public localKey: string + public localCastAsKey: string /** * This exists on the through model */ - public $foreignKey: string - public $foreignCastAsKey: string + public foreignKey: string + public foreignCastAsKey: string /** * This exists on the through model */ - public $throughLocalKey: string - public $throughLocalCastAsKey: string + public throughLocalKey: string + public throughLocalCastAsKey: string /** * This exists on the related model */ - public $throughForeignKey: string - public $throughForeignCastAsKey: string - - public get $profilerData () { - return { - model: this.$model.name, - relatedModel: this.$relatedModel().name, - throughModel: this.$throughModel().name, - relation: this.$type, - } - } + public throughForeignKey: string + public throughForeignCastAsKey: string + + // public get $profilerData () { + // return { + // model: this.model.name, + // relatedModel: this.relatedModel().name, + // throughModel: this.throughModel().name, + // relation: this.type, + // } + // } constructor ( - relationName: string, - private throughOptions: ThroughRelationOptions, - model: ModelConstructorContract, + public relationName: string, + private options: ThroughRelationOptions, + public model: ModelConstructorContract, ) { - super(relationName, throughOptions, model) + // super(relationName, throughOptions, model) } /** * Returns the alias for the through key */ - public throughAlias (key) { + public throughAlias (key: string): string { return `through_${key}` } @@ -77,8 +82,8 @@ ModelConstructorContract * Boot the relationship and ensure that all keys are in * place for queries to do their job. */ - public $boot () { - if (this.$booted) { + public boot () { + if (this.booted) { return } @@ -87,75 +92,79 @@ ModelConstructorContract * extractor ensures all the required columns are defined on * the models for the relationship to work */ - const { localKey, foreignKey, throughLocalKey, throughForeignKey } = this.$extractKeys({ - localKey: { - model: this.$model, - key: ( - this.throughOptions.localKey || - this.$model.$configurator.getLocalKey(this.$type, this.$model, this.$relatedModel()) - ), - }, - foreignKey: { - model: this.$throughModel(), - key: ( - this.throughOptions.foreignKey || - this.$model.$configurator.getForeignKey(this.$type, this.$model, this.$throughModel()) - ), - }, - throughLocalKey: { - model: this.$throughModel(), - key: ( - this.throughOptions.throughLocalKey || - this.$model.$configurator.getLocalKey(this.$type, this.$throughModel(), this.$relatedModel()) - ), - }, - throughForeignKey: { - model: this.$relatedModel(), - key: ( - this.throughOptions.throughForeignKey || - this.$model.$configurator.getForeignKey(this.$type, this.$throughModel(), this.$relatedModel()) - ), - }, - }) + const { localKey, foreignKey, throughLocalKey, throughForeignKey } = new KeysExtractor( + this.model, + this.relationName, + { + localKey: { + model: this.model, + key: ( + this.options.localKey || + this.model.$configurator.getLocalKey(this.type, this.model, this.relatedModel()) + ), + }, + foreignKey: { + model: this.throughModel(), + key: ( + this.options.foreignKey || + this.model.$configurator.getForeignKey(this.type, this.model, this.throughModel()) + ), + }, + throughLocalKey: { + model: this.throughModel(), + key: ( + this.options.throughLocalKey || + this.model.$configurator.getLocalKey(this.type, this.throughModel(), this.relatedModel()) + ), + }, + throughForeignKey: { + model: this.relatedModel(), + key: ( + this.options.throughForeignKey || + this.model.$configurator.getForeignKey(this.type, this.throughModel(), this.relatedModel()) + ), + }, + } + ).extract() /** * Keys on the parent model */ - this.$localKey = localKey.attributeName - this.$localCastAsKey = localKey.castAsKey + this.localKey = localKey.attributeName + this.localCastAsKey = localKey.castAsKey /** * Keys on the through model */ - this.$foreignKey = foreignKey.attributeName - this.$foreignCastAsKey = foreignKey.castAsKey + this.foreignKey = foreignKey.attributeName + this.foreignCastAsKey = foreignKey.castAsKey - this.$throughLocalKey = throughLocalKey.attributeName - this.$throughLocalCastAsKey = throughLocalKey.castAsKey + this.throughLocalKey = throughLocalKey.attributeName + this.throughLocalCastAsKey = throughLocalKey.castAsKey - this.$throughForeignKey = throughForeignKey.attributeName - this.$throughForeignCastAsKey = throughForeignKey.castAsKey + this.throughForeignKey = throughForeignKey.attributeName + this.throughForeignCastAsKey = throughForeignKey.castAsKey /** * Booted successfully */ - this.$booted = true + this.booted = true } /** * Set related model instances */ public $setRelated (parent: ModelContract, related: ModelContract[]): void { - this.$ensureIsBooted() - parent.$setRelated(this.$relationName as any, related) + ensureRelationIsBooted(this) + parent.$setRelated(this.relationName as any, related) } /** * Push related model instance(s) */ public $pushRelated (parent: ModelContract, related: ModelContract | ModelContract[]): void { - this.$ensureIsBooted() - parent.$pushRelated(this.$relationName as any, related as any) + ensureRelationIsBooted(this) + parent.$pushRelated(this.relationName as any, related as any) } /** @@ -163,12 +172,12 @@ ModelConstructorContract * models. */ public $setRelatedForMany (parent: ModelContract[], related: ModelContract[]): void { - this.$ensureIsBooted() - const $foreignCastAsKeyAlias = this.throughAlias(this.$foreignCastAsKey) + ensureRelationIsBooted(this) + const $foreignCastAsKeyAlias = this.throughAlias(this.foreignCastAsKey) parent.forEach((parentModel) => { this.$setRelated(parentModel, related.filter((relatedModel) => { - const value = parentModel[this.$localKey] + const value = parentModel[this.localKey] return value !== undefined && relatedModel.$extras[$foreignCastAsKeyAlias] === value })) }) @@ -178,7 +187,7 @@ ModelConstructorContract * Returns an instance of query client for invoking queries */ public client (parent: ModelContract | ModelContract[], client: QueryClientContract): any { - this.$ensureIsBooted() + ensureRelationIsBooted(this) return new HasManyThroughClient(parent, client, this) } } diff --git a/src/Orm/Relations/HasOne/QueryBuilder.ts b/src/Orm/Relations/HasOne/QueryBuilder.ts index 29f27a43..27fde0b0 100644 --- a/src/Orm/Relations/HasOne/QueryBuilder.ts +++ b/src/Orm/Relations/HasOne/QueryBuilder.ts @@ -24,38 +24,48 @@ export class HasOneQueryBuilder extends BaseQueryBuilder implements RelationBase ModelConstructorContract, ModelConstructorContract > { + private appliedConstraints: boolean = false + constructor ( builder: knex.QueryBuilder, client: QueryClientContract, private parent: ModelContract | ModelContract[], - protected $relation: HasOne, + private relation: HasOne, isEager: boolean = false, ) { - super(builder, client, $relation, isEager, (userFn) => { + super(builder, client, relation, isEager, (userFn) => { return (__builder) => { - userFn(new HasOneQueryBuilder(__builder, this.client, this.parent, this.$relation)) + userFn(new HasOneQueryBuilder(__builder, this.client, this.parent, this.relation)) } }) } + protected profilerData () { + return { + relation: this.relation.type, + model: this.relation.model.name, + relatedModel: this.relation.relatedModel().name, + } + } + /** * Applies constraint to limit rows to the current relationship * only. */ public applyConstraints () { - if (this.$appliedConstraints) { + if (this.appliedConstraints) { return } - this.$appliedConstraints = true - const queryAction = this.$queryAction() + this.appliedConstraints = true + const queryAction = this.queryAction() /** * Eager query contraints */ if (Array.isArray(this.parent)) { - this.knexQuery.whereIn(this.$relation.$foreignCastAsKey, unique(this.parent.map((model) => { - return getValue(model, this.$relation.$localKey, this.$relation, queryAction) + this.knexQuery.whereIn(this.relation.foreignCastAsKey, unique(this.parent.map((model) => { + return getValue(model, this.relation.localKey, this.relation, queryAction) }))) return } @@ -63,8 +73,8 @@ ModelConstructorContract /** * Query constraints */ - const value = getValue(this.parent, this.$relation.$localKey, this.$relation, queryAction) - this.knexQuery.where(this.$relation.$foreignCastAsKey, value) + const value = getValue(this.parent, this.relation.localKey, this.relation, queryAction) + this.knexQuery.where(this.relation.foreignCastAsKey, value) /** * Do not add limit when updating or deleting @@ -78,6 +88,6 @@ ModelConstructorContract * The keys for constructing the join query */ public getRelationKeys (): string[] { - return [this.$relation.$foreignCastAsKey] + return [this.relation.foreignCastAsKey] } } diff --git a/src/Orm/Relations/HasOne/QueryClient.ts b/src/Orm/Relations/HasOne/QueryClient.ts index f4818a1d..fbcfa626 100644 --- a/src/Orm/Relations/HasOne/QueryClient.ts +++ b/src/Orm/Relations/HasOne/QueryClient.ts @@ -14,23 +14,21 @@ import { ModelObject, ModelConstructorContract, ModelContract } from '@ioc:Adoni import { HasOne } from './index' import { getValue } from '../../../utils' -import { BaseQueryClient } from '../Base/QueryClient' import { HasOneQueryBuilder } from './QueryBuilder' /** * Query client for executing queries in scope to the defined * relationship */ -export class HasOneQueryClient extends BaseQueryClient implements HasOneClientContract< +export class HasOneQueryClient implements HasOneClientContract< ModelConstructorContract, ModelConstructorContract > { constructor ( private parent: ModelContract | ModelContract[], - protected $client: QueryClientContract, - protected $relation: HasOne, + private client: QueryClientContract, + private relation: HasOne, ) { - super($client, $relation) } /** @@ -46,21 +44,21 @@ ModelConstructorContract * Returns value for the foreign key */ private getForeignKeyValue (parent: ModelContract, action: string) { - return getValue(parent, this.$relation.$localKey, this.$relation, action) + return getValue(parent, this.relation.localKey, this.relation, action) } /** * Returns instance of query builder */ public query (): any { - return new HasOneQueryBuilder(this.$client.knexQuery(), this.$client, this.parent, this.$relation) + return new HasOneQueryBuilder(this.client.knexQuery(), this.client, this.parent, this.relation) } /** * Returns instance of query builder with `eager=true` */ public eagerQuery (): any { - return new HasOneQueryBuilder(this.$client.knexQuery(), this.$client, this.parent, this.$relation, true) + return new HasOneQueryBuilder(this.client.knexQuery(), this.client, this.parent, this.relation, true) } /** @@ -74,7 +72,7 @@ ModelConstructorContract * Do not copy options or trx from the parent model, the end user must do * it themselves for explicit behavior */ - related[this.$relation.$foreignKey] = this.getForeignKeyValue(this.parent, 'save') + related[this.relation.foreignKey] = this.getForeignKeyValue(this.parent, 'save') await related.save() } @@ -85,9 +83,13 @@ ModelConstructorContract this.ensureSingleParent(this.parent) await this.parent.save() - return this.$relation.$relatedModel().create(Object.assign({ - [this.$relation.$foreignKey]: this.getForeignKeyValue(this.parent, 'create'), - }, values), this.$clientOptions) + return this.relation.relatedModel().create(Object.assign({ + [this.relation.foreignKey]: this.getForeignKeyValue(this.parent, 'create'), + }, values), { + client: this.client, + connection: this.client.connectionName, + profiler: this.client.profiler, + }) } /** @@ -100,9 +102,13 @@ ModelConstructorContract this.ensureSingleParent(this.parent) await this.parent.save() - return this.$relation.$relatedModel().firstOrCreate(Object.assign({ - [this.$relation.$foreignKey]: this.getForeignKeyValue(this.parent, 'firstOrCreate'), - }, search), savePayload, this.$clientOptions) + return this.relation.relatedModel().firstOrCreate(Object.assign({ + [this.relation.foreignKey]: this.getForeignKeyValue(this.parent, 'firstOrCreate'), + }, search), savePayload, { + client: this.client, + connection: this.client.connectionName, + profiler: this.client.profiler, + }) } /** @@ -115,8 +121,12 @@ ModelConstructorContract this.ensureSingleParent(this.parent) await this.parent.save() - return this.$relation.$relatedModel().updateOrCreate(Object.assign({ - [this.$relation.$foreignKey]: this.getForeignKeyValue(this.parent, 'updateOrCreate'), - }, search), updatePayload, this.$clientOptions) + return this.relation.relatedModel().updateOrCreate(Object.assign({ + [this.relation.foreignKey]: this.getForeignKeyValue(this.parent, 'updateOrCreate'), + }, search), updatePayload, { + client: this.client, + connection: this.client.connectionName, + profiler: this.client.profiler, + }) } } diff --git a/src/Orm/Relations/HasOne/index.ts b/src/Orm/Relations/HasOne/index.ts index 5c90d063..19858432 100644 --- a/src/Orm/Relations/HasOne/index.ts +++ b/src/Orm/Relations/HasOne/index.ts @@ -11,106 +11,112 @@ import { QueryClientContract } from '@ioc:Adonis/Lucid/Database' import { ModelConstructorContract, ModelContract } from '@ioc:Adonis/Lucid/Model' import { HasOneRelationContract, RelationOptions } from '@ioc:Adonis/Lucid/Relations' -import { BaseRelation } from '../Base' +// import { BaseRelation } from '../Base' import { HasOneQueryClient } from './QueryClient' +import { KeysExtractor } from '../KeysExtractor' +import { ensureRelationIsBooted } from '../../../utils' /** * Manages loading and persisting has one relationship */ -export class HasOne extends BaseRelation implements HasOneRelationContract< +export class HasOne implements HasOneRelationContract< ModelConstructorContract, ModelConstructorContract > { - public $type = 'hasOne' as const + public type = 'hasOne' as const + public booted: boolean = false + public relatedModel = this.options.relatedModel + public serializeAs = this.options.serializeAs || this.relationName /** * Available after boot is invoked */ - public $localKey: string - public $localCastAsKey: string - public $foreignKey: string - public $foreignCastAsKey: string + public localKey: string + public localCastAsKey: string + public foreignKey: string + public foreignCastAsKey: string constructor ( - relationName: string, - options: RelationOptions, - model: ModelConstructorContract, + public relationName: string, + private options: RelationOptions, + public model: ModelConstructorContract, ) { - super(relationName, options, model) } /** * Boot the relationship and ensure that all keys are in * place for queries to do their job. */ - public $boot () { - if (this.$booted) { + public boot () { + if (this.booted) { return } + const relatedModel = this.relatedModel() + /** * Extracting keys from the model and the relation model. The keys * extractor ensures all the required columns are defined on * the models for the relationship to work */ - const { localKey, foreignKey } = this.$extractKeys({ + const { localKey, foreignKey } = new KeysExtractor(this.model, this.relationName, { localKey: { - model: this.$model, + model: this.model, key: ( - this.$options.localKey || - this.$model.$configurator.getLocalKey(this.$type, this.$model, this.$relatedModel()) + this.options.localKey || + this.model.$configurator.getLocalKey(this.type, this.model, relatedModel) ), }, foreignKey: { - model: this.$relatedModel(), + model: relatedModel, key: ( - this.$options.foreignKey || - this.$model.$configurator.getForeignKey(this.$type, this.$model, this.$relatedModel()) + this.options.foreignKey || + this.model.$configurator.getForeignKey(this.type, this.model, relatedModel) ), }, - }) + }).extract() /** * Keys on the parent model */ - this.$localKey = localKey.attributeName - this.$localCastAsKey = localKey.castAsKey + this.localKey = localKey.attributeName + this.localCastAsKey = localKey.castAsKey /** * Keys on the related model */ - this.$foreignKey = foreignKey.attributeName - this.$foreignCastAsKey = foreignKey.castAsKey + this.foreignKey = foreignKey.attributeName + this.foreignCastAsKey = foreignKey.castAsKey /** * Booted successfully */ - this.$booted = true + this.booted = true } /** * Set related model instance */ public $setRelated (parent: ModelContract, related: ModelContract | null): void { - this.$ensureIsBooted() + ensureRelationIsBooted(this) if (!related) { return } - parent.$setRelated(this.$relationName as any, related) + parent.$setRelated(this.relationName as any, related) } /** * Push related model instance */ public $pushRelated (parent: ModelContract, related: ModelContract | null): void { - this.$ensureIsBooted() + ensureRelationIsBooted(this) if (!related) { return } - parent.$pushRelated(this.$relationName as any, related) + parent.$pushRelated(this.relationName as any, related) } /** @@ -118,7 +124,7 @@ ModelConstructorContract * models. */ public $setRelatedForMany (parent: ModelContract[], related: ModelContract[]): void { - this.$ensureIsBooted() + ensureRelationIsBooted(this) /** * The related model will always be equal or less than the parent @@ -127,8 +133,8 @@ ModelConstructorContract */ related.forEach((relatedModel) => { const match = parent.find((parentModel) => { - const value = parentModel[this.$localKey] - return value !== undefined && value === relatedModel[this.$foreignKey] + const value = parentModel[this.localKey] + return value !== undefined && value === relatedModel[this.foreignKey] }) if (match) { this.$setRelated(match, relatedModel) @@ -140,7 +146,7 @@ ModelConstructorContract * Returns an instance of query client for invoking queries */ public client (parent: ModelContract | ModelContract[], client: QueryClientContract): any { - this.$ensureIsBooted() + ensureRelationIsBooted(this) return new HasOneQueryClient(parent, client, this) } } diff --git a/src/Orm/Relations/ManyToMany/QueryBuilder.ts b/src/Orm/Relations/ManyToMany/QueryBuilder.ts index f98dc267..0573ad77 100644 --- a/src/Orm/Relations/ManyToMany/QueryBuilder.ts +++ b/src/Orm/Relations/ManyToMany/QueryBuilder.ts @@ -25,43 +25,53 @@ ModelConstructorContract, ModelConstructorContract > { private cherryPickingKeys: boolean = false + private appliedConstraints: boolean = false constructor ( builder: knex.QueryBuilder, client: QueryClientContract, private parent: ModelContract | ModelContract[], - protected $relation: ManyToMany, + private relation: ManyToMany, private pivotOnly: boolean, isEager: boolean = false, ) { - super(builder, client, $relation, isEager, (userFn) => { + super(builder, client, relation, isEager, (userFn) => { return (__builder) => { userFn( - new ManyToManyQueryBuilder(__builder, this.client, this.parent, this.$relation, this.pivotOnly, isEager), + new ManyToManyQueryBuilder(__builder, this.client, this.parent, this.relation, this.pivotOnly, isEager), ) } }) } + protected profilerData () { + return { + relation: this.relation.type, + model: this.relation.model.name, + pivotTable: this.relation.pivotTable, + relatedModel: this.relation.relatedModel().name, + } + } + /** * Prefixes the pivot table name to the key */ private prefixPivotTable (key: string) { - return this.pivotOnly ? key : `${this.$relation.$pivotTable}.${key}` + return this.pivotOnly ? key : `${this.relation.pivotTable}.${key}` } /** * Adds where constraint to the pivot table */ private addWhereConstraints () { - const queryAction = this.$queryAction() + const queryAction = this.queryAction() /** * Eager query contraints */ if (Array.isArray(this.parent)) { - this.whereInPivot(this.$relation.$pivotForeignKey, unique(this.parent.map((model) => { - return getValue(model, this.$relation.$localKey, this.$relation, queryAction) + this.whereInPivot(this.relation.pivotForeignKey, unique(this.parent.map((model) => { + return getValue(model, this.relation.localKey, this.relation, queryAction) }))) return } @@ -69,8 +79,8 @@ ModelConstructorContract /** * Query constraints */ - const value = getValue(this.parent, this.$relation.$localKey, this.$relation, queryAction) - this.wherePivot(this.$relation.$pivotForeignKey, value) + const value = getValue(this.parent, this.relation.localKey, this.relation, queryAction) + this.wherePivot(this.relation.pivotForeignKey, value) } /** @@ -82,7 +92,7 @@ ModelConstructorContract return columns } - const relatedTable = this.$relation.$relatedModel().$table + const relatedTable = this.relation.relatedModel().table return columns.map((column) => { if (typeof (column) === 'string') { return `${relatedTable}.${column}` @@ -117,11 +127,11 @@ ModelConstructorContract */ public wherePivot (key: any, operator?: any, value?: any): this { if (value !== undefined) { - this.knexQuery.where(this.prefixPivotTable(key), operator, this.$transformValue(value)) + this.knexQuery.where(this.prefixPivotTable(key), operator, this.transformValue(value)) } else if (operator) { - this.knexQuery.where(this.prefixPivotTable(key), this.$transformValue(operator)) + this.knexQuery.where(this.prefixPivotTable(key), this.transformValue(operator)) } else { - this.knexQuery.where(this.$transformCallback(key)) + this.knexQuery.where(this.transformCallback(key)) } return this @@ -132,11 +142,11 @@ ModelConstructorContract */ public orWherePivot (key: any, operator?: any, value?: any): this { if (value !== undefined) { - this.knexQuery.orWhere(this.prefixPivotTable(key), operator, this.$transformValue(value)) + this.knexQuery.orWhere(this.prefixPivotTable(key), operator, this.transformValue(value)) } else if (operator) { - this.knexQuery.orWhere(this.prefixPivotTable(key), this.$transformValue(operator)) + this.knexQuery.orWhere(this.prefixPivotTable(key), this.transformValue(operator)) } else { - this.knexQuery.orWhere(this.$transformCallback(key)) + this.knexQuery.orWhere(this.transformCallback(key)) } return this @@ -154,11 +164,11 @@ ModelConstructorContract */ public whereNotPivot (key: any, operator?: any, value?: any): this { if (value !== undefined) { - this.knexQuery.whereNot(this.prefixPivotTable(key), operator, this.$transformValue(value)) + this.knexQuery.whereNot(this.prefixPivotTable(key), operator, this.transformValue(value)) } else if (operator) { - this.knexQuery.whereNot(this.prefixPivotTable(key), this.$transformValue(operator)) + this.knexQuery.whereNot(this.prefixPivotTable(key), this.transformValue(operator)) } else { - this.knexQuery.whereNot(this.$transformCallback(key)) + this.knexQuery.whereNot(this.transformCallback(key)) } return this @@ -169,11 +179,11 @@ ModelConstructorContract */ public orWhereNotPivot (key: any, operator?: any, value?: any): this { if (value !== undefined) { - this.knexQuery.orWhereNot(this.prefixPivotTable(key), operator, this.$transformValue(value)) + this.knexQuery.orWhereNot(this.prefixPivotTable(key), operator, this.transformValue(value)) } else if (operator) { - this.knexQuery.orWhereNot(this.prefixPivotTable(key), this.$transformValue(operator)) + this.knexQuery.orWhereNot(this.prefixPivotTable(key), this.transformValue(operator)) } else { - this.knexQuery.orWhereNot(this.$transformCallback(key)) + this.knexQuery.orWhereNot(this.transformCallback(key)) } return this @@ -191,8 +201,8 @@ ModelConstructorContract */ public whereInPivot (key: any, value: any) { value = Array.isArray(value) - ? value.map((one) => this.$transformValue(one)) - : this.$transformValue(value) + ? value.map((one) => this.transformValue(one)) + : this.transformValue(value) key = Array.isArray(key) ? key.map((one) => this.prefixPivotTable(one)) @@ -207,8 +217,8 @@ ModelConstructorContract */ public orWhereInPivot (key: any, value: any) { value = Array.isArray(value) - ? value.map((one) => this.$transformValue(one)) - : this.$transformValue(value) + ? value.map((one) => this.transformValue(one)) + : this.transformValue(value) key = Array.isArray(key) ? key.map((one) => this.prefixPivotTable(one)) @@ -230,8 +240,8 @@ ModelConstructorContract */ public whereNotInPivot (key: any, value: any) { value = Array.isArray(value) - ? value.map((one) => this.$transformValue(one)) - : this.$transformValue(value) + ? value.map((one) => this.transformValue(one)) + : this.transformValue(value) key = Array.isArray(key) ? key.map((one) => this.prefixPivotTable(one)) @@ -246,8 +256,8 @@ ModelConstructorContract */ public orWhereNotInPivot (key: any, value: any) { value = Array.isArray(value) - ? value.map((one) => this.$transformValue(one)) - : this.$transformValue(value) + ? value.map((one) => this.transformValue(one)) + : this.transformValue(value) key = Array.isArray(key) ? key.map((one) => this.prefixPivotTable(one)) @@ -269,7 +279,7 @@ ModelConstructorContract */ public pivotColumns (columns: string[]): this { this.knexQuery.select(columns.map((column) => { - return `${this.prefixPivotTable(column)} as ${this.$relation.pivotAlias(column)}` + return `${this.prefixPivotTable(column)} as ${this.relation.pivotAlias(column)}` })) return this } @@ -279,13 +289,13 @@ ModelConstructorContract * only. */ public applyConstraints () { - if (this.$appliedConstraints) { + if (this.appliedConstraints) { return } - this.$appliedConstraints = true - if (this.pivotOnly || ['delete', 'update'].includes(this.$queryAction())) { - this.from(this.$relation.$pivotTable) + this.appliedConstraints = true + if (this.pivotOnly || ['delete', 'update'].includes(this.queryAction())) { + this.from(this.relation.pivotTable) this.addWhereConstraints() return } @@ -303,18 +313,18 @@ ModelConstructorContract */ this.pivotColumns( [ - this.$relation.$pivotForeignKey, - this.$relation.$pivotRelatedForeignKey, - ].concat(this.$relation.$extrasPivotColumns), + this.relation.pivotForeignKey, + this.relation.pivotRelatedForeignKey, + ].concat(this.relation.extrasPivotColumns), ) /** * Add inner join between related model and pivot table */ this.innerJoin( - this.$relation.$pivotTable, - `${this.$relation.$relatedModel().$table}.${this.$relation.$relatedCastAsKey}`, - `${this.$relation.$pivotTable}.${this.$relation.$pivotRelatedForeignKey}`, + this.relation.pivotTable, + `${this.relation.relatedModel().table}.${this.relation.relatedCastAsKey}`, + `${this.relation.pivotTable}.${this.relation.pivotRelatedForeignKey}`, ) this.addWhereConstraints() @@ -325,7 +335,7 @@ ModelConstructorContract */ public getRelationKeys (): string[] { return [ - `${this.$relation.$relatedModel().$table}.${this.$relation.$relatedCastAsKey}`, + `${this.relation.relatedModel().table}.${this.relation.relatedCastAsKey}`, ] } } diff --git a/src/Orm/Relations/ManyToMany/QueryClient.ts b/src/Orm/Relations/ManyToMany/QueryClient.ts index c11d3641..5ac508ce 100644 --- a/src/Orm/Relations/ManyToMany/QueryClient.ts +++ b/src/Orm/Relations/ManyToMany/QueryClient.ts @@ -14,23 +14,23 @@ import { ModelConstructorContract, ModelContract, ModelObject } from '@ioc:Adoni import { ManyToMany } from './index' import { unique, getValue } from '../../../utils' -import { BaseQueryClient } from '../Base/QueryClient' +// import { BaseQueryClient } from '../Base/QueryClient' import { ManyToManyQueryBuilder } from './QueryBuilder' /** * Query client for executing queries in scope to the defined * relationship */ -export class ManyToManyQueryClient extends BaseQueryClient implements ManyToManyClientContract< +export class ManyToManyQueryClient implements ManyToManyClientContract< ModelConstructorContract, ModelConstructorContract > { constructor ( private parent: ModelContract | ModelContract[], - protected $client: QueryClientContract, - protected $relation: ManyToMany, + private client: QueryClientContract, + private relation: ManyToMany, ) { - super($client, $relation) + // super($client, $relation) } /** @@ -46,19 +46,19 @@ ModelConstructorContract * Returns value for the foreign key */ private getForeignKeyValue (parent: ModelContract, action: string) { - return getValue(parent, this.$relation.$localKey, this.$relation, action) + return getValue(parent, this.relation.localKey, this.relation, action) } public query (): any { - return new ManyToManyQueryBuilder(this.$client.knexQuery(), this.$client, this.parent, this.$relation, false, false) + return new ManyToManyQueryBuilder(this.client.knexQuery(), this.client, this.parent, this.relation, false, false) } public eagerQuery (): any { - return new ManyToManyQueryBuilder(this.$client.knexQuery(), this.$client, this.parent, this.$relation, false, true) + return new ManyToManyQueryBuilder(this.client.knexQuery(), this.client, this.parent, this.relation, false, true) } public pivotQuery (): any { - return new ManyToManyQueryBuilder(this.$client.knexQuery(), this.$client, this.parent, this.$relation, true, false) + return new ManyToManyQueryBuilder(this.client.knexQuery(), this.client, this.parent, this.relation, true, false) } public async create (): Promise { @@ -73,18 +73,18 @@ ModelConstructorContract this.ensureSingleParent(this.parent) await this.parent.save() - const trx = await this.$client.transaction() + const trx = await this.client.transaction() try { - related.$trx = trx + related.trx = trx await related.save() - const relatedKeyValue = related[this.$relation.$relatedKey] + const relatedKeyValue = related[this.relation.relatedKey] let hasRow = false if (checkExisting) { hasRow = await this .pivotQuery() - .wherePivot(this.$relation.$pivotRelatedForeignKey, relatedKeyValue) + .wherePivot(this.relation.pivotRelatedForeignKey, relatedKeyValue) .useTransaction(trx) .first() } @@ -104,27 +104,27 @@ ModelConstructorContract this.ensureSingleParent(this.parent) await this.parent.save() - const trx = await this.$client.transaction() + const trx = await this.client.transaction() try { await Promise.all(related.map((one) => { - one.$trx = trx + one.trx = trx return one.save() })) - const relatedKeyValues = related.map((one) => one[this.$relation.$relatedKey]) + const relatedKeyValues = related.map((one) => one[this.relation.relatedKey]) let existingsRows: ModelContract[] = [] if (checkExisting) { existingsRows = await this .pivotQuery() - .select(this.$relation.$pivotRelatedForeignKey) - .whereInPivot(this.$relation.$pivotRelatedForeignKey, relatedKeyValues) + .select(this.relation.pivotRelatedForeignKey) + .whereInPivot(this.relation.pivotRelatedForeignKey, relatedKeyValues) .useTransaction(trx) } const nonExistingRows = relatedKeyValues.filter((id) => !existingsRows.find((existingRow) => { - return existingRow.$extras[this.$relation.$pivotRelatedForeignKey] === id + return existingRow.$extras[this.relation.pivotRelatedForeignKey] === id })) await this.attach(nonExistingRows, trx) @@ -157,7 +157,7 @@ ModelConstructorContract * Use existing transaction or create a new one */ let selfTransaction = !trx - trx = trx || await this.$client.transaction() + trx = trx || await this.client.transaction() /** * Perform multi insert @@ -165,11 +165,11 @@ ModelConstructorContract try { await trx .insertQuery() - .table(this.$relation.$pivotTable) + .table(this.relation.pivotTable) .multiInsert(unique(relatedForeignKeyValues).map((id) => { return Object.assign({}, hasAttributes ? ids[id] : {}, { - [this.$relation.$pivotForeignKey]: foreignKeyValue, - [this.$relation.$pivotRelatedForeignKey]: id, + [this.relation.pivotForeignKey]: foreignKeyValue, + [this.relation.pivotRelatedForeignKey]: id, }) })) @@ -185,7 +185,7 @@ ModelConstructorContract } public async detach (ids: string[]) { - await this.pivotQuery().whereInPivot(this.$relation.$pivotRelatedForeignKey, ids).del() + await this.pivotQuery().whereInPivot(this.relation.pivotRelatedForeignKey, ids).del() } public async sync () { diff --git a/src/Orm/Relations/ManyToMany/index.ts b/src/Orm/Relations/ManyToMany/index.ts index 175d083c..a9cb930f 100644 --- a/src/Orm/Relations/ManyToMany/index.ts +++ b/src/Orm/Relations/ManyToMany/index.ts @@ -11,54 +11,59 @@ import { QueryClientContract } from '@ioc:Adonis/Lucid/Database' import { ModelConstructorContract, ModelContract } from '@ioc:Adonis/Lucid/Model' import { ManyToManyRelationContract, ManyToManyRelationOptions } from '@ioc:Adonis/Lucid/Relations' -import { BaseRelation } from '../Base' +// import { BaseRelation } from '../Base' import { ManyToManyQueryClient } from './QueryClient' +import { KeysExtractor } from '../KeysExtractor' +import { ensureRelationIsBooted } from '../../../utils' /** * Manages loading and persisting many to many relationship */ -export class ManyToMany extends BaseRelation implements ManyToManyRelationContract< +export class ManyToMany implements ManyToManyRelationContract< ModelConstructorContract, ModelConstructorContract > { - public $type = 'manyToMany' as const + public type = 'manyToMany' as const + public booted: boolean = false + public relatedModel = this.options.relatedModel + public serializeAs = this.options.serializeAs || this.relationName /** * Available after boot is invoked */ - public $localKey: string - public $localCastAsKey: string + public localKey: string + public localCastAsKey: string - public $relatedKey: string - public $relatedCastAsKey: string + public relatedKey: string + public relatedCastAsKey: string - public $pivotForeignKey: string - public $pivotRelatedForeignKey: string + public pivotForeignKey: string + public pivotRelatedForeignKey: string - public $pivotTable: string - public $extrasPivotColumns: string[] = this.manyToManyOptions.pivotColumns || [] + public pivotTable: string + public extrasPivotColumns: string[] = this.options.pivotColumns || [] - public get $profilerData () { - return { - model: this.$model.name, - relatedModel: this.$relatedModel().name, - pivotTable: this.$pivotTable, - relation: this.$type, - } - } + // public get profilerData () { + // return { + // model: this.model.name, + // relatedModel: this.relatedModel().name, + // pivotTable: this.pivotTable, + // relation: this.type, + // } + // } constructor ( - relationName: string, - private manyToManyOptions: ManyToManyRelationOptions, - model: ModelConstructorContract, + public relationName: string, + private options: ManyToManyRelationOptions, + public model: ModelConstructorContract, ) { - super(relationName, manyToManyOptions, model) + // super(relationName, options, model) } /** * Returns the alias for the pivot key */ - public pivotAlias (key) { + public pivotAlias (key: string): string { return `pivot_${key}` } @@ -66,88 +71,88 @@ ModelConstructorContract * Boot the relationship and ensure that all keys are in * place for queries to do their job. */ - public $boot () { - if (this.$booted) { + public boot () { + if (this.booted) { return } + const relatedModel = this.relatedModel() + /** * Extracting keys from the model and the relation model. The keys * extractor ensures all the required columns are defined on * the models for the relationship to work */ - const { localKey, relatedKey } = this.$extractKeys({ + const { localKey, relatedKey } = new KeysExtractor(this.model, this.relationName, { localKey: { - model: this.$model, + model: this.model, key: ( - this.manyToManyOptions.localKey || - this.$model.$configurator.getLocalKey(this.$type, this.$model, this.$relatedModel()) + this.options.localKey || + this.model.$configurator.getLocalKey(this.type, this.model, relatedModel) ), }, relatedKey: { - model: this.$relatedModel(), + model: relatedModel, key: ( - this.manyToManyOptions.relatedKey || - this.$model.$configurator.getLocalKey(this.$type, this.$model, this.$relatedModel()) + this.options.relatedKey || + this.model.$configurator.getLocalKey(this.type, this.model, relatedModel) ), }, - }) + }).extract() - this.$pivotTable = this.manyToManyOptions.pivotTable || this.$model.$configurator.getPivotTableName( - this.$type, - this.$model, - this.$relatedModel(), - this.$relationName, + this.pivotTable = this.options.pivotTable || this.model.$configurator.getPivotTableName( + this.type, + this.model, + relatedModel, + this.relationName, ) /** * Keys on the parent model */ - this.$localKey = localKey.attributeName - this.$localCastAsKey = localKey.castAsKey + this.localKey = localKey.attributeName + this.localCastAsKey = localKey.castAsKey /** * Keys on the related model */ - this.$relatedKey = relatedKey.attributeName - this.$relatedCastAsKey = relatedKey.castAsKey + this.relatedKey = relatedKey.attributeName + this.relatedCastAsKey = relatedKey.castAsKey /** * Parent model foreign key in the pivot table */ - this.$pivotForeignKey = this.manyToManyOptions.pivotForeignKey || - this.$model.$configurator.getPivotForeignKey( - this.$type, this.$model, this.$relatedModel(), this.$relationName - ) + this.pivotForeignKey = + this.options.pivotForeignKey || + this.model.$configurator.getPivotForeignKey(this.type, this.model, relatedModel, this.relationName) /** * Related model foreign key in the pivot table */ - this.$pivotRelatedForeignKey = this.manyToManyOptions.pivotRelatedForeignKey || - this.$model.$configurator.getPivotForeignKey( - this.$type, this.$relatedModel(), this.$model, this.$relationName - ) + this.pivotRelatedForeignKey = + this.options.pivotRelatedForeignKey || + this.model.$configurator.getPivotForeignKey(this.type, relatedModel, this.model, this.relationName) /** * Booted successfully */ - this.$booted = true + this.booted = true } /** * Set related model instances */ public $setRelated (parent: ModelContract, related: ModelContract[]): void { - this.$ensureIsBooted() - parent.$setRelated(this.$relationName as any, related) + ensureRelationIsBooted(this) + parent.$setRelated(this.relationName as any, related) } /** * Push related model instance(s) */ public $pushRelated (parent: ModelContract, related: ModelContract | ModelContract[]): void { - this.$ensureIsBooted() - parent.$pushRelated(this.$relationName as any, related as any) + ensureRelationIsBooted(this) + parent.$pushRelated(this.relationName as any, related as any) } /** @@ -155,14 +160,14 @@ ModelConstructorContract * models. */ public $setRelatedForMany (parent: ModelContract[], related: ModelContract[]): void { - this.$ensureIsBooted() - const pivotForeignKeyAlias = this.pivotAlias(this.$pivotForeignKey) + ensureRelationIsBooted(this) + const pivotForeignKeyAlias = this.pivotAlias(this.pivotForeignKey) parent.forEach((parentModel) => { this.$setRelated( parentModel, related.filter((relatedModel) => { - const value = parentModel[this.$localKey] + const value = parentModel[this.localKey] return value !== undefined && relatedModel.$extras[pivotForeignKeyAlias] === value }), ) @@ -173,7 +178,7 @@ ModelConstructorContract * Returns an instance of query client for invoking queries */ public client (parent: ModelContract | ModelContract[], client: QueryClientContract): any { - this.$ensureIsBooted() + ensureRelationIsBooted(this) return new ManyToManyQueryClient(parent, client, this) } } diff --git a/src/utils/index.ts b/src/utils/index.ts index 21fb6048..85a45740 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -38,6 +38,16 @@ export function ensureValue (collection: any, key: string, missingCallback: () = return value } +export function ensureRelationIsBooted (relation: RelationshipsContract) { + if (!relation.booted) { + throw new Exception( + 'Relationship is not booted. Make sure to call boot first', + 500, + 'E_RUNTIME_EXCEPTION', + ) + } +} + /** * Returns the value for a key from the model instance and raises descriptive * exception when the value is missing @@ -50,7 +60,7 @@ export function getValue ( ) { return ensureValue(model, key, () => { throw new Exception( - `Cannot ${action} "${relation.$relationName}", value of "${relation.$model.name}.${key}" is undefined`, + `Cannot ${action} "${relation.relationName}", value of "${relation.model.name}.${key}" is undefined`, 500, ) }) diff --git a/test/orm/adapter.spec.ts b/test/orm/adapter.spec.ts index af39ff44..826eba44 100644 --- a/test/orm/adapter.spec.ts +++ b/test/orm/adapter.spec.ts @@ -43,7 +43,7 @@ test.group('Adapter', (group) => { public username: string } - User.$boot() + User.boot() const user = new User() user.username = 'virk' @@ -51,8 +51,8 @@ test.group('Adapter', (group) => { assert.exists(user.id) assert.deepEqual(user.$attributes, { username: 'virk', id: user.id }) - assert.isFalse(user.$isDirty) - assert.isTrue(user.$isPersisted) + assert.isFalse(user.isDirty) + assert.isTrue(user.isPersisted) }) test('make update call using a model', async (assert) => { @@ -65,7 +65,7 @@ test.group('Adapter', (group) => { @column() public username: string } - User.$boot() + User.boot() const user = new User() user.username = 'virk' @@ -73,12 +73,12 @@ test.group('Adapter', (group) => { assert.exists(user.id) assert.deepEqual(user.$attributes, { username: 'virk', id: user.id }) - assert.isFalse(user.$isDirty) - assert.isTrue(user.$isPersisted) + assert.isFalse(user.isDirty) + assert.isTrue(user.isPersisted) user.username = 'nikk' - assert.isTrue(user.$isDirty) - assert.deepEqual(user.$dirty, { username: 'nikk' }) + assert.isTrue(user.isDirty) + assert.deepEqual(user.dirty, { username: 'nikk' }) await user.save() }) @@ -93,7 +93,7 @@ test.group('Adapter', (group) => { @column() public username: string } - User.$boot() + User.boot() const user = new User() user.username = 'virk' @@ -101,11 +101,11 @@ test.group('Adapter', (group) => { assert.exists(user.id) assert.deepEqual(user.$attributes, { username: 'virk', id: user.id }) - assert.isFalse(user.$isDirty) - assert.isTrue(user.$isPersisted) + assert.isFalse(user.isDirty) + assert.isTrue(user.isPersisted) await user.delete() - assert.isTrue(user.$isDeleted) + assert.isTrue(user.isDeleted) const users = await db.from('users').select('*') assert.lengthOf(users, 0) @@ -121,7 +121,7 @@ test.group('Adapter', (group) => { @column() public username: string } - User.$boot() + User.boot() await db.table('users').returning('id').multiInsert( [{ username: 'virk' }, { username: 'nikk' }], @@ -133,8 +133,8 @@ test.group('Adapter', (group) => { assert.instanceOf(users[0], User) assert.instanceOf(users[1], User) - assert.isFalse(users[0].$isDirty) - assert.isFalse(users[1].$isDirty) + assert.isFalse(users[0].isDirty) + assert.isFalse(users[1].isDirty) assert.deepEqual(users[0].$attributes, { id: 2, username: 'nikk' }) assert.deepEqual(users[1].$attributes, { id: 1, username: 'virk' }) @@ -151,11 +151,11 @@ test.group('Adapter', (group) => { public username: string } - User.$boot() + User.boot() const trx = await db.transaction() const user = new User() - user.$trx = trx + user.trx = trx user.username = 'virk' await user.save() await trx.commit() @@ -164,10 +164,10 @@ test.group('Adapter', (group) => { assert.equal(totalUsers[0].total, 1) assert.exists(user.id) - assert.isUndefined(user.$trx) + assert.isUndefined(user.trx) assert.deepEqual(user.$attributes, { username: 'virk', id: user.id }) - assert.isFalse(user.$isDirty) - assert.isTrue(user.$isPersisted) + assert.isFalse(user.isDirty) + assert.isTrue(user.isPersisted) }) test('do not insert when transaction rollbacks', async (assert) => { @@ -181,11 +181,11 @@ test.group('Adapter', (group) => { public username: string } - User.$boot() + User.boot() const trx = await db.transaction() const user = new User() - user.$trx = trx + user.trx = trx user.username = 'virk' await user.save() await trx.rollback() @@ -194,10 +194,10 @@ test.group('Adapter', (group) => { assert.equal(totalUsers[0].total, 0) assert.exists(user.id) - assert.isUndefined(user.$trx) + assert.isUndefined(user.trx) assert.deepEqual(user.$attributes, { username: 'virk', id: user.id }) - assert.isFalse(user.$isDirty) - assert.isTrue(user.$isPersisted) + assert.isFalse(user.isDirty) + assert.isTrue(user.isPersisted) }) test('cleanup old trx event listeners when transaction is updated', async (assert) => { @@ -211,17 +211,17 @@ test.group('Adapter', (group) => { public username: string } - User.$boot() + User.boot() const trx = await db.transaction() const trx1 = await trx.transaction() const user = new User() - user.$trx = trx1 - user.$trx = trx + user.trx = trx1 + user.trx = trx user.username = 'virk' await trx1.rollback() - assert.deepEqual(user.$trx, trx) + assert.deepEqual(user.trx, trx) await trx.rollback() }) @@ -235,7 +235,7 @@ test.group('Adapter', (group) => { @column() public username: string } - User.$boot() + User.boot() const user = new User() user.username = 'virk' @@ -243,11 +243,11 @@ test.group('Adapter', (group) => { assert.exists(user.id) assert.deepEqual(user.$attributes, { username: 'virk', id: user.id }) - assert.isFalse(user.$isDirty) - assert.isTrue(user.$isPersisted) + assert.isFalse(user.isDirty) + assert.isTrue(user.isPersisted) const trx = await db.transaction() - user.$trx = trx + user.trx = trx user.username = 'nikk' await user.save() await trx.rollback() @@ -267,7 +267,7 @@ test.group('Adapter', (group) => { @column() public username: string } - User.$boot() + User.boot() const user = new User() user.username = 'virk' @@ -275,11 +275,11 @@ test.group('Adapter', (group) => { assert.exists(user.id) assert.deepEqual(user.$attributes, { username: 'virk', id: user.id }) - assert.isFalse(user.$isDirty) - assert.isTrue(user.$isPersisted) + assert.isFalse(user.isDirty) + assert.isTrue(user.isPersisted) const trx = await db.transaction() - user.$trx = trx + user.trx = trx await user.delete() await trx.rollback() diff --git a/test/orm/base-model-options.spec.ts b/test/orm/base-model-options.spec.ts index be692591..86063067 100644 --- a/test/orm/base-model-options.spec.ts +++ b/test/orm/base-model-options.spec.ts @@ -51,8 +51,8 @@ test.group('Model options | QueryBuilder', (group) => { const users = await User.query().exec() assert.lengthOf(users, 1) - assert.equal(users[0].$options!.connection, 'primary') - assert.instanceOf(users[0].$options!.profiler, Profiler) + assert.equal(users[0].options!.connection, 'primary') + assert.instanceOf(users[0].options!.profiler, Profiler) }) test('query builder set model options when only one row is fetched', async (assert) => { @@ -70,8 +70,8 @@ test.group('Model options | QueryBuilder', (group) => { const user = await User.query().first() - assert.equal(user!.$options!.connection, 'primary') - assert.instanceOf(user!.$options!.profiler, Profiler) + assert.equal(user!.options!.connection, 'primary') + assert.instanceOf(user!.options!.profiler, Profiler) }) test('query builder use transaction when updating rows', async (assert) => { @@ -118,7 +118,7 @@ test.group('Model options | QueryBuilder', (group) => { assert.lengthOf(users, 1) await trx.commit() - assert.isUndefined(users[0].$trx) + assert.isUndefined(users[0].trx) users[0].username = 'nikk' await users[0].save() @@ -157,8 +157,8 @@ test.group('Model options | Adapter', (group) => { await db.insertQuery().table('users').insert({ username: 'virk' }) const user = await User.query({ connection: 'secondary' }).first() - assert.equal(user!.$options!.connection, 'secondary') - assert.instanceOf(user!.$options!.profiler, Profiler) + assert.equal(user!.options!.connection, 'secondary') + assert.instanceOf(user!.options!.profiler, Profiler) }) test('pass profiler to the client when defined explicitly', async (assert) => { @@ -176,8 +176,8 @@ test.group('Model options | Adapter', (group) => { const profiler = new Profiler({}) const user = await User.query({ profiler }).first() - assert.equal(user!.$options!.connection, 'primary') - assert.deepEqual(user!.$options!.profiler, profiler) + assert.equal(user!.options!.connection, 'primary') + assert.deepEqual(user!.options!.profiler, profiler) }) test('pass custom client to query builder', async (assert) => { @@ -196,7 +196,7 @@ test.group('Model options | Adapter', (group) => { const client = db.connection() const user = await User.query({ client }).first() - assert.equal(user!.$options!.connection, 'primary') + assert.equal(user!.options!.connection, 'primary') }) test('pass transaction client to query builder', async (assert) => { @@ -216,7 +216,7 @@ test.group('Model options | Adapter', (group) => { const user = await User.query({ client: trx }).first() await trx.rollback() - assert.equal(user!.$options!.connection, 'secondary') + assert.equal(user!.options!.connection, 'secondary') }) }) @@ -250,8 +250,8 @@ test.group('Model options | Model.find', (group) => { await db.insertQuery().table('users').insert({ username: 'virk' }) const user = await User.find(1, { connection: 'secondary' }) - assert.equal(user!.$options!.connection, 'secondary') - assert.instanceOf(user!.$options!.profiler, Profiler) + assert.equal(user!.options!.connection, 'secondary') + assert.instanceOf(user!.options!.profiler, Profiler) }) test('define custom profiler', async (assert) => { @@ -269,7 +269,7 @@ test.group('Model options | Model.find', (group) => { const profiler = new Profiler({}) const user = await User.find(1, { profiler }) - assert.deepEqual(user!.$options!.profiler, profiler) + assert.deepEqual(user!.options!.profiler, profiler) }) test('define custom query client', async (assert) => { @@ -287,8 +287,8 @@ test.group('Model options | Model.find', (group) => { const client = db.connection() const user = await User.find(1, { client }) - assert.deepEqual(user!.$options!.profiler, client.profiler) - assert.deepEqual(user!.$options!.connection, client.connectionName) + assert.deepEqual(user!.options!.profiler, client.profiler) + assert.deepEqual(user!.options!.connection, client.connectionName) }) }) @@ -322,8 +322,8 @@ test.group('Model options | Model.findOrFail', (group) => { await db.insertQuery().table('users').insert({ username: 'virk' }) const user = await User.findOrFail(1, { connection: 'secondary' }) - assert.equal(user.$options!.connection, 'secondary') - assert.instanceOf(user.$options!.profiler, Profiler) + assert.equal(user.options!.connection, 'secondary') + assert.instanceOf(user.options!.profiler, Profiler) }) test('define custom profiler', async (assert) => { @@ -342,7 +342,7 @@ test.group('Model options | Model.findOrFail', (group) => { const profiler = new Profiler({}) const user = await User.findOrFail(1, { profiler }) - assert.deepEqual(user.$options!.profiler, profiler) + assert.deepEqual(user.options!.profiler, profiler) }) test('define custom query client', async (assert) => { @@ -360,8 +360,8 @@ test.group('Model options | Model.findOrFail', (group) => { const client = db.connection('secondary') const user = await User.findOrFail(1, { client }) - assert.deepEqual(user.$options!.profiler, client.profiler) - assert.deepEqual(user.$options!.connection, client.connectionName) + assert.deepEqual(user.options!.profiler, client.profiler) + assert.deepEqual(user.options!.connection, client.connectionName) }) }) @@ -395,8 +395,8 @@ test.group('Model options | Model.findMany', (group) => { await db.insertQuery().table('users').insert({ username: 'virk' }) const users = await User.findMany([1], { connection: 'secondary' }) - assert.equal(users[0].$options!.connection, 'secondary') - assert.instanceOf(users[0].$options!.profiler, Profiler) + assert.equal(users[0].options!.connection, 'secondary') + assert.instanceOf(users[0].options!.profiler, Profiler) }) test('define custom profiler', async (assert) => { @@ -414,7 +414,7 @@ test.group('Model options | Model.findMany', (group) => { const profiler = new Profiler({}) const users = await User.findMany([1], { profiler }) - assert.deepEqual(users[0].$options!.profiler, profiler) + assert.deepEqual(users[0].options!.profiler, profiler) }) test('define custom query client', async (assert) => { @@ -432,8 +432,8 @@ test.group('Model options | Model.findMany', (group) => { const client = db.connection('secondary') const users = await User.findMany([1], { client }) - assert.deepEqual(users[0].$options!.profiler, client.profiler) - assert.deepEqual(users[0].$options!.connection, client.connectionName) + assert.deepEqual(users[0].options!.profiler, client.profiler) + assert.deepEqual(users[0].options!.connection, client.connectionName) }) }) @@ -470,8 +470,8 @@ test.group('Model options | Model.firstOrCreate', (group) => { const total = await db.from('users').count('*', 'total') assert.equal(total[0].total, 1) - assert.equal(user.$options!.connection, 'secondary') - assert.instanceOf(user.$options!.profiler, Profiler) + assert.equal(user.options!.connection, 'secondary') + assert.instanceOf(user.options!.profiler, Profiler) }) test('define custom connection when search fails', async (assert) => { @@ -491,8 +491,8 @@ test.group('Model options | Model.firstOrCreate', (group) => { const total = await db.from('users').count('*', 'total') assert.equal(total[0].total, 2) - assert.equal(user.$options!.connection, 'secondary') - assert.instanceOf(user.$options!.profiler, Profiler) + assert.equal(user.options!.connection, 'secondary') + assert.instanceOf(user.options!.profiler, Profiler) }) test('define custom profiler', async (assert) => { @@ -513,8 +513,8 @@ test.group('Model options | Model.firstOrCreate', (group) => { const total = await db.from('users').count('*', 'total') assert.equal(total[0].total, 1) - assert.equal(user.$options!.connection, 'primary') - assert.deepEqual(user.$options!.profiler, profiler) + assert.equal(user.options!.connection, 'primary') + assert.deepEqual(user.options!.profiler, profiler) }) test('define custom profiler when search fails', async (assert) => { @@ -535,7 +535,7 @@ test.group('Model options | Model.firstOrCreate', (group) => { const total = await db.from('users').count('*', 'total') assert.equal(total[0].total, 2) - assert.deepEqual(user.$options!.profiler, profiler) + assert.deepEqual(user.options!.profiler, profiler) }) test('define custom client', async (assert) => { @@ -556,8 +556,8 @@ test.group('Model options | Model.firstOrCreate', (group) => { const total = await db.from('users').count('*', 'total') assert.equal(total[0].total, 1) - assert.deepEqual(user.$options!.profiler, client.profiler) - assert.deepEqual(user.$options!.connection, client.connectionName) + assert.deepEqual(user.options!.profiler, client.profiler) + assert.deepEqual(user.options!.connection, client.connectionName) }) test('define custom client when search fails', async (assert) => { @@ -578,8 +578,8 @@ test.group('Model options | Model.firstOrCreate', (group) => { const total = await db.from('users').count('*', 'total') assert.equal(total[0].total, 2) - assert.deepEqual(user.$options!.profiler, client.profiler) - assert.deepEqual(user.$options!.connection, client.connectionName) + assert.deepEqual(user.options!.profiler, client.profiler) + assert.deepEqual(user.options!.connection, client.connectionName) }) test('use transaction', async (assert) => { @@ -602,8 +602,8 @@ test.group('Model options | Model.firstOrCreate', (group) => { const total = await db.from('users').count('*', 'total') assert.equal(total[0].total, 1) - assert.deepEqual(user.$options!.profiler, client.profiler) - assert.deepEqual(user.$options!.connection, client.connectionName) + assert.deepEqual(user.options!.profiler, client.profiler) + assert.deepEqual(user.options!.connection, client.connectionName) }) test('use transaction to save when search fails', async (assert) => { @@ -625,8 +625,8 @@ test.group('Model options | Model.firstOrCreate', (group) => { const total = await db.from('users').count('*', 'total') assert.equal(total[0].total, 0) - assert.deepEqual(user.$options!.profiler, client.profiler) - assert.deepEqual(user.$options!.connection, client.connectionName) + assert.deepEqual(user.options!.profiler, client.profiler) + assert.deepEqual(user.options!.connection, client.connectionName) }) }) @@ -668,8 +668,8 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { const total = await db.from('users').count('*', 'total') assert.equal(total[0].total, 1) - assert.equal(user.$options!.connection, 'secondary') - assert.instanceOf(user.$options!.profiler, Profiler) + assert.equal(user.options!.connection, 'secondary') + assert.instanceOf(user.options!.profiler, Profiler) }) test('define custom connection when search fails', async (assert) => { @@ -692,8 +692,8 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { const total = await db.from('users').count('*', 'total') assert.equal(total[0].total, 1) - assert.equal(user.$options!.connection, 'secondary') - assert.instanceOf(user.$options!.profiler, Profiler) + assert.equal(user.options!.connection, 'secondary') + assert.instanceOf(user.options!.profiler, Profiler) }) test('define custom profiler', async (assert) => { @@ -719,8 +719,8 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { const total = await db.from('users').count('*', 'total') assert.equal(total[0].total, 1) - assert.equal(user.$options!.connection, 'primary') - assert.deepEqual(user.$options!.profiler, profiler) + assert.equal(user.options!.connection, 'primary') + assert.deepEqual(user.options!.profiler, profiler) }) test('define custom profiler when search fails', async (assert) => { @@ -744,8 +744,8 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { const total = await db.from('users').count('*', 'total') assert.equal(total[0].total, 1) - assert.equal(user.$options!.connection, 'primary') - assert.deepEqual(user.$options!.profiler, profiler) + assert.equal(user.options!.connection, 'primary') + assert.deepEqual(user.options!.profiler, profiler) }) test('define custom client', async (assert) => { @@ -771,8 +771,8 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { const total = await db.from('users').count('*', 'total') assert.equal(total[0].total, 1) - assert.deepEqual(user.$options!.profiler, client.profiler) - assert.deepEqual(user.$options!.connection, client.connectionName) + assert.deepEqual(user.options!.profiler, client.profiler) + assert.deepEqual(user.options!.connection, client.connectionName) }) test('define custom client when search fails', async (assert) => { @@ -797,8 +797,8 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { const total = await db.from('users').count('*', 'total') assert.equal(total[0].total, 1) - assert.deepEqual(user.$options!.profiler, client.profiler) - assert.deepEqual(user.$options!.connection, client.connectionName) + assert.deepEqual(user.options!.profiler, client.profiler) + assert.deepEqual(user.options!.connection, client.connectionName) }) test('wrap create many calls inside a transaction', async (assert) => { @@ -946,11 +946,11 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { // const users = await User.query({ connection: 'secondary' }).preload('profile').exec() // assert.lengthOf(users, 1) -// assert.equal(users[0].$options!.connection, 'secondary') -// assert.instanceOf(users[0].$options!.profiler, Profiler) +// assert.equal(users[0].options!.connection, 'secondary') +// assert.instanceOf(users[0].options!.profiler, Profiler) -// assert.equal(users[0].profile.$options!.connection, 'secondary') -// assert.instanceOf(users[0].profile.$options!.profiler, Profiler) +// assert.equal(users[0].profile.options!.connection, 'secondary') +// assert.instanceOf(users[0].profile.options!.profiler, Profiler) // }) // test('use transaction client to execute preload queries', async (assert) => { @@ -985,11 +985,11 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { // assert.lengthOf(users, 1) -// assert.equal(users[0].$options!.connection, 'primary') -// assert.instanceOf(users[0].$options!.profiler, Profiler) +// assert.equal(users[0].options!.connection, 'primary') +// assert.instanceOf(users[0].options!.profiler, Profiler) -// assert.equal(users[0].profile.$options!.connection, 'primary') -// assert.instanceOf(users[0].profile.$options!.profiler, Profiler) +// assert.equal(users[0].profile.options!.connection, 'primary') +// assert.instanceOf(users[0].profile.options!.profiler, Profiler) // }) // test('pass profiler to preload models', async (assert) => { @@ -1023,11 +1023,11 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { // assert.lengthOf(users, 1) -// assert.equal(users[0].$options!.connection, 'primary') -// assert.deepEqual(users[0].$options!.profiler, profiler) +// assert.equal(users[0].options!.connection, 'primary') +// assert.deepEqual(users[0].options!.profiler, profiler) -// assert.equal(users[0].profile.$options!.connection, 'primary') -// assert.deepEqual(users[0].profile.$options!.profiler, profiler) +// assert.equal(users[0].profile.options!.connection, 'primary') +// assert.deepEqual(users[0].profile.options!.profiler, profiler) // }) // test('pass sideloaded data to preloads', async (assert) => { @@ -1060,7 +1060,7 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { // assert.lengthOf(users, 1) -// assert.equal(users[0].$options!.connection, 'primary') +// assert.equal(users[0].options!.connection, 'primary') // assert.deepEqual(users[0].$sideloaded, { id: 1 }) // assert.deepEqual(users[0].profile.$sideloaded, { id: 1 }) // }) @@ -1097,7 +1097,7 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { // assert.lengthOf(users, 1) -// assert.equal(users[0].$options!.connection, 'primary') +// assert.equal(users[0].options!.connection, 'primary') // assert.deepEqual(users[0].$sideloaded, { id: 1 }) // assert.deepEqual(users[0].profile.$sideloaded, { id: 2 }) // }) @@ -1230,12 +1230,12 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { // await db.insertQuery().table('profiles').insert({ user_id: 1, display_name: 'Virk' }) // const user = await User.query({ connection: 'secondary' }).firstOrFail() -// assert.equal(user.$options!.connection, 'secondary') +// assert.equal(user.options!.connection, 'secondary') // await user.preload('profile') -// assert.equal(user.profile.$options!.connection, 'secondary') -// assert.instanceOf(user.profile.$options!.profiler, Profiler) +// assert.equal(user.profile.options!.connection, 'secondary') +// assert.instanceOf(user.profile.options!.profiler, Profiler) // }) // test('pass profiler to preload models', async (assert) => { @@ -1267,13 +1267,13 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => { // const profiler = new Profiler({}) // const user = await User.query({ profiler }).firstOrFail() -// assert.equal(user.$options!.connection, 'primary') -// assert.deepEqual(user.$options!.profiler, profiler) +// assert.equal(user.options!.connection, 'primary') +// assert.deepEqual(user.options!.profiler, profiler) // await user.preload('profile') -// assert.equal(user.profile.$options!.connection, 'primary') -// assert.deepEqual(user.profile.$options!.profiler, profiler) +// assert.equal(user.profile.options!.connection, 'primary') +// assert.deepEqual(user.profile.options!.profiler, profiler) // }) // test('pass sideloaded data to preloads', async (assert) => { diff --git a/test/orm/base-model.spec.ts b/test/orm/base-model.spec.ts index 4b33a68e..ec242c57 100644 --- a/test/orm/base-model.spec.ts +++ b/test/orm/base-model.spec.ts @@ -45,13 +45,13 @@ test.group('Base model | boot', (group) => { public username: string } - User.$boot() - assert.equal(User.$table, 'users') + User.boot() + assert.equal(User.table, 'users') }) test('allow overriding table name', async (assert) => { class User extends BaseModel { - public static $table = 'my_users' + public static table = 'my_users' @column({ isPrimary: true }) public id: number @@ -60,8 +60,8 @@ test.group('Base model | boot', (group) => { public username: string } - User.$boot() - assert.equal(User.$table, 'my_users') + User.boot() + assert.equal(User.table, 'my_users') }) test('set increments to true by default', async (assert) => { @@ -73,13 +73,13 @@ test.group('Base model | boot', (group) => { public username: string } - User.$boot() - assert.isTrue(User.$increments) + User.boot() + assert.isTrue(User.increments) }) test('allow overriding increments', async (assert) => { class User extends BaseModel { - public static $increments = false + public static increments = false @column({ isPrimary: true }) public id: number @@ -88,15 +88,15 @@ test.group('Base model | boot', (group) => { public username: string } - User.$boot() - assert.isFalse(User.$increments) + User.boot() + assert.isFalse(User.increments) }) test('initiate all required static properties', async (assert) => { class User extends BaseModel { } - User.$boot() + User.boot() assert.deepEqual(mapToObj(User.$columns), {}) assert.deepEqual(mapToObj(User.$relations), {}) assert.deepEqual(mapToObj(User.$computed), {}) @@ -114,7 +114,7 @@ test.group('Base model | boot', (group) => { public userName: string } - User.$boot() + User.boot() assert.deepEqual(User.$refs, { id: 'id', userName: 'user_name' }) }) }) @@ -159,7 +159,7 @@ test.group('Base Model | getter-setters', (group) => { class User extends BaseModel { public username: string } - User.$boot() + User.boot() const user = new User() user.username = 'virk' @@ -199,7 +199,7 @@ test.group('Base Model | getter-setters', (group) => { public username = 'virk' } - User.$boot() + User.boot() const user = new User() assert.equal(user.username, 'virk') }) @@ -216,10 +216,10 @@ test.group('Base Model | getter-setters', (group) => { const user = new User() user.$attributes = { username: 'virk', id: 1 } - assert.deepEqual(user.$primaryKeyValue, 1) + assert.deepEqual(user.primaryKeyValue, 1) }) - test('invoke getter when accessing value using $primaryKeyValue', (assert) => { + test('invoke getter when accessing value using primaryKeyValue', (assert) => { class User extends BaseModel { @column({ isPrimary: true }) public get id () { @@ -233,7 +233,7 @@ test.group('Base Model | getter-setters', (group) => { const user = new User() user.$attributes = { username: 'virk', id: 1 } - assert.deepEqual(user.$primaryKeyValue, '1') + assert.deepEqual(user.primaryKeyValue, '1') }) test('invoke column serialize method when serializing model', (assert) => { @@ -277,8 +277,8 @@ test.group('Base Model | dirty', (group) => { const user = new User() user.username = 'virk' - assert.deepEqual(user.$dirty, { username: 'virk' }) - assert.isTrue(user.$isDirty) + assert.deepEqual(user.dirty, { username: 'virk' }) + assert.isTrue(user.isDirty) }) test('get empty object when model is not dirty', (assert) => { @@ -288,12 +288,13 @@ test.group('Base Model | dirty', (group) => { } const user = new User() - user.username = 'virk' + user.$attributes = { username: 'virk' } user.$original = { username: 'virk' } - user.$isPersisted = true - assert.deepEqual(user.$dirty, {}) - assert.isFalse(user.$isDirty) + user.isPersisted = true + + assert.deepEqual(user.dirty, {}) + assert.isFalse(user.isDirty) }) test('get empty object when model is not dirty with null values', (assert) => { @@ -306,10 +307,10 @@ test.group('Base Model | dirty', (group) => { user.$attributes = { username: null } user.$original = { username: null } - user.$isPersisted = true + user.isPersisted = true - assert.deepEqual(user.$dirty, {}) - assert.isFalse(user.$isDirty) + assert.deepEqual(user.dirty, {}) + assert.isFalse(user.isDirty) }) test('get empty object when model is not dirty with false values', (assert) => { @@ -322,10 +323,10 @@ test.group('Base Model | dirty', (group) => { user.$attributes = { username: false } user.$original = { username: false } - user.$isPersisted = true + user.isPersisted = true - assert.deepEqual(user.$dirty, {}) - assert.isFalse(user.$isDirty) + assert.deepEqual(user.dirty, {}) + assert.isFalse(user.isDirty) }) test('get values removed as a side-effect of fill as dirty', async (assert) => { @@ -344,12 +345,12 @@ test.group('Base Model | dirty', (group) => { user.age = 22 await user.save() - assert.deepEqual(user.$dirty, {}) - assert.isFalse(user.$isDirty) - assert.isTrue(user.$isPersisted) + assert.deepEqual(user.dirty, {}) + assert.isFalse(user.isDirty) + assert.isTrue(user.isPersisted) user.fill({ username: 'virk' }) - assert.deepEqual(user.$dirty, { age: null }) + assert.deepEqual(user.dirty, { age: null }) }) }) @@ -387,8 +388,8 @@ test.group('Base Model | persist', (group) => { user.fullName = 'H virk' await user.save() - assert.isTrue(user.$isPersisted) - assert.isFalse(user.$isDirty) + assert.isTrue(user.isPersisted) + assert.isFalse(user.isDirty) assert.deepEqual(adapter.operations, [{ type: 'insert', instance: user, @@ -419,8 +420,8 @@ test.group('Base Model | persist', (group) => { user.username = 'virk' await user.save() - assert.isTrue(user.$isPersisted) - assert.isFalse(user.$isDirty) + assert.isTrue(user.isPersisted) + assert.isFalse(user.isDirty) assert.deepEqual(adapter.operations, [{ type: 'insert', instance: user, @@ -448,8 +449,8 @@ test.group('Base Model | persist', (group) => { user.username = 'virk' await user.save() - assert.isTrue(user.$isPersisted) - assert.isFalse(user.$isDirty) + assert.isTrue(user.isPersisted) + assert.isFalse(user.isDirty) assert.deepEqual(adapter.operations, [{ type: 'insert', instance: user, @@ -472,11 +473,11 @@ test.group('Base Model | persist', (group) => { const user = new User() user.username = 'virk' - user.$isPersisted = true + user.isPersisted = true await user.save() - assert.isTrue(user.$isPersisted) - assert.isFalse(user.$isDirty) + assert.isTrue(user.isPersisted) + assert.isFalse(user.isDirty) assert.deepEqual(adapter.operations, [{ type: 'update', instance: user, @@ -506,11 +507,11 @@ test.group('Base Model | persist', (group) => { const user = new User() user.username = 'virk' - user.$isPersisted = true + user.isPersisted = true await user.save() - assert.isTrue(user.$isPersisted) - assert.isFalse(user.$isDirty) + assert.isTrue(user.isPersisted) + assert.isFalse(user.isDirty) assert.deepEqual(adapter.operations, [{ type: 'update', instance: user, @@ -535,11 +536,11 @@ test.group('Base Model | persist', (group) => { User.$adapter = adapter const user = new User() - user.$isPersisted = true + user.isPersisted = true await user.save() - assert.isTrue(user.$isPersisted) - assert.isFalse(user.$isDirty) + assert.isTrue(user.isPersisted) + assert.isFalse(user.isDirty) assert.deepEqual(adapter.operations, []) assert.deepEqual(user.$attributes, {}) assert.deepEqual(user.$original, {}) @@ -564,13 +565,13 @@ test.group('Base Model | persist', (group) => { user.username = 'virk' await user.save() - assert.isTrue(user.$isPersisted) - assert.isFalse(user.$isDirty) + assert.isTrue(user.isPersisted) + assert.isFalse(user.isDirty) assert.isUndefined(user.updatedAt) await user.refresh() - assert.isTrue(user.$isPersisted) - assert.isFalse(user.$isDirty) + assert.isTrue(user.isPersisted) + assert.isFalse(user.isDirty) assert.isDefined(user.updatedAt) }) @@ -595,8 +596,8 @@ test.group('Base Model | persist', (group) => { user.username = 'virk' await user.save() - assert.isTrue(user.$isPersisted) - assert.isFalse(user.$isDirty) + assert.isTrue(user.isPersisted) + assert.isFalse(user.isDirty) assert.isUndefined(user.updatedAt) await db.from('users').del() @@ -631,9 +632,9 @@ test.group('Base Model | create from adapter results', (group) => { const user = User.$createFromAdapterResult({ username: 'virk' }) user!.username = 'virk' - assert.isTrue(user!.$isPersisted) - assert.isFalse(user!.$isDirty) - assert.isFalse(user!.$isLocal) + assert.isTrue(user!.isPersisted) + assert.isFalse(user!.isDirty) + assert.isFalse(user!.isLocal) assert.deepEqual(user!.$attributes, { username: 'virk' }) assert.deepEqual(user!.$original, { username: 'virk' }) }) @@ -649,10 +650,10 @@ test.group('Base Model | create from adapter results', (group) => { const user = User.$createFromAdapterResult({ username: 'virk' }, [], { connection: 'foo' }) - assert.deepEqual(user!.$options, { connection: 'foo' }) - assert.isTrue(user!.$isPersisted) - assert.isFalse(user!.$isDirty) - assert.isFalse(user!.$isLocal) + assert.deepEqual(user!.options, { connection: 'foo' }) + assert.isTrue(user!.isPersisted) + assert.isFalse(user!.isDirty) + assert.isFalse(user!.isLocal) assert.deepEqual(user!.$attributes, { username: 'virk' }) assert.deepEqual(user!.$original, { username: 'virk' }) }) @@ -685,15 +686,15 @@ test.group('Base Model | create from adapter results', (group) => { ]) assert.lengthOf(users, 2) - assert.isTrue(users[0].$isPersisted) - assert.isFalse(users[0].$isDirty) - assert.isFalse(users[0].$isLocal) + assert.isTrue(users[0].isPersisted) + assert.isFalse(users[0].isDirty) + assert.isFalse(users[0].isLocal) assert.deepEqual(users[0].$attributes, { username: 'virk', fullName: 'H virk' }) assert.deepEqual(users[0].$original, { username: 'virk', fullName: 'H virk' }) - assert.isTrue(users[1].$isPersisted) - assert.isFalse(users[1].$isDirty) - assert.isFalse(users[1].$isLocal) + assert.isTrue(users[1].isPersisted) + assert.isFalse(users[1].isDirty) + assert.isFalse(users[1].isLocal) assert.deepEqual(users[1].$attributes, { username: 'prasan' }) assert.deepEqual(users[1].$original, { username: 'prasan' }) }) @@ -715,17 +716,17 @@ test.group('Base Model | create from adapter results', (group) => { assert.lengthOf(users, 2) - assert.isTrue(users[0].$isPersisted) - assert.isFalse(users[0].$isDirty) - assert.isFalse(users[0].$isLocal) - assert.deepEqual(users[0].$options, { connection: 'foo' }) + assert.isTrue(users[0].isPersisted) + assert.isFalse(users[0].isDirty) + assert.isFalse(users[0].isLocal) + assert.deepEqual(users[0].options, { connection: 'foo' }) assert.deepEqual(users[0].$attributes, { username: 'virk', fullName: 'H virk' }) assert.deepEqual(users[0].$original, { username: 'virk', fullName: 'H virk' }) - assert.isTrue(users[1].$isPersisted) - assert.isFalse(users[1].$isDirty) - assert.isFalse(users[1].$isLocal) - assert.deepEqual(users[1].$options, { connection: 'foo' }) + assert.isTrue(users[1].isPersisted) + assert.isFalse(users[1].isDirty) + assert.isFalse(users[1].isLocal) + assert.deepEqual(users[1].options, { connection: 'foo' }) assert.deepEqual(users[1].$attributes, { username: 'prasan' }) assert.deepEqual(users[1].$original, { username: 'prasan' }) }) @@ -745,9 +746,9 @@ test.group('Base Model | create from adapter results', (group) => { ) assert.lengthOf(users, 1) - assert.isTrue(users[0].$isPersisted) - assert.isFalse(users[0].$isDirty) - assert.isFalse(users[0].$isLocal) + assert.isTrue(users[0].isPersisted) + assert.isFalse(users[0].isDirty) + assert.isFalse(users[0].isLocal) assert.deepEqual(users[0].$attributes, { username: 'virk', fullName: 'H virk' }) assert.deepEqual(users[0].$original, { username: 'virk', fullName: 'H virk' }) }) @@ -780,7 +781,7 @@ test.group('Base Model | delete', (group) => { instance: user, }]) - assert.isTrue(user.$isDeleted) + assert.isTrue(user.isDeleted) }) test('raise exception when trying to mutate model after deletion', async (assert) => { @@ -1060,7 +1061,7 @@ test.group('Base | apdater', (group) => { User.$adapter = adapter const user = new User() user.username = 'virk' - user.$options = { connection: 'foo' } + user.options = { connection: 'foo' } await user.save() @@ -1082,7 +1083,7 @@ test.group('Base | apdater', (group) => { User.$adapter = adapter const user = new User() user.username = 'virk' - user.$options = { connection: 'foo' } + user.options = { connection: 'foo' } await user.save() @@ -1114,7 +1115,7 @@ test.group('Base | apdater', (group) => { User.$adapter = adapter const user = new User() user.username = 'virk' - user.$options = { connection: 'foo' } + user.options = { connection: 'foo' } await user.save() await user.delete() @@ -1175,7 +1176,7 @@ test.group('Base Model | sideloaded', (group) => { user.$consumeAdapterResult({ username: 'virk' }, { loggedInUser: { id: 1 } }) assert.deepEqual(user.$attributes, { username: 'virk' }) - assert.deepEqual(user.$sideloaded, { loggedInUser: { id: 1 } }) + assert.deepEqual(user.sideloaded, { loggedInUser: { id: 1 } }) }) test('define sideloaded properties using $createFromAdapterResult method', (assert) => { @@ -1186,7 +1187,7 @@ test.group('Base Model | sideloaded', (group) => { const user = User.$createFromAdapterResult({ username: 'virk' }, { loggedInUser: { id: 1 } })! assert.deepEqual(user.$attributes, { username: 'virk' }) - assert.deepEqual(user.$sideloaded, { loggedInUser: { id: 1 } }) + assert.deepEqual(user.sideloaded, { loggedInUser: { id: 1 } }) }) test('define sideloaded properties using $createMultipleFromAdapterResult method', (assert) => { @@ -1201,10 +1202,10 @@ test.group('Base Model | sideloaded', (group) => { ) assert.deepEqual(users[0].$attributes, { username: 'virk' }) - assert.deepEqual(users[0].$sideloaded, { loggedInUser: { id: 1 } }) + assert.deepEqual(users[0].sideloaded, { loggedInUser: { id: 1 } }) assert.deepEqual(users[1].$attributes, { username: 'nikk' }) - assert.deepEqual(users[1].$sideloaded, { loggedInUser: { id: 1 } }) + assert.deepEqual(users[1].sideloaded, { loggedInUser: { id: 1 } }) }) // @todo: PASS SIDELOADED PROPERTIES TO RELATIONSHIPS AS WELL @@ -1534,7 +1535,7 @@ test.group('Base Model | fetch', (group) => { const user = await User.find(1) assert.instanceOf(user, User) - assert.equal(user!.$primaryKeyValue, 1) + assert.equal(user!.primaryKeyValue, 1) }) test('raise exception when row is not found', async (assert) => { @@ -1576,8 +1577,8 @@ test.group('Base Model | fetch', (group) => { const users = await User.findMany([1, 2]) assert.lengthOf(users, 2) - assert.equal(users[0].$primaryKeyValue, 2) - assert.equal(users[1].$primaryKeyValue, 1) + assert.equal(users[0].primaryKeyValue, 2) + assert.equal(users[1].primaryKeyValue, 1) }) test('return the existing row when search criteria matches', async (assert) => { @@ -1598,9 +1599,9 @@ test.group('Base Model | fetch', (group) => { const totalUsers = await db.query().from('users').count('*', 'total') assert.equal(totalUsers[0].total, 1) - assert.isTrue(user.$isPersisted) + assert.isTrue(user.isPersisted) assert.instanceOf(user, User) - assert.equal(user!.$primaryKeyValue, 1) + assert.equal(user!.primaryKeyValue, 1) }) test('create new row when search criteria doesn\'t match', async (assert) => { @@ -1623,8 +1624,8 @@ test.group('Base Model | fetch', (group) => { assert.equal(totalUsers[0].total, 2) assert.instanceOf(user, User) - assert.equal(user!.$primaryKeyValue, 2) - assert.isTrue(user.$isPersisted) + assert.equal(user!.primaryKeyValue, 2) + assert.isTrue(user.isPersisted) assert.equal(user!.email, 'nikk@gmail.com') assert.equal(user!.userName, 'nikk') }) @@ -1648,8 +1649,8 @@ test.group('Base Model | fetch', (group) => { assert.equal(totalUsers[0].total, 1) assert.instanceOf(user, User) - assert.isTrue(user.$isPersisted) - assert.equal(user!.$primaryKeyValue, 1) + assert.isTrue(user.isPersisted) + assert.equal(user!.primaryKeyValue, 1) }) test('instantiate new row when search criteria doesn\'t match using firstOrNew', async (assert) => { @@ -1672,8 +1673,8 @@ test.group('Base Model | fetch', (group) => { assert.equal(totalUsers[0].total, 1) assert.instanceOf(user, User) - assert.isUndefined(user!.$primaryKeyValue) - assert.isFalse(user.$isPersisted) + assert.isUndefined(user!.primaryKeyValue) + assert.isFalse(user.isPersisted) assert.equal(user!.email, 'nikk@gmail.com') assert.equal(user!.userName, 'nikk') }) @@ -1695,7 +1696,7 @@ test.group('Base Model | fetch', (group) => { await db.insertQuery().table('users').insert({ username: 'virk' }) const user = await User.updateOrCreate({ userName: 'virk' }, { points: 20 }) - assert.isTrue(user.$isPersisted) + assert.isTrue(user.isPersisted) assert.equal(user.points, 20) assert.equal(user.userName, 'virk') @@ -1725,7 +1726,7 @@ test.group('Base Model | fetch', (group) => { const user = await User.updateOrCreate({ userName: 'virk' }, { points: 20 }, { client: trx }) - assert.isTrue(user.$isPersisted) + assert.isTrue(user.isPersisted) assert.equal(user.points, 20) assert.equal(user.userName, 'virk') @@ -1756,7 +1757,7 @@ test.group('Base Model | fetch', (group) => { await db.insertQuery().table('users').insert({ username: 'virk' }) const user = await User.updateOrCreate({ username: 'nikk' }, { points: 20 }) - assert.isTrue(user.$isPersisted) + assert.isTrue(user.isPersisted) assert.equal(user.points, 20) assert.equal(user.username, 'nikk') @@ -1790,7 +1791,7 @@ test.group('Base Model | fetch', (group) => { const user = await User.updateOrCreate({ username: 'nikk' }, { points: 20 }, { client: trx }) - assert.isTrue(user.$isPersisted) + assert.isTrue(user.isPersisted) assert.equal(user.points, 20) assert.equal(user.username, 'nikk') @@ -1837,15 +1838,15 @@ test.group('Base Model | fetch', (group) => { ) assert.lengthOf(users, 3) - assert.isTrue(users[0].$isPersisted) + assert.isTrue(users[0].isPersisted) assert.equal(users[0].username, 'virk') assert.equal(users[0].email, 'virk@adonisjs.com') - assert.isTrue(users[1].$isPersisted) + assert.isTrue(users[1].isPersisted) assert.equal(users[1].username, 'nikk') assert.equal(users[1].email, 'nikk@adonisjs.com') - assert.isTrue(users[2].$isPersisted) + assert.isTrue(users[2].isPersisted) assert.equal(users[2].username, 'romain') assert.equal(users[2].email, 'romain@adonisjs.com') @@ -1893,17 +1894,17 @@ test.group('Base Model | fetch', (group) => { ) assert.lengthOf(users, 3) - assert.isTrue(users[0].$isPersisted) + assert.isTrue(users[0].isPersisted) assert.equal(users[0].username, 'virk') assert.equal(users[0].email, 'virk@adonisjs.com') assert.equal(users[0].points, 10) - assert.isTrue(users[1].$isPersisted) + assert.isTrue(users[1].isPersisted) assert.equal(users[1].username, 'nikk') assert.equal(users[1].email, 'nikk@adonisjs.com') assert.isUndefined(users[1].points) - assert.isTrue(users[2].$isPersisted) + assert.isTrue(users[2].isPersisted) assert.equal(users[2].username, 'romain') assert.equal(users[2].email, 'romain@adonisjs.com') assert.isUndefined(users[2].points) @@ -2001,17 +2002,17 @@ test.group('Base Model | fetch', (group) => { ) assert.lengthOf(users, 3) - assert.isTrue(users[0].$isPersisted) + assert.isTrue(users[0].isPersisted) assert.equal(users[0].userName, 'virk') assert.equal(users[0].email, 'virk@adonisjs.com') assert.equal(users[0].points, 10) - assert.isTrue(users[1].$isPersisted) + assert.isTrue(users[1].isPersisted) assert.equal(users[1].userName, 'nikk') assert.equal(users[1].email, 'nikk@adonisjs.com') assert.isUndefined(users[1].points) - assert.isTrue(users[2].$isPersisted) + assert.isTrue(users[2].isPersisted) assert.equal(users[2].userName, 'romain') assert.equal(users[2].email, 'romain@adonisjs.com') assert.isUndefined(users[2].points) @@ -2190,15 +2191,15 @@ test.group('Base Model | fetch', (group) => { ) assert.lengthOf(users, 3) - assert.isTrue(users[0].$isPersisted) + assert.isTrue(users[0].isPersisted) assert.equal(users[0].username, 'virk') assert.equal(users[0].email, 'virk@adonisjs.com') - assert.isTrue(users[1].$isPersisted) + assert.isTrue(users[1].isPersisted) assert.equal(users[1].username, 'nikk') assert.equal(users[1].email, 'nikk@adonisjs.com') - assert.isTrue(users[2].$isPersisted) + assert.isTrue(users[2].isPersisted) assert.equal(users[2].username, 'romain') assert.equal(users[2].email, 'romain@adonisjs.com') @@ -2247,17 +2248,17 @@ test.group('Base Model | fetch', (group) => { ) assert.lengthOf(users, 3) - assert.isTrue(users[0].$isPersisted) + assert.isTrue(users[0].isPersisted) assert.equal(users[0].username, 'virk') assert.equal(users[0].email, 'virk@adonisjs.com') assert.equal(users[0].points, 4) - assert.isTrue(users[1].$isPersisted) + assert.isTrue(users[1].isPersisted) assert.equal(users[1].username, 'nikk') assert.equal(users[1].email, 'nikk@adonisjs.com') assert.isUndefined(users[1].points) - assert.isTrue(users[2].$isPersisted) + assert.isTrue(users[2].isPersisted) assert.equal(users[2].username, 'romain') assert.equal(users[2].email, 'romain@adonisjs.com') assert.isUndefined(users[2].points) @@ -2396,31 +2397,31 @@ test.group('Base Model | hooks', (group) => { @column() public email: string - public static $boot () { - if (this.$booted) { + public static boot () { + if (this.booted) { return } - super.$boot() + super.boot() - this.$before('create', (model) => { + this.before('create', (model) => { assert.instanceOf(model, User) - assert.isFalse(model.$isPersisted) + assert.isFalse(model.isPersisted) }) - this.$before('save', (model) => { + this.before('save', (model) => { assert.instanceOf(model, User) - assert.isFalse(model.$isPersisted) + assert.isFalse(model.isPersisted) }) - this.$after('create', (model) => { + this.after('create', (model) => { assert.instanceOf(model, User) - assert.isTrue(model.$isPersisted) + assert.isTrue(model.isPersisted) }) - this.$after('save', (model) => { + this.after('save', (model) => { assert.instanceOf(model, User) - assert.isTrue(model.$isPersisted) + assert.isTrue(model.isPersisted) }) } } @@ -2443,32 +2444,32 @@ test.group('Base Model | hooks', (group) => { @column() public email: string - public static $boot () { - if (this.$booted) { + public static boot () { + if (this.booted) { return } - super.$boot() + super.boot() - this.$before('create', (model) => { + this.before('create', (model) => { assert.instanceOf(model, User) - assert.isFalse(model.$isPersisted) + assert.isFalse(model.isPersisted) throw new Error('Wait') }) - this.$before('save', (model) => { + this.before('save', (model) => { assert.instanceOf(model, User) - assert.isFalse(model.$isPersisted) + assert.isFalse(model.isPersisted) }) - this.$after('create', (model) => { + this.after('create', (model) => { assert.instanceOf(model, User) - assert.isTrue(model.$isPersisted) + assert.isTrue(model.isPersisted) }) - this.$after('save', (model) => { + this.after('save', (model) => { assert.instanceOf(model, User) - assert.isTrue(model.$isPersisted) + assert.isTrue(model.isPersisted) }) } } @@ -2496,16 +2497,16 @@ test.group('Base Model | hooks', (group) => { @column() public email: string - public static $boot () { - if (this.$booted) { + public static boot () { + if (this.booted) { return } - super.$boot() + super.boot() - this.$after('save', (model) => { - if (model.$trx) { - model.$trx.on('commit', () => { + this.after('save', (model) => { + if (model.trx) { + model.trx.on('commit', () => { assert.isTrue(true) }) } @@ -2517,7 +2518,7 @@ test.group('Base Model | hooks', (group) => { const user = new User() user.username = 'virk' - user.$trx = trx + user.trx = trx await user.save() await trx.commit() @@ -2536,16 +2537,16 @@ test.group('Base Model | hooks', (group) => { @column() public email: string - public static $boot () { - if (this.$booted) { + public static boot () { + if (this.booted) { return } - super.$boot() + super.boot() - this.$after('save', (model) => { - if (model.$trx) { - model.$trx.on('rollback', () => { + this.after('save', (model) => { + if (model.trx) { + model.trx.on('rollback', () => { assert.isTrue(true) }) } @@ -2557,7 +2558,7 @@ test.group('Base Model | hooks', (group) => { const user = new User() user.username = 'virk' - user.$trx = trx + user.trx = trx await user.save() await trx.rollback() @@ -2576,31 +2577,31 @@ test.group('Base Model | hooks', (group) => { @column() public email: string - public static $boot () { - if (this.$booted) { + public static boot () { + if (this.booted) { return } - super.$boot() + super.boot() - this.$before('update', (model) => { + this.before('update', (model) => { assert.instanceOf(model, User) - assert.isTrue(model.$isDirty) + assert.isTrue(model.isDirty) }) - this.$before('save', (model) => { + this.before('save', (model) => { assert.instanceOf(model, User) - assert.isTrue(model.$isDirty) + assert.isTrue(model.isDirty) }) - this.$after('update', (model) => { + this.after('update', (model) => { assert.instanceOf(model, User) - assert.isFalse(model.$isDirty) + assert.isFalse(model.isDirty) }) - this.$after('save', (model) => { + this.after('save', (model) => { assert.instanceOf(model, User) - assert.isFalse(model.$isDirty) + assert.isFalse(model.isDirty) }) } } @@ -2629,32 +2630,32 @@ test.group('Base Model | hooks', (group) => { @column() public email: string - public static $boot () { - if (this.$booted) { + public static boot () { + if (this.booted) { return } - super.$boot() + super.boot() - this.$before('update', (model) => { + this.before('update', (model) => { assert.instanceOf(model, User) - assert.isTrue(model.$isDirty) + assert.isTrue(model.isDirty) throw new Error('Wait') }) - this.$before('save', (model) => { + this.before('save', (model) => { assert.instanceOf(model, User) - assert.isTrue(model.$isDirty) + assert.isTrue(model.isDirty) }) - this.$after('update', (model) => { + this.after('update', (model) => { assert.instanceOf(model, User) - assert.isFalse(model.$isDirty) + assert.isFalse(model.isDirty) }) - this.$after('save', (model) => { + this.after('save', (model) => { assert.instanceOf(model, User) - assert.isFalse(model.$isDirty) + assert.isFalse(model.isDirty) }) } } @@ -2688,18 +2689,18 @@ test.group('Base Model | hooks', (group) => { @column() public email: string - public static $boot () { - if (this.$booted) { + public static boot () { + if (this.booted) { return } - super.$boot() + super.boot() - this.$before('delete', (model) => { + this.before('delete', (model) => { assert.instanceOf(model, User) }) - this.$after('delete', (model) => { + this.after('delete', (model) => { assert.instanceOf(model, User) }) } @@ -2726,19 +2727,19 @@ test.group('Base Model | hooks', (group) => { @column() public email: string - public static $boot () { - if (this.$booted) { + public static boot () { + if (this.booted) { return } - super.$boot() + super.boot() - this.$before('delete', (model) => { + this.before('delete', (model) => { assert.instanceOf(model, User) throw new Error('Wait') }) - this.$after('delete', (model) => { + this.after('delete', (model) => { assert.instanceOf(model, User) }) } @@ -2776,7 +2777,7 @@ test.group('Base model | extend', (group) => { @column() public username: string } - User.$boot() + User.boot() db.ModelQueryBuilder.macro('whereActive', function () { this.where('is_active', true) @@ -2806,7 +2807,7 @@ test.group('Base model | extend', (group) => { return client.insertQuery().table('users').withId() } } - User.$boot() + User.boot() db.InsertQueryBuilder.macro('withId', function () { this.returning('id') diff --git a/test/orm/model-belongs-to.spec.ts b/test/orm/model-belongs-to.spec.ts index 53b9793d..058a913a 100644 --- a/test/orm/model-belongs-to.spec.ts +++ b/test/orm/model-belongs-to.spec.ts @@ -30,15 +30,15 @@ test.group('Model | BelongsTo | Options', (group) => { try { class User extends BaseModel { } - User.$boot() + User.boot() class Profile extends BaseModel { @belongsTo(() => User) public user: BelongsTo } - Profile.$boot() - Profile.$getRelation('user').$boot() + Profile.boot() + Profile.$getRelation('user').boot() } catch ({ message }) { assert.equal( message, @@ -56,15 +56,15 @@ test.group('Model | BelongsTo | Options', (group) => { public id: number } - User.$boot() + User.boot() class Profile extends BaseModel { @belongsTo(() => User) public user: BelongsTo } - Profile.$boot() - Profile.$getRelation('user').$boot() + Profile.boot() + Profile.$getRelation('user').boot() } catch ({ message }) { assert.equal( message, @@ -87,10 +87,10 @@ test.group('Model | BelongsTo | Options', (group) => { public user: BelongsTo } - Profile.$getRelation('user').$boot() + Profile.$getRelation('user').boot() - assert.equal(Profile.$getRelation('user')!['$localKey'], 'id') - assert.equal(Profile.$getRelation('user')!['$localCastAsKey'], 'id') + assert.equal(Profile.$getRelation('user')!['localKey'], 'id') + assert.equal(Profile.$getRelation('user')!['localCastAsKey'], 'id') }) test('use custom defined local key', (assert) => { @@ -110,10 +110,10 @@ test.group('Model | BelongsTo | Options', (group) => { public user: BelongsTo } - Profile.$getRelation('user').$boot() + Profile.$getRelation('user').boot() - assert.equal(Profile.$getRelation('user')!['$localKey'], 'uid') - assert.equal(Profile.$getRelation('user')!['$localCastAsKey'], 'user_uid') + assert.equal(Profile.$getRelation('user')!['localKey'], 'uid') + assert.equal(Profile.$getRelation('user')!['localCastAsKey'], 'user_uid') }) test('compute foreign key from model name and primary key', (assert) => { @@ -130,10 +130,10 @@ test.group('Model | BelongsTo | Options', (group) => { public user: BelongsTo } - Profile.$getRelation('user').$boot() + Profile.$getRelation('user').boot() - assert.equal(Profile.$getRelation('user')!['$foreignKey'], 'userId') - assert.equal(Profile.$getRelation('user')!['$foreignCastAsKey'], 'user_id') + assert.equal(Profile.$getRelation('user')!['foreignKey'], 'userId') + assert.equal(Profile.$getRelation('user')!['foreignCastAsKey'], 'user_id') }) test('use pre defined foreign key', (assert) => { @@ -150,10 +150,10 @@ test.group('Model | BelongsTo | Options', (group) => { public user: BelongsTo } - Profile.$getRelation('user').$boot() + Profile.$getRelation('user').boot() - assert.equal(Profile.$getRelation('user')!['$foreignKey'], 'userUid') - assert.equal(Profile.$getRelation('user')!['$foreignCastAsKey'], 'user_id') + assert.equal(Profile.$getRelation('user')!['foreignKey'], 'userUid') + assert.equal(Profile.$getRelation('user')!['foreignCastAsKey'], 'user_id') }) }) @@ -177,7 +177,7 @@ test.group('Model | BelongsTo | Set Relations', (group) => { public user: BelongsTo } - Profile.$getRelation('user').$boot() + Profile.$getRelation('user').boot() const user = new User() const profile = new Profile() @@ -200,7 +200,7 @@ test.group('Model | BelongsTo | Set Relations', (group) => { public user: BelongsTo } - Profile.$getRelation('user').$boot() + Profile.$getRelation('user').boot() const profile = new Profile() const user = new User() @@ -226,7 +226,7 @@ test.group('Model | BelongsTo | Set Relations', (group) => { public user: BelongsTo } - Profile.$getRelation('user').$boot() + Profile.$getRelation('user').boot() const profile = new Profile() profile.fill({ userId: 1 }) @@ -316,7 +316,7 @@ test.group('Model | BelongsTo | bulk operations', (group) => { ]) const profiles = await Profile.all() - Profile.$getRelation('user').$boot() + Profile.$getRelation('user').boot() const related = Profile.$getRelation('user').client(profiles, db.connection()) const { sql, bindings } = related.query().toSQL() @@ -383,7 +383,7 @@ test.group('Model | BelongsTo | bulk operations', (group) => { ]) const profiles = await Profile.all() - Profile.$getRelation('user').$boot() + Profile.$getRelation('user').boot() const now = new Date() const related = Profile.$getRelation('user').client(profiles, db.connection()) @@ -450,7 +450,7 @@ test.group('Model | BelongsTo | bulk operations', (group) => { ]) const profiles = await Profile.all() - Profile.$getRelation('user').$boot() + Profile.$getRelation('user').boot() const related = Profile.$getRelation('user').client(profiles, db.connection()) const { sql, bindings } = related.query().del().toSQL() @@ -500,7 +500,7 @@ test.group('Model | BelongsTo | preload', (group) => { await db.insertQuery().table('users').insert({ username: 'virk' }) await db.insertQuery().table('profiles').insert({ display_name: 'Hvirk', user_id: 1 }) - Profile.$boot() + Profile.boot() const profiles = await Profile.query().preload('user') assert.lengthOf(profiles, 1) @@ -534,7 +534,7 @@ test.group('Model | BelongsTo | preload', (group) => { }, ]) - Profile.$boot() + Profile.boot() const profiles = await Profile.query().preload('user') assert.lengthOf(profiles, 2) @@ -568,7 +568,7 @@ test.group('Model | BelongsTo | preload', (group) => { }, ]) - Profile.$boot() + Profile.boot() const profiles = await Profile.query().preload('user', (builder) => builder.where('username', 'foo')) assert.lengthOf(profiles, 2) @@ -605,7 +605,7 @@ test.group('Model | BelongsTo | preload', (group) => { }, ]) - Profile.$boot() + Profile.boot() const profiles = await Profile.query().preload('user', (builder) => { return builder.select('username') @@ -645,7 +645,7 @@ test.group('Model | BelongsTo | preload', (group) => { }, ]) - Profile.$boot() + Profile.boot() const profiles = await Profile.query().preload('user', (builder) => { return builder.select('username', 'id') @@ -687,7 +687,7 @@ test.group('Model | BelongsTo | preload', (group) => { }, ]) - Profile.$boot() + Profile.boot() try { await Profile.query().select('display_name').preload('user') @@ -934,9 +934,9 @@ test.group('Model | BelongsTo | preload', (group) => { assert.instanceOf(identity!.profile, Profile) assert.instanceOf(identity!.profile!.user, User) - assert.equal(identity!.$options!.connection, 'secondary') - assert.equal(identity!.profile.$options!.connection, 'secondary') - assert.equal(identity!.profile.user.$options!.connection, 'secondary') + assert.equal(identity!.options!.connection, 'secondary') + assert.equal(identity!.profile.options!.connection, 'secondary') + assert.equal(identity!.profile.user.options!.connection, 'secondary') }) test('pass relationship metadata to the profiler', async (assert) => { @@ -960,7 +960,11 @@ test.group('Model | BelongsTo | preload', (group) => { let profilerPacketIndex = 0 profiler.subscribe((packet) => { if (profilerPacketIndex === 1) { - assert.deepEqual(packet.data.relation, { model: 'Profile', relatedModel: 'User', relation: 'belongsTo' }) + assert.deepEqual(packet.data.relation, { + model: 'Profile', + relatedModel: 'User', + relation: 'belongsTo', + }) } profilerPacketIndex++ }) @@ -1015,7 +1019,7 @@ test.group('Model | BelongsTo | persist', (group) => { await profile.related('user').associate(user) - assert.isTrue(profile.$isPersisted) + assert.isTrue(profile.isPersisted) assert.equal(user.id, profile.userId) const profiles = await db.query().from('profiles') @@ -1049,7 +1053,7 @@ test.group('Model | BelongsTo | persist', (group) => { const profile = await Profile.query().first() await profile!.related('user').dissociate() - assert.isTrue(profile!.$isPersisted) + assert.isTrue(profile!.isPersisted) assert.isNull(profile!.userId) const profiles = await db.query().from('profiles') diff --git a/test/orm/model-has-many-through.spec.ts b/test/orm/model-has-many-through.spec.ts index d387bc9e..7d4fd50f 100644 --- a/test/orm/model-has-many-through.spec.ts +++ b/test/orm/model-has-many-through.spec.ts @@ -30,19 +30,19 @@ test.group('Model | Has Many Through | Options', (group) => { try { class User extends BaseModel { } - User.$boot() + User.boot() class Post extends BaseModel { } - Post.$boot() + Post.boot() class Country extends BaseModel { @hasManyThrough([() => Post, () => User]) public posts: HasManyThrough } - Country.$boot() + Country.boot() - Country.$getRelation('posts').$boot() + Country.$getRelation('posts').boot() } catch ({ message }) { assert.equal( message, @@ -57,11 +57,11 @@ test.group('Model | Has Many Through | Options', (group) => { try { class User extends BaseModel { } - User.$boot() + User.boot() class Post extends BaseModel { } - Post.$boot() + Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) @@ -70,9 +70,9 @@ test.group('Model | Has Many Through | Options', (group) => { @hasManyThrough([() => Post, () => User]) public posts: HasManyThrough } - Country.$boot() + Country.boot() - Country.$getRelation('posts').$boot() + Country.$getRelation('posts').boot() } catch ({ message }) { assert.equal( message, @@ -89,11 +89,11 @@ test.group('Model | Has Many Through | Options', (group) => { @column() public countryId: number } - User.$boot() + User.boot() class Post extends BaseModel { } - Post.$boot() + Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) @@ -102,9 +102,9 @@ test.group('Model | Has Many Through | Options', (group) => { @hasManyThrough([() => Post, () => User]) public posts: HasManyThrough } - Country.$boot() + Country.boot() - Country.$getRelation('posts').$boot() + Country.$getRelation('posts').boot() } catch ({ message }) { assert.equal( message, @@ -124,11 +124,11 @@ test.group('Model | Has Many Through | Options', (group) => { @column() public countryId: number } - User.$boot() + User.boot() class Post extends BaseModel { } - Post.$boot() + Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) @@ -137,9 +137,9 @@ test.group('Model | Has Many Through | Options', (group) => { @hasManyThrough([() => Post, () => User]) public posts: HasManyThrough } - Country.$boot() + Country.boot() - Country.$getRelation('posts').$boot() + Country.$getRelation('posts').boot() } catch ({ message }) { assert.equal( message, @@ -156,13 +156,13 @@ test.group('Model | Has Many Through | Options', (group) => { @column() public countryId: number } - User.$boot() + User.boot() class Post extends BaseModel { @column() public userId: number } - Post.$boot() + Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) @@ -172,22 +172,22 @@ test.group('Model | Has Many Through | Options', (group) => { public posts: HasManyThrough } - Country.$boot() + Country.boot() const relation = Country.$getRelation('posts') - relation.$boot() + relation.boot() - assert.equal(relation['$localKey'], 'id') - assert.equal(relation['$localCastAsKey'], 'id') + assert.equal(relation['localKey'], 'id') + assert.equal(relation['localCastAsKey'], 'id') - assert.equal(relation['$foreignKey'], 'countryId') - assert.equal(relation['$foreignCastAsKey'], 'country_id') + assert.equal(relation['foreignKey'], 'countryId') + assert.equal(relation['foreignCastAsKey'], 'country_id') - assert.equal(relation['$throughLocalKey'], 'id') - assert.equal(relation['$throughLocalCastAsKey'], 'id') + assert.equal(relation['throughLocalKey'], 'id') + assert.equal(relation['throughLocalCastAsKey'], 'id') - assert.equal(relation['$throughForeignKey'], 'userId') - assert.equal(relation['$throughForeignCastAsKey'], 'user_id') + assert.equal(relation['throughForeignKey'], 'userId') + assert.equal(relation['throughForeignCastAsKey'], 'user_id') }) test('compute custom keys', (assert) => { @@ -198,13 +198,13 @@ test.group('Model | Has Many Through | Options', (group) => { @column() public countryUid: number } - User.$boot() + User.boot() class Post extends BaseModel { @column() public userUid: number } - Post.$boot() + Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) @@ -219,22 +219,22 @@ test.group('Model | Has Many Through | Options', (group) => { public posts: HasManyThrough } - Country.$boot() + Country.boot() const relation = Country.$getRelation('posts') - relation.$boot() + relation.boot() - assert.equal(relation['$localKey'], 'uid') - assert.equal(relation['$localCastAsKey'], 'uid') + assert.equal(relation['localKey'], 'uid') + assert.equal(relation['localCastAsKey'], 'uid') - assert.equal(relation['$foreignKey'], 'countryUid') - assert.equal(relation['$foreignCastAsKey'], 'country_uid') + assert.equal(relation['foreignKey'], 'countryUid') + assert.equal(relation['foreignCastAsKey'], 'country_uid') - assert.equal(relation['$throughLocalKey'], 'uid') - assert.equal(relation['$throughLocalCastAsKey'], 'uid') + assert.equal(relation['throughLocalKey'], 'uid') + assert.equal(relation['throughLocalCastAsKey'], 'uid') - assert.equal(relation['$throughForeignKey'], 'userUid') - assert.equal(relation['$throughForeignCastAsKey'], 'user_uid') + assert.equal(relation['throughForeignKey'], 'userUid') + assert.equal(relation['throughForeignCastAsKey'], 'user_uid') }) }) @@ -252,13 +252,13 @@ test.group('Model | Has Many Through | Set Relations', (group) => { @column() public countryId: number } - User.$boot() + User.boot() class Post extends BaseModel { @column() public userId: number } - Post.$boot() + Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) @@ -268,8 +268,8 @@ test.group('Model | Has Many Through | Set Relations', (group) => { public posts: HasManyThrough } - Country.$boot() - Country.$getRelation('posts').$boot() + Country.boot() + Country.$getRelation('posts').boot() const country = new Country() const post = new Post() @@ -286,13 +286,13 @@ test.group('Model | Has Many Through | Set Relations', (group) => { @column() public countryId: number } - User.$boot() + User.boot() class Post extends BaseModel { @column() public userId: number } - Post.$boot() + Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) @@ -302,8 +302,8 @@ test.group('Model | Has Many Through | Set Relations', (group) => { public posts: HasManyThrough } - Country.$boot() - Country.$getRelation('posts').$boot() + Country.boot() + Country.$getRelation('posts').boot() const country = new Country() const post = new Post() @@ -322,13 +322,13 @@ test.group('Model | Has Many Through | Set Relations', (group) => { @column() public countryId: number } - User.$boot() + User.boot() class Post extends BaseModel { @column() public userId: number } - Post.$boot() + Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) @@ -338,8 +338,8 @@ test.group('Model | Has Many Through | Set Relations', (group) => { public posts: HasManyThrough } - Country.$boot() - Country.$getRelation('posts').$boot() + Country.boot() + Country.$getRelation('posts').boot() const country = new Country() country.fill({ id: 1 }) @@ -399,13 +399,13 @@ test.group('Model | Has Many Through | bulk operations', (group) => { @column() public countryId: number } - User.$boot() + User.boot() class Post extends BaseModel { @column() public userId: number } - Post.$boot() + Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) @@ -415,7 +415,7 @@ test.group('Model | Has Many Through | bulk operations', (group) => { public posts: HasManyThrough } - Country.$boot() + Country.boot() await db.table('countries').insert({ name: 'India' }) const country = await Country.find(1) @@ -441,13 +441,13 @@ test.group('Model | Has Many Through | bulk operations', (group) => { @column() public countryId: number } - User.$boot() + User.boot() class Post extends BaseModel { @column() public userId: number } - Post.$boot() + Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) @@ -457,14 +457,14 @@ test.group('Model | Has Many Through | bulk operations', (group) => { public posts: HasManyThrough } - Country.$boot() + Country.boot() await db.table('countries').multiInsert([ { name: 'India' }, { name: 'UK' }, ]) const countries = await Country.all() - Country.$getRelation('posts').$boot() + Country.$getRelation('posts').boot() const related = Country.$getRelation('posts').client(countries, db.connection()) const { sql, bindings } = related.query().toSQL() @@ -489,13 +489,13 @@ test.group('Model | Has Many Through | bulk operations', (group) => { @column() public countryId: number } - User.$boot() + User.boot() class Post extends BaseModel { @column() public userId: number } - Post.$boot() + Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) @@ -505,7 +505,7 @@ test.group('Model | Has Many Through | bulk operations', (group) => { public posts: HasManyThrough } - Country.$boot() + Country.boot() await db.table('countries').insert({ name: 'India' }) const country = await Country.find(1) @@ -536,13 +536,13 @@ test.group('Model | Has Many Through | bulk operations', (group) => { @column() public countryId: number } - User.$boot() + User.boot() class Post extends BaseModel { @column() public userId: number } - Post.$boot() + Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) @@ -552,14 +552,14 @@ test.group('Model | Has Many Through | bulk operations', (group) => { public posts: HasManyThrough } - Country.$boot() + Country.boot() await db.table('countries').multiInsert([ { name: 'India' }, { name: 'UK' }, ]) const countries = await Country.all() - Country.$getRelation('posts').$boot() + Country.$getRelation('posts').boot() const now = new Date() const related = Country.$getRelation('posts').client(countries, db.connection()) @@ -588,13 +588,13 @@ test.group('Model | Has Many Through | bulk operations', (group) => { @column() public countryId: number } - User.$boot() + User.boot() class Post extends BaseModel { @column() public userId: number } - Post.$boot() + Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) @@ -604,7 +604,7 @@ test.group('Model | Has Many Through | bulk operations', (group) => { public posts: HasManyThrough } - Country.$boot() + Country.boot() await db.table('countries').insert({ name: 'India' }) const country = await Country.find(1) @@ -631,13 +631,13 @@ test.group('Model | Has Many Through | bulk operations', (group) => { @column() public countryId: number } - User.$boot() + User.boot() class Post extends BaseModel { @column() public userId: number } - Post.$boot() + Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) @@ -647,14 +647,14 @@ test.group('Model | Has Many Through | bulk operations', (group) => { public posts: HasManyThrough } - Country.$boot() + Country.boot() await db.table('countries').multiInsert([ { name: 'India' }, { name: 'UK' }, ]) const countries = await Country.all() - Country.$getRelation('posts').$boot() + Country.$getRelation('posts').boot() const related = Country.$getRelation('posts').client(countries, db.connection()) @@ -697,7 +697,7 @@ test.group('Model | Has Many Through | preload', (group) => { @column() public countryId: number } - User.$boot() + User.boot() class Post extends BaseModel { @column({ isPrimary: true }) @@ -709,7 +709,7 @@ test.group('Model | Has Many Through | preload', (group) => { @column() public title: string } - Post.$boot() + Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) @@ -718,7 +718,7 @@ test.group('Model | Has Many Through | preload', (group) => { @hasManyThrough([() => Post, () => User]) public posts: HasManyThrough } - Country.$boot() + Country.boot() await db.insertQuery().table('countries').insert([{ name: 'India' }]) @@ -754,7 +754,7 @@ test.group('Model | Has Many Through | preload', (group) => { @column() public countryId: number } - User.$boot() + User.boot() class Post extends BaseModel { @column({ isPrimary: true }) @@ -766,7 +766,7 @@ test.group('Model | Has Many Through | preload', (group) => { @column() public title: string } - Post.$boot() + Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) @@ -775,7 +775,7 @@ test.group('Model | Has Many Through | preload', (group) => { @hasManyThrough([() => Post, () => User]) public posts: HasManyThrough } - Country.$boot() + Country.boot() await db.insertQuery().table('countries').insert([{ name: 'India' }, { name: 'USA' }]) @@ -813,7 +813,7 @@ test.group('Model | Has Many Through | preload', (group) => { @column() public countryId: number } - User.$boot() + User.boot() class Post extends BaseModel { @column({ isPrimary: true }) @@ -825,7 +825,7 @@ test.group('Model | Has Many Through | preload', (group) => { @column() public title: string } - Post.$boot() + Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) @@ -834,7 +834,7 @@ test.group('Model | Has Many Through | preload', (group) => { @hasManyThrough([() => Post, () => User]) public posts: HasManyThrough } - Country.$boot() + Country.boot() await db.insertQuery().table('countries').insert([{ name: 'India' }, { name: 'USA' }]) @@ -876,7 +876,7 @@ test.group('Model | Has Many Through | preload', (group) => { @column() public countryId: number } - User.$boot() + User.boot() class Post extends BaseModel { @column({ isPrimary: true }) @@ -888,7 +888,7 @@ test.group('Model | Has Many Through | preload', (group) => { @column() public title: string } - Post.$boot() + Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) @@ -897,7 +897,7 @@ test.group('Model | Has Many Through | preload', (group) => { @hasManyThrough([() => Post, () => User]) public posts: HasManyThrough } - Country.$boot() + Country.boot() await db.insertQuery().table('countries').insert([{ name: 'India' }, { name: 'USA' }]) @@ -938,7 +938,7 @@ test.group('Model | Has Many Through | preload', (group) => { @column() public countryId: number } - User.$boot() + User.boot() class Post extends BaseModel { @column({ isPrimary: true }) @@ -950,7 +950,7 @@ test.group('Model | Has Many Through | preload', (group) => { @column() public title: string } - Post.$boot() + Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) @@ -959,7 +959,7 @@ test.group('Model | Has Many Through | preload', (group) => { @hasManyThrough([() => Post, () => User]) public posts: HasManyThrough } - Country.$boot() + Country.boot() await db.insertQuery().table('countries').insert([{ name: 'India' }, { name: 'USA' }]) @@ -981,7 +981,7 @@ test.group('Model | Has Many Through | preload', (group) => { } }) - test('preload through relationships', async (assert) => { + test('pass relationship metadata to the profiler', async (assert) => { assert.plan(1) class User extends BaseModel { @@ -991,7 +991,7 @@ test.group('Model | Has Many Through | preload', (group) => { @column() public countryId: number } - User.$boot() + User.boot() class Post extends BaseModel { @column({ isPrimary: true }) @@ -1003,7 +1003,7 @@ test.group('Model | Has Many Through | preload', (group) => { @column() public title: string } - Post.$boot() + Post.boot() class Country extends BaseModel { @column({ isPrimary: true }) @@ -1012,7 +1012,7 @@ test.group('Model | Has Many Through | preload', (group) => { @hasManyThrough([() => Post, () => User]) public posts: HasManyThrough } - Country.$boot() + Country.boot() await db.insertQuery().table('countries').insert([{ name: 'India' }]) diff --git a/test/orm/model-has-many.spec.ts b/test/orm/model-has-many.spec.ts index fad0b18b..a21140ba 100644 --- a/test/orm/model-has-many.spec.ts +++ b/test/orm/model-has-many.spec.ts @@ -36,8 +36,8 @@ test.group('Model | HasMany | Options', (group) => { public posts: HasMany } - User.$boot() - User.$getRelation('posts').$boot() + User.boot() + User.$getRelation('posts').boot() } catch ({ message }) { assert.equal( message, @@ -52,7 +52,7 @@ test.group('Model | HasMany | Options', (group) => { try { class Post extends BaseModel { } - Post.$boot() + Post.boot() class User extends BaseModel { @column({ isPrimary: true }) @@ -62,8 +62,8 @@ test.group('Model | HasMany | Options', (group) => { public posts: HasMany } - User.$boot() - User.$getRelation('posts').$boot() + User.boot() + User.$getRelation('posts').boot() } catch ({ message }) { assert.equal( message, @@ -86,11 +86,11 @@ test.group('Model | HasMany | Options', (group) => { public posts: HasMany } - User.$boot() - User.$getRelation('posts').$boot() + User.boot() + User.$getRelation('posts').boot() - assert.equal(User.$getRelation('posts')!['$localKey'], 'id') - assert.equal(User.$getRelation('posts')!['$localCastAsKey'], 'id') + assert.equal(User.$getRelation('posts')!['localKey'], 'id') + assert.equal(User.$getRelation('posts')!['localCastAsKey'], 'id') }) test('use custom defined primary key', (assert) => { @@ -110,11 +110,11 @@ test.group('Model | HasMany | Options', (group) => { public posts: HasMany } - User.$boot() - User.$getRelation('posts').$boot() + User.boot() + User.$getRelation('posts').boot() - assert.equal(User.$getRelation('posts')!['$localKey'], 'uid') - assert.equal(User.$getRelation('posts')!['$localCastAsKey'], 'user_uid') + assert.equal(User.$getRelation('posts')!['localKey'], 'uid') + assert.equal(User.$getRelation('posts')!['localCastAsKey'], 'user_uid') }) test('compute foreign key from model name and primary key', (assert) => { @@ -131,11 +131,11 @@ test.group('Model | HasMany | Options', (group) => { public posts: HasMany } - User.$boot() - User.$getRelation('posts').$boot() + User.boot() + User.$getRelation('posts').boot() - assert.equal(User.$getRelation('posts')!['$foreignKey'], 'userId') - assert.equal(User.$getRelation('posts')!['$foreignCastAsKey'], 'user_id') + assert.equal(User.$getRelation('posts')!['foreignKey'], 'userId') + assert.equal(User.$getRelation('posts')!['foreignCastAsKey'], 'user_id') }) test('use pre defined foreign key', (assert) => { @@ -152,11 +152,11 @@ test.group('Model | HasMany | Options', (group) => { public posts: HasMany } - User.$boot() - User.$getRelation('posts').$boot() + User.boot() + User.$getRelation('posts').boot() - assert.equal(User.$getRelation('posts')!['$foreignKey'], 'userUid') - assert.equal(User.$getRelation('posts')!['$foreignCastAsKey'], 'user_id') + assert.equal(User.$getRelation('posts')!['foreignKey'], 'userUid') + assert.equal(User.$getRelation('posts')!['foreignCastAsKey'], 'user_id') }) }) @@ -180,8 +180,8 @@ test.group('Model | HasMany | Set Relations', (group) => { public posts: HasMany } - User.$boot() - User.$getRelation('posts').$boot() + User.boot() + User.$getRelation('posts').boot() const user = new User() const post = new Post() @@ -203,8 +203,8 @@ test.group('Model | HasMany | Set Relations', (group) => { public posts: HasMany } - User.$boot() - User.$getRelation('posts').$boot() + User.boot() + User.$getRelation('posts').boot() const user = new User() const post = new Post() @@ -230,8 +230,8 @@ test.group('Model | HasMany | Set Relations', (group) => { public posts: HasMany } - User.$boot() - User.$getRelation('posts').$boot() + User.boot() + User.$getRelation('posts').boot() const user = new User() user.fill({ id: 1 }) @@ -288,8 +288,8 @@ test.group('Model | HasMany | bulk operations', (group) => { public posts: HasMany } - User.$boot() - User.$getRelation('posts').$boot() + User.boot() + User.$getRelation('posts').boot() await db.table('users').insert({ username: 'virk' }) @@ -320,8 +320,8 @@ test.group('Model | HasMany | bulk operations', (group) => { public posts: HasMany } - User.$boot() - User.$getRelation('posts').$boot() + User.boot() + User.$getRelation('posts').boot() await db.table('users').multiInsert([ { username: 'virk' }, @@ -357,8 +357,8 @@ test.group('Model | HasMany | bulk operations', (group) => { public posts: HasMany } - User.$boot() - User.$getRelation('posts').$boot() + User.boot() + User.$getRelation('posts').boot() await db.table('users').insert({ username: 'virk' }) @@ -398,7 +398,7 @@ test.group('Model | HasMany | bulk operations', (group) => { ]) const users = await User.all() - User.$getRelation('posts').$boot() + User.$getRelation('posts').boot() const now = new Date() const related = User.$getRelation('posts').client(users, db.connection()) @@ -465,7 +465,7 @@ test.group('Model | HasMany | bulk operations', (group) => { ]) const users = await User.all() - User.$getRelation('posts').$boot() + User.$getRelation('posts').boot() const related = User.$getRelation('posts').client(users, db.connection()) const { sql, bindings } = related.query().del().toSQL() @@ -526,7 +526,7 @@ test.group('Model | HasMany | preload', (group) => { }, ]) - User.$boot() + User.boot() const users = await User.query().preload('posts') assert.lengthOf(users, 2) @@ -571,7 +571,7 @@ test.group('Model | HasMany | preload', (group) => { }, ]) - User.$boot() + User.boot() const users = await User.query().preload('posts') assert.lengthOf(users[0]!.posts, 2) @@ -621,7 +621,7 @@ test.group('Model | HasMany | preload', (group) => { }, ]) - User.$boot() + User.boot() const users = await User.query().preload('posts', (builder) => builder.where('title', 'Lucid 101')) assert.lengthOf(users, 2) @@ -667,7 +667,7 @@ test.group('Model | HasMany | preload', (group) => { }, ]) - User.$boot() + User.boot() const users = await User.query().preload('posts', (builder) => { return builder.select('title') @@ -714,7 +714,7 @@ test.group('Model | HasMany | preload', (group) => { }, ]) - User.$boot() + User.boot() const users = await User.query().preload('posts', (builder) => { return builder.select('title', 'user_id') @@ -979,9 +979,9 @@ test.group('Model | HasMany | preload', (group) => { assert.lengthOf(user!.posts[0].comments, 1) assert.equal(user!.posts[0].comments[0].postId, user!.posts[0].id) - assert.equal(user!.$options!.connection, 'secondary') - assert.equal(user!.posts[0].$options!.connection, 'secondary') - assert.equal(user!.posts[0].comments[0].$options!.connection, 'secondary') + assert.equal(user!.options!.connection, 'secondary') + assert.equal(user!.posts[0].options!.connection, 'secondary') + assert.equal(user!.posts[0].comments[0].options!.connection, 'secondary') }) test('pass relationship metadata to the profiler', async (assert) => { @@ -1024,7 +1024,7 @@ test.group('Model | HasMany | preload', (group) => { profilerPacketIndex++ }) - User.$boot() + User.boot() await User.query({ profiler }).preload('posts') }) }) @@ -1077,7 +1077,7 @@ test.group('Model | HasMany | persist', (group) => { await user.related('posts').save(post) - assert.isTrue(post.$isPersisted) + assert.isTrue(post.isPersisted) assert.equal(user.id, post.userId) const totalUsers = await db.query().from('users').count('*', 'total') @@ -1122,10 +1122,10 @@ test.group('Model | HasMany | persist', (group) => { await user.related('posts').saveMany([post, post1]) - assert.isTrue(post.$isPersisted) + assert.isTrue(post.isPersisted) assert.equal(user.id, post.userId) - assert.isTrue(post1.$isPersisted) + assert.isTrue(post1.isPersisted) assert.equal(user.id, post1.userId) const totalUsers = await db.query().from('users').count('*', 'total') @@ -1179,9 +1179,9 @@ test.group('Model | HasMany | persist', (group) => { assert.equal(totalUsers[0].total, 1) assert.equal(totalPosts[0].total, 0) - assert.isUndefined(user.$trx) - assert.isUndefined(post.$trx) - assert.isUndefined(post1.$trx) + assert.isUndefined(user.trx) + assert.isUndefined(post.trx) + assert.isUndefined(post1.trx) }) test('wrap save many calls inside a save point when parent is in transaction', async (assert) => { @@ -1209,14 +1209,14 @@ test.group('Model | HasMany | persist', (group) => { const trx = await db.transaction() const user = new User() - user.$trx = trx + user.trx = trx user.username = 'virk' const post = new Post() post.title = 'Adonis 101' await user.related('posts').saveMany([post]) - assert.isFalse(user.$trx.isCompleted) + assert.isFalse(user.trx.isCompleted) await trx.rollback() const totalUsers = await db.query().from('users').count('*', 'total') @@ -1224,8 +1224,8 @@ test.group('Model | HasMany | persist', (group) => { assert.equal(totalUsers[0].total, 0) assert.equal(totalPosts[0].total, 0) - assert.isUndefined(user.$trx) - assert.isUndefined(post.$trx) + assert.isUndefined(user.trx) + assert.isUndefined(post.trx) }) test('create related instance', async (assert) => { @@ -1257,7 +1257,7 @@ test.group('Model | HasMany | persist', (group) => { const post = await user.related('posts').create({ title: 'Adonis 101' }) - assert.isTrue(post.$isPersisted) + assert.isTrue(post.isPersisted) assert.equal(user.id, post.userId) const totalUsers = await db.query().from('users').count('*', 'total') @@ -1303,10 +1303,10 @@ test.group('Model | HasMany | persist', (group) => { }, ]) - assert.isTrue(post.$isPersisted) + assert.isTrue(post.isPersisted) assert.equal(user.id, post.userId) - assert.isTrue(post1.$isPersisted) + assert.isTrue(post1.isPersisted) assert.equal(user.id, post1.userId) const totalUsers = await db.query().from('users').count('*', 'total') @@ -1355,7 +1355,7 @@ test.group('Model | HasMany | persist', (group) => { assert.equal(totalUsers[0].total, 1) assert.equal(totalPosts[0].total, 0) - assert.isUndefined(user.$trx) + assert.isUndefined(user.trx) }) test('wrap create many calls inside a save point when parent is in transaction', async (assert) => { @@ -1383,11 +1383,11 @@ test.group('Model | HasMany | persist', (group) => { const trx = await db.transaction() const user = new User() - user.$trx = trx + user.trx = trx user.username = 'virk' const [post] = await user.related('posts').createMany([{ title: 'Adonis 101' }]) - assert.isFalse(user.$trx.isCompleted) + assert.isFalse(user.trx.isCompleted) await trx.rollback() const totalUsers = await db.query().from('users').count('*', 'total') @@ -1395,8 +1395,8 @@ test.group('Model | HasMany | persist', (group) => { assert.equal(totalUsers[0].total, 0) assert.equal(totalPosts[0].total, 0) - assert.isUndefined(user.$trx) - assert.isUndefined(post.$trx) + assert.isUndefined(user.trx) + assert.isUndefined(post.trx) }) }) @@ -1448,8 +1448,8 @@ test.group('Model | HasMany | firstOrCreate', (group) => { title: 'Adonis 101', }) - assert.isTrue(post.$isPersisted) - assert.isTrue(post.$isLocal) + assert.isTrue(post.isPersisted) + assert.isTrue(post.isLocal) assert.equal(user.id, post.userId) assert.equal(post.title, 'Adonis 101') @@ -1490,8 +1490,8 @@ test.group('Model | HasMany | firstOrCreate', (group) => { title: 'Adonis 101', }) - assert.isTrue(post.$isPersisted) - assert.isFalse(post.$isLocal) + assert.isTrue(post.isPersisted) + assert.isFalse(post.isLocal) assert.equal(user.id, post.userId) assert.equal(post.title, 'Lucid 101') @@ -1549,8 +1549,8 @@ test.group('Model | HasMany | updateOrCreate', (group) => { title: 'Adonis 101', }) - assert.isTrue(post.$isPersisted) - assert.isTrue(post.$isLocal) + assert.isTrue(post.isPersisted) + assert.isTrue(post.isLocal) assert.equal(user.id, post.userId) assert.equal(post.title, 'Adonis 101') @@ -1591,8 +1591,8 @@ test.group('Model | HasMany | updateOrCreate', (group) => { title: 'Adonis 101', }) - assert.isTrue(post.$isPersisted) - assert.isFalse(post.$isLocal) + assert.isTrue(post.isPersisted) + assert.isFalse(post.isLocal) assert.equal(user.id, post.userId) assert.equal(post.title, 'Adonis 101') diff --git a/test/orm/model-has-one.spec.ts b/test/orm/model-has-one.spec.ts index 504ab8d7..92c58fa9 100644 --- a/test/orm/model-has-one.spec.ts +++ b/test/orm/model-has-one.spec.ts @@ -36,8 +36,8 @@ test.group('Model | HasOne | Options', (group) => { public profile: HasOne } - User.$boot() - User.$getRelation('profile').$boot() + User.boot() + User.$getRelation('profile').boot() } catch ({ message }) { assert.equal( message, @@ -52,7 +52,7 @@ test.group('Model | HasOne | Options', (group) => { try { class Profile extends BaseModel { } - Profile.$boot() + Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) @@ -62,8 +62,8 @@ test.group('Model | HasOne | Options', (group) => { public profile: HasOne } - User.$boot() - User.$getRelation('profile')!.$boot() + User.boot() + User.$getRelation('profile')!.boot() } catch ({ message }) { assert.equal( message, @@ -77,7 +77,7 @@ test.group('Model | HasOne | Options', (group) => { @column() public userId: number } - Profile.$boot() + Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) @@ -87,11 +87,11 @@ test.group('Model | HasOne | Options', (group) => { public profile: HasOne } - User.$boot() - User.$getRelation('profile').$boot() + User.boot() + User.$getRelation('profile').boot() - assert.equal(User.$getRelation('profile')['$localKey'], 'id') - assert.equal(User.$getRelation('profile')!['$localCastAsKey'], 'id') + assert.equal(User.$getRelation('profile')['localKey'], 'id') + assert.equal(User.$getRelation('profile')!['localCastAsKey'], 'id') }) test('use custom defined local key', (assert) => { @@ -99,7 +99,7 @@ test.group('Model | HasOne | Options', (group) => { @column() public userId: number } - Profile.$boot() + Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) @@ -112,11 +112,11 @@ test.group('Model | HasOne | Options', (group) => { public profile: HasOne } - User.$boot() - User.$getRelation('profile').$boot() + User.boot() + User.$getRelation('profile').boot() - assert.equal(User.$getRelation('profile')['$localKey'], 'uid') - assert.equal(User.$getRelation('profile')['$localCastAsKey'], 'user_uid') + assert.equal(User.$getRelation('profile')['localKey'], 'uid') + assert.equal(User.$getRelation('profile')['localCastAsKey'], 'user_uid') }) test('compute foreign key from model name and primary key', (assert) => { @@ -124,7 +124,7 @@ test.group('Model | HasOne | Options', (group) => { @column() public userId: number } - Profile.$boot() + Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) @@ -134,11 +134,11 @@ test.group('Model | HasOne | Options', (group) => { public profile: HasOne } - User.$boot() - User.$getRelation('profile').$boot() + User.boot() + User.$getRelation('profile').boot() - assert.equal(User.$getRelation('profile')['$foreignKey'], 'userId') - assert.equal(User.$getRelation('profile')['$foreignCastAsKey'], 'user_id') + assert.equal(User.$getRelation('profile')['foreignKey'], 'userId') + assert.equal(User.$getRelation('profile')['foreignCastAsKey'], 'user_id') }) test('use pre defined foreign key', (assert) => { @@ -146,7 +146,7 @@ test.group('Model | HasOne | Options', (group) => { @column({ castAs: 'user_id' }) public userUid: number } - Profile.$boot() + Profile.boot() class User extends BaseModel { @column({ isPrimary: true }) @@ -156,11 +156,11 @@ test.group('Model | HasOne | Options', (group) => { public profile: HasOne } - User.$boot() - User.$getRelation('profile').$boot() + User.boot() + User.$getRelation('profile').boot() - assert.equal(User.$getRelation('profile')!['$foreignKey'], 'userUid') - assert.equal(User.$getRelation('profile')!['$foreignCastAsKey'], 'user_id') + assert.equal(User.$getRelation('profile')!['foreignKey'], 'userUid') + assert.equal(User.$getRelation('profile')!['foreignCastAsKey'], 'user_id') }) }) @@ -184,8 +184,8 @@ test.group('Model | HasOne | Set Relations', (group) => { public profile: HasOne } - User.$boot() - User.$getRelation('profile').$boot() + User.boot() + User.$getRelation('profile').boot() const user = new User() const profile = new Profile() @@ -207,8 +207,8 @@ test.group('Model | HasOne | Set Relations', (group) => { public profile: HasOne } - User.$boot() - User.$getRelation('profile').$boot() + User.boot() + User.$getRelation('profile').boot() const user = new User() const profile = new Profile() @@ -230,8 +230,8 @@ test.group('Model | HasOne | Set Relations', (group) => { public profile: HasOne } - User.$boot() - User.$getRelation('profile').$boot() + User.boot() + User.$getRelation('profile').boot() const user = new User() user.fill({ id: 1 }) @@ -339,7 +339,7 @@ test.group('Model | HasOne | bulk operations', (group) => { ]) const users = await User.all() - User.$getRelation('profile').$boot() + User.$getRelation('profile').boot() const related = User.$getRelation('profile').client(users, db.connection()) const { sql, bindings } = related.query().toSQL() @@ -424,7 +424,7 @@ test.group('Model | HasOne | bulk operations', (group) => { ]) const users = await User.all() - User.$getRelation('profile').$boot() + User.$getRelation('profile').boot() const now = new Date() const related = User.$getRelation('profile').client(users, db.connection()) @@ -509,7 +509,7 @@ test.group('Model | HasOne | bulk operations', (group) => { ]) const users = await User.all() - User.$getRelation('profile').$boot() + User.$getRelation('profile').boot() const related = User.$getRelation('profile').client(users, db.connection()) const { sql, bindings } = related.query().del().toSQL() @@ -576,7 +576,7 @@ test.group('Model | HasOne | preload', (group) => { }, ]) - User.$boot() + User.boot() const users = await User.query().preload('profile') assert.lengthOf(users, 2) @@ -642,7 +642,7 @@ test.group('Model | HasOne | preload', (group) => { }, ]) - User.$boot() + User.boot() const user = await User.query() .preload('profile', (builder) => builder.preload('identity')) @@ -690,7 +690,7 @@ test.group('Model | HasOne | preload', (group) => { }, ]) - User.$boot() + User.boot() const users = await User.query().preload('profile', (builder) => builder.preload('user')) assert.lengthOf(users, 2) @@ -733,7 +733,7 @@ test.group('Model | HasOne | preload', (group) => { }, ]) - User.$boot() + User.boot() const users = await User.query().preload('profile', (builder) => builder.where('display_name', 'foo')) assert.lengthOf(users, 2) @@ -776,7 +776,7 @@ test.group('Model | HasOne | preload', (group) => { }, ]) - User.$boot() + User.boot() const users = await User.query().preload('profile', (builder) => { return builder.select('display_name') @@ -821,7 +821,7 @@ test.group('Model | HasOne | preload', (group) => { }, ]) - User.$boot() + User.boot() const users = await User.query().preload('profile', (builder) => { return builder.select('display_name', 'user_id') @@ -866,15 +866,15 @@ test.group('Model | HasOne | preload', (group) => { }, ]) - User.$boot() + User.boot() const users = await User.query().preload('profile').sideload({ id: 1 }) assert.lengthOf(users, 2) - assert.deepEqual(users[0].$sideloaded, { id: 1 }) - assert.deepEqual(users[1].$sideloaded, { id: 1 }) - assert.deepEqual(users[0].profile.$sideloaded, { id: 1 }) - assert.deepEqual(users[1].profile.$sideloaded, { id: 1 }) + assert.deepEqual(users[0].sideloaded, { id: 1 }) + assert.deepEqual(users[1].sideloaded, { id: 1 }) + assert.deepEqual(users[0].profile.sideloaded, { id: 1 }) + assert.deepEqual(users[1].profile.sideloaded, { id: 1 }) }) test('preload using model instance', async (assert) => { @@ -909,7 +909,7 @@ test.group('Model | HasOne | preload', (group) => { }, ]) - User.$boot() + User.boot() const users = await User.all() assert.lengthOf(users, 2) @@ -1021,7 +1021,7 @@ test.group('Model | HasOne | preload', (group) => { }, ]) - User.$boot() + User.boot() const users = await User.all() assert.lengthOf(users, 2) @@ -1098,7 +1098,7 @@ test.group('Model | HasOne | preload', (group) => { }, ]) - User.$boot() + User.boot() const query = User.query({ connection: 'secondary' }) .preload('profile', (builder) => builder.preload('identity')) @@ -1108,9 +1108,9 @@ test.group('Model | HasOne | preload', (group) => { assert.instanceOf(user!.profile, Profile) assert.instanceOf(user!.profile.identity, Identity) - assert.equal(user!.$options!.connection, 'secondary') - assert.equal(user!.profile.$options!.connection, 'secondary') - assert.equal(user!.profile.identity.$options!.connection, 'secondary') + assert.equal(user!.options!.connection, 'secondary') + assert.equal(user!.profile.options!.connection, 'secondary') + assert.equal(user!.profile.identity.options!.connection, 'secondary') }) test('pass relationship metadata to the profiler', async (assert) => { @@ -1159,7 +1159,7 @@ test.group('Model | HasOne | preload', (group) => { profilerPacketIndex++ }) - User.$boot() + User.boot() await User.query({ profiler }).preload('profile') }) }) @@ -1212,7 +1212,7 @@ test.group('Model | HasOne | persist', (group) => { await user.related('profile').save(profile) - assert.isTrue(profile.$isPersisted) + assert.isTrue(profile.isPersisted) assert.equal(user.id, profile.userId) }) @@ -1247,7 +1247,7 @@ test.group('Model | HasOne | persist', (group) => { displayName: 'Hvirk', }) - assert.isTrue(profile.$isPersisted) + assert.isTrue(profile.isPersisted) assert.equal(user.id, profile.userId) }) @@ -1278,7 +1278,7 @@ test.group('Model | HasOne | persist', (group) => { const user = new User() user.username = 'virk' - user.$trx = trx + user.trx = trx await user.save() const profile = await user.related('profile').create({ @@ -1292,8 +1292,8 @@ test.group('Model | HasOne | persist', (group) => { assert.equal(totalUsers[0].total, 0) assert.equal(totalProfiles[0].total, 0) - assert.isUndefined(user.$trx) - assert.isUndefined(profile.$trx) + assert.isUndefined(user.trx) + assert.isUndefined(profile.trx) }) }) @@ -1344,8 +1344,8 @@ test.group('Model | HasOne | firstOrCreate', (group) => { displayName: 'Hvirk', }) - assert.isTrue(profile.$isPersisted) - assert.isTrue(profile.$isLocal) + assert.isTrue(profile.isPersisted) + assert.isTrue(profile.isLocal) assert.equal(user.id, profile.userId) assert.equal(profile.displayName, 'Hvirk') }) @@ -1382,8 +1382,8 @@ test.group('Model | HasOne | firstOrCreate', (group) => { displayName: 'Hvirk', }) - assert.isTrue(profile.$isPersisted) - assert.isFalse(profile.$isLocal) + assert.isTrue(profile.isPersisted) + assert.isFalse(profile.isLocal) assert.equal(user.id, profile.userId) assert.equal(profile.displayName, 'Hvirk') @@ -1439,8 +1439,8 @@ test.group('Model | HasOne | updateOrCreate', (group) => { displayName: 'Virk', }) - assert.isTrue(profile.$isPersisted) - assert.isTrue(profile.$isLocal) + assert.isTrue(profile.isPersisted) + assert.isTrue(profile.isLocal) assert.equal(user.id, profile.userId) assert.equal(profile.displayName, 'Virk') @@ -1481,8 +1481,8 @@ test.group('Model | HasOne | updateOrCreate', (group) => { displayName: 'Virk', }) - assert.isTrue(profile.$isPersisted) - assert.isFalse(profile.$isLocal) + assert.isTrue(profile.isPersisted) + assert.isFalse(profile.isLocal) assert.equal(user.id, profile.userId) assert.equal(profile.displayName, 'Virk') diff --git a/test/orm/model-many-to-many.spec.ts b/test/orm/model-many-to-many.spec.ts index e49a1ba3..5112e3ef 100644 --- a/test/orm/model-many-to-many.spec.ts +++ b/test/orm/model-many-to-many.spec.ts @@ -36,8 +36,8 @@ test.group('Model | ManyToMany | Options', (group) => { public skills: ManyToMany } - User.$boot() - User.$getRelation('skills').$boot() + User.boot() + User.$getRelation('skills').boot() } catch ({ message }) { assert.equal( message, @@ -60,10 +60,10 @@ test.group('Model | ManyToMany | Options', (group) => { public skills: ManyToMany } - User.$getRelation('skills').$boot() + User.$getRelation('skills').boot() - assert.equal(User.$getRelation('skills')!['$localKey'], 'id') - assert.equal(User.$getRelation('skills')!['$localCastAsKey'], 'id') + assert.equal(User.$getRelation('skills')!['localKey'], 'id') + assert.equal(User.$getRelation('skills')!['localCastAsKey'], 'id') }) test('use custom defined local key', (assert) => { @@ -83,11 +83,11 @@ test.group('Model | ManyToMany | Options', (group) => { public skills: ManyToMany } - User.$boot() - User.$getRelation('skills').$boot() + User.boot() + User.$getRelation('skills').boot() - assert.equal(User.$getRelation('skills')!['$localKey'], 'uid') - assert.equal(User.$getRelation('skills')!['$localCastAsKey'], 'uid') + assert.equal(User.$getRelation('skills')!['localKey'], 'uid') + assert.equal(User.$getRelation('skills')!['localCastAsKey'], 'uid') }) test('raise error when relatedKey is missing', (assert) => { @@ -96,7 +96,7 @@ test.group('Model | ManyToMany | Options', (group) => { try { class Skill extends BaseModel { } - Skill.$boot() + Skill.boot() class User extends BaseModel { @column({ isPrimary: true }) @@ -106,8 +106,8 @@ test.group('Model | ManyToMany | Options', (group) => { public skills: ManyToMany } - User.$boot() - User.$getRelation('skills').$boot() + User.boot() + User.$getRelation('skills').boot() } catch ({ message }) { assert.equal( message, @@ -130,10 +130,10 @@ test.group('Model | ManyToMany | Options', (group) => { public skills: ManyToMany } - User.$getRelation('skills').$boot() + User.$getRelation('skills').boot() - assert.equal(User.$getRelation('skills')!['$relatedKey'], 'id') - assert.equal(User.$getRelation('skills')!['$relatedCastAsKey'], 'id') + assert.equal(User.$getRelation('skills')!['relatedKey'], 'id') + assert.equal(User.$getRelation('skills')!['relatedCastAsKey'], 'id') }) test('use custom defined related key', (assert) => { @@ -153,10 +153,10 @@ test.group('Model | ManyToMany | Options', (group) => { public skills: ManyToMany } - User.$getRelation('skills').$boot() + User.$getRelation('skills').boot() - assert.equal(User.$getRelation('skills')!['$relatedKey'], 'uid') - assert.equal(User.$getRelation('skills')!['$relatedCastAsKey'], 'uid') + assert.equal(User.$getRelation('skills')!['relatedKey'], 'uid') + assert.equal(User.$getRelation('skills')!['relatedCastAsKey'], 'uid') }) test('compute pivotForeignKey from table name + primary key', (assert) => { @@ -173,9 +173,9 @@ test.group('Model | ManyToMany | Options', (group) => { public skills: ManyToMany } - User.$getRelation('skills').$boot() + User.$getRelation('skills').boot() - assert.equal(User.$getRelation('skills')!['$pivotForeignKey'], 'user_id') + assert.equal(User.$getRelation('skills')!['pivotForeignKey'], 'user_id') }) test('use custom defined pivotForeignKey', (assert) => { @@ -192,9 +192,9 @@ test.group('Model | ManyToMany | Options', (group) => { public skills: ManyToMany } - User.$getRelation('skills').$boot() + User.$getRelation('skills').boot() - assert.equal(User.$getRelation('skills')!['$pivotForeignKey'], 'user_uid') + assert.equal(User.$getRelation('skills')!['pivotForeignKey'], 'user_uid') }) test('compute relatedPivotForeignKey from related model name + primary key', (assert) => { @@ -211,10 +211,10 @@ test.group('Model | ManyToMany | Options', (group) => { public skills: ManyToMany } - User.$boot() - User.$getRelation('skills').$boot() + User.boot() + User.$getRelation('skills').boot() - assert.equal(User.$getRelation('skills')!['$pivotRelatedForeignKey'], 'skill_id') + assert.equal(User.$getRelation('skills')!['pivotRelatedForeignKey'], 'skill_id') }) test('use custom defined relatedPivotForeignKey', (assert) => { @@ -231,10 +231,10 @@ test.group('Model | ManyToMany | Options', (group) => { public skills: ManyToMany } - User.$boot() - User.$getRelation('skills').$boot() + User.boot() + User.$getRelation('skills').boot() - assert.equal(User.$getRelation('skills')!['$pivotRelatedForeignKey'], 'skill_uid') + assert.equal(User.$getRelation('skills')!['pivotRelatedForeignKey'], 'skill_uid') }) }) @@ -258,7 +258,7 @@ test.group('Model | ManyToMany | Set Relations', (group) => { public skills: ManyToMany } - User.$getRelation('skills').$boot() + User.$getRelation('skills').boot() const user = new User() const skill = new Skill() @@ -280,7 +280,7 @@ test.group('Model | ManyToMany | Set Relations', (group) => { public skills: ManyToMany } - User.$getRelation('skills').$boot() + User.$getRelation('skills').boot() const user = new User() const skill = new Skill() @@ -308,8 +308,8 @@ test.group('Model | ManyToMany | Set Relations', (group) => { public skills: ManyToMany } - User.$getRelation('skills').$boot() - Skill.$getRelation('users').$boot() + User.$getRelation('skills').boot() + Skill.$getRelation('users').boot() const user = new User() user.fill({ id: 1 }) @@ -409,7 +409,7 @@ test.group('Model | ManyToMany | bulk operations', (group) => { ]) const users = await User.all() - User.$getRelation('skills').$boot() + User.$getRelation('skills').boot() const related = User.$getRelation('skills').client(users, db.connection()) const { sql, bindings } = related.query().toSQL() @@ -552,7 +552,7 @@ test.group('Model | ManyToMany | bulk operations', (group) => { ]) const users = await User.all() - User.$getRelation('skills').$boot() + User.$getRelation('skills').boot() const related = User.$getRelation('skills').client(users, db.connection()) const now = new Date() @@ -620,7 +620,7 @@ test.group('Model | ManyToMany | bulk operations', (group) => { ]) const users = await User.all() - User.$getRelation('skills').$boot() + User.$getRelation('skills').boot() const related = User.$getRelation('skills').client(users, db.connection()) @@ -670,7 +670,7 @@ test.group('Model | ManyToMany | preload', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() await db.insertQuery().table('users').insert([{ username: 'virk' }]) await db.insertQuery().table('skills').insert([{ name: 'Programming' }, { name: 'Dancing' }]) await db.insertQuery().table('skill_user').insert([ @@ -705,7 +705,7 @@ test.group('Model | ManyToMany | preload', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() await db.insertQuery().table('users').insert([{ username: 'virk' }, { username: 'nikk' }]) await db.insertQuery().table('skills').insert([{ name: 'Programming' }, { name: 'Dancing' }]) @@ -759,7 +759,7 @@ test.group('Model | ManyToMany | preload', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() await db.insertQuery().table('users').insert([{ username: 'virk' }, { username: 'nikk' }]) await db.insertQuery().table('skills').insert([{ name: 'Programming' }, { name: 'Dancing' }]) @@ -820,7 +820,7 @@ test.group('Model | ManyToMany | preload', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() await db.insertQuery().table('users').insert([{ username: 'virk' }, { username: 'nikk' }]) await db.insertQuery().table('skills').insert([{ name: 'Programming' }, { name: 'Dancing' }]) @@ -883,7 +883,7 @@ test.group('Model | ManyToMany | preload', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() await db.insertQuery().table('users').insert([{ username: 'virk' }, { username: 'nikk' }]) await db.insertQuery().table('skills').insert([{ name: 'Programming' }, { name: 'Dancing' }]) @@ -946,7 +946,7 @@ test.group('Model | ManyToMany | preload', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() await db.insertQuery().table('users').insert([{ username: 'virk' }]) await db.insertQuery().table('skills').insert([{ name: 'Programming' }, { name: 'Dancing' }]) await db.insertQuery().table('skill_user').insert([ @@ -985,7 +985,7 @@ test.group('Model | ManyToMany | preload', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() await db.insertQuery().table('users').insert([{ username: 'virk' }, { username: 'nikk' }]) await db.insertQuery().table('skills').insert([{ name: 'Programming' }, { name: 'Dancing' }]) @@ -1038,11 +1038,11 @@ test.group('Model | ManyToMany | wherePivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query .wherePivot('username', 'virk') @@ -1071,11 +1071,11 @@ test.group('Model | ManyToMany | wherePivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query .where((builder) => builder.wherePivot('username', 'virk')) @@ -1104,11 +1104,11 @@ test.group('Model | ManyToMany | wherePivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query .wherePivot('age', '>', 22) @@ -1137,11 +1137,11 @@ test.group('Model | ManyToMany | wherePivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query .wherePivot('age', '>', db.raw('select min_age from ages limit 1;')) @@ -1174,11 +1174,11 @@ test.group('Model | ManyToMany | wherePivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query .wherePivot('age', '>', 22) @@ -1209,11 +1209,11 @@ test.group('Model | ManyToMany | wherePivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query .wherePivot('age', '>', 22) @@ -1234,7 +1234,7 @@ test.group('Model | ManyToMany | wherePivot', (group) => { assert.deepEqual(bindings, knexBindings) }) - test('preload self referenced relationship', async (assert) => { + test('pass relationship metadata to the profiler', async (assert) => { assert.plan(1) class Skill extends BaseModel { @@ -1253,7 +1253,7 @@ test.group('Model | ManyToMany | wherePivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() await db.insertQuery().table('users').insert([{ username: 'virk' }]) await db.insertQuery().table('skills').insert([{ name: 'Programming' }, { name: 'Dancing' }]) await db.insertQuery().table('skill_user').insert([ @@ -1308,11 +1308,11 @@ test.group('Model | ManyToMany | whereNotPivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query.whereNotPivot('username', 'virk').toSQL() const { sql: knexSql, bindings: knexBindings } = db.connection().getWriteClient() @@ -1338,11 +1338,11 @@ test.group('Model | ManyToMany | whereNotPivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query .whereNotPivot('age', '>', 22) @@ -1371,11 +1371,11 @@ test.group('Model | ManyToMany | whereNotPivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query .whereNotPivot('age', '>', db.raw('select min_age from ages limit 1;')) @@ -1408,11 +1408,11 @@ test.group('Model | ManyToMany | whereNotPivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query .whereNotPivot('age', '>', 22) @@ -1456,11 +1456,11 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query .whereInPivot('username', ['virk', 'nikk']) @@ -1489,11 +1489,11 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query .whereInPivot('username', (builder) => { @@ -1526,11 +1526,11 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query .whereInPivot('username', db.query().select('id').from('accounts')) @@ -1561,11 +1561,11 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query .whereInPivot('username', [ @@ -1598,11 +1598,11 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query .whereInPivot( @@ -1637,11 +1637,11 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query .whereInPivot(['username', 'email'], [['foo', 'bar']]) @@ -1670,11 +1670,11 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query .whereInPivot('username', ['virk', 'nikk']) @@ -1705,11 +1705,11 @@ test.group('Model | ManyToMany | whereInPivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query .whereInPivot('username', (builder) => { @@ -1761,11 +1761,11 @@ test.group('Model | ManyToMany | whereNotInPivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query .whereNotInPivot('username', ['virk', 'nikk']) @@ -1794,11 +1794,11 @@ test.group('Model | ManyToMany | whereNotInPivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query .whereNotInPivot('username', (builder) => { @@ -1831,11 +1831,11 @@ test.group('Model | ManyToMany | whereNotInPivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query .whereNotInPivot('username', db.query().select('username').from('accounts')) @@ -1867,11 +1867,11 @@ test.group('Model | ManyToMany | whereNotInPivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query .whereNotInPivot(['username', 'email'], [['foo', 'bar']]) @@ -1900,11 +1900,11 @@ test.group('Model | ManyToMany | whereNotInPivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query .whereNotInPivot('username', ['virk', 'nikk']) @@ -1935,11 +1935,11 @@ test.group('Model | ManyToMany | whereNotInPivot', (group) => { public skills: ManyToMany } - User.$boot() + User.boot() const user = new User() const query = user!.related('skills').query() - query['$appliedConstraints'] = true + query['appliedConstraints'] = true const { sql, bindings } = query .whereNotInPivot('username', (builder) => { @@ -2010,8 +2010,8 @@ test.group('Model | ManyToMany | persist', (group) => { await user.related('skills').save(skill) - assert.isTrue(user.$isPersisted) - assert.isTrue(skill.$isPersisted) + assert.isTrue(user.isPersisted) + assert.isTrue(skill.isPersisted) const totalUsers = await db.query().from('users').count('*', 'total') const totalPosts = await db.query().from('skills').count('*', 'total') @@ -2023,62 +2023,11 @@ test.group('Model | ManyToMany | persist', (group) => { assert.lengthOf(skillUsers, 1) assert.equal(skillUsers[0].user_id, user.id) assert.equal(skillUsers[0].skill_id, skill.id) - assert.isUndefined(user.$trx) - assert.isUndefined(skill.$trx) + assert.isUndefined(user.trx) + assert.isUndefined(skill.trx) }) - test('attach duplicates when save is called twice and check existing is false', async (assert) => { - class Skill extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @column() - public name: string - } - - class User extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @column() - public username: string - - @manyToMany(() => Skill) - public skills: ManyToMany - } - - const user = new User() - user.username = 'virk' - await user.save() - - const skill = new Skill() - skill.name = 'Programming' - - await user.related('skills').save(skill) - await user.related('skills').save(skill, false) - - assert.isTrue(user.$isPersisted) - assert.isTrue(skill.$isPersisted) - - const totalUsers = await db.query().from('users').count('*', 'total') - const totalPosts = await db.query().from('skills').count('*', 'total') - const skillUsers = await db.query().from('skill_user') - - assert.equal(totalUsers[0].total, 1) - assert.equal(totalPosts[0].total, 1) - - assert.lengthOf(skillUsers, 2) - assert.equal(skillUsers[0].user_id, user.id) - assert.equal(skillUsers[0].skill_id, skill.id) - - assert.equal(skillUsers[1].user_id, user.id) - assert.equal(skillUsers[1].skill_id, skill.id) - - assert.isUndefined(user.$trx) - assert.isUndefined(skill.$trx) - }) - - test('do not attach duplicates when checkExisting is true', async (assert) => { + test('do not attach duplicates when save is called', async (assert) => { class Skill extends BaseModel { @column({ isPrimary: true }) public id: number @@ -2108,8 +2057,8 @@ test.group('Model | ManyToMany | persist', (group) => { await user.related('skills').save(skill) await user.related('skills').save(skill) - assert.isTrue(user.$isPersisted) - assert.isTrue(skill.$isPersisted) + assert.isTrue(user.isPersisted) + assert.isTrue(skill.isPersisted) const totalUsers = await db.query().from('users').count('*', 'total') const totalPosts = await db.query().from('skills').count('*', 'total') @@ -2122,8 +2071,8 @@ test.group('Model | ManyToMany | persist', (group) => { assert.equal(skillUsers[0].user_id, user.id) assert.equal(skillUsers[0].skill_id, skill.id) - assert.isUndefined(user.$trx) - assert.isUndefined(skill.$trx) + assert.isUndefined(user.trx) + assert.isUndefined(skill.trx) }) test('attach when related pivot entry exists but for a different parent @sanityCheck', async (assert) => { @@ -2160,8 +2109,8 @@ test.group('Model | ManyToMany | persist', (group) => { await user.related('skills').save(skill) await user1.related('skills').save(skill) - assert.isTrue(user.$isPersisted) - assert.isTrue(skill.$isPersisted) + assert.isTrue(user.isPersisted) + assert.isTrue(skill.isPersisted) const totalUsers = await db.query().from('users').count('*', 'total') const totalSkills = await db.query().from('skills').count('*', 'total') @@ -2176,9 +2125,9 @@ test.group('Model | ManyToMany | persist', (group) => { assert.equal(skillUsers[1].user_id, user1.id) assert.equal(skillUsers[1].skill_id, skill.id) - assert.isUndefined(user.$trx) - assert.isUndefined(user1.$trx) - assert.isUndefined(skill.$trx) + assert.isUndefined(user.trx) + assert.isUndefined(user1.trx) + assert.isUndefined(skill.trx) }) test('save many of the related instances', async (assert) => { @@ -2213,9 +2162,9 @@ test.group('Model | ManyToMany | persist', (group) => { await user.related('skills').saveMany([skill, skill1]) - assert.isTrue(user.$isPersisted) - assert.isTrue(skill.$isPersisted) - assert.isTrue(skill1.$isPersisted) + assert.isTrue(user.isPersisted) + assert.isTrue(skill.isPersisted) + assert.isTrue(skill1.isPersisted) const totalUsers = await db.query().from('users').count('*', 'total') const totalSkills = await db.query().from('skills').count('*', 'total') @@ -2231,9 +2180,9 @@ test.group('Model | ManyToMany | persist', (group) => { assert.equal(skillUsers[1].user_id, user.id) assert.equal(skillUsers[1].skill_id, skill1.id) - assert.isUndefined(user.$trx) - assert.isUndefined(skill.$trx) - assert.isUndefined(skill1.$trx) + assert.isUndefined(user.trx) + assert.isUndefined(skill.trx) + assert.isUndefined(skill1.trx) }) test('save many do not add duplicates', async (assert) => { @@ -2269,9 +2218,9 @@ test.group('Model | ManyToMany | persist', (group) => { await user.related('skills').save(skill) await user.related('skills').saveMany([skill, skill1]) - assert.isTrue(user.$isPersisted) - assert.isTrue(skill.$isPersisted) - assert.isTrue(skill1.$isPersisted) + assert.isTrue(user.isPersisted) + assert.isTrue(skill.isPersisted) + assert.isTrue(skill1.isPersisted) const totalUsers = await db.query().from('users').count('*', 'total') const totalSkills = await db.query().from('skills').count('*', 'total') @@ -2287,9 +2236,9 @@ test.group('Model | ManyToMany | persist', (group) => { assert.equal(skillUsers[1].user_id, user.id) assert.equal(skillUsers[1].skill_id, skill1.id) - assert.isUndefined(user.$trx) - assert.isUndefined(skill.$trx) - assert.isUndefined(skill1.$trx) + assert.isUndefined(user.trx) + assert.isUndefined(skill.trx) + assert.isUndefined(skill1.trx) }) test('attach ids with extra attributes', async (assert) => { @@ -2321,7 +2270,7 @@ test.group('Model | ManyToMany | persist', (group) => { 2: {}, }) - assert.isTrue(user.$isPersisted) + assert.isTrue(user.isPersisted) const totalUsers = await db.query().from('users').count('*', 'total') const skillUsers = await db.query().from('skill_user').orderBy('id', 'asc') @@ -2368,7 +2317,7 @@ test.group('Model | ManyToMany | persist', (group) => { await user.related('skills').detach([2]) - assert.isTrue(user.$isPersisted) + assert.isTrue(user.isPersisted) const totalUsers = await db.query().from('users').count('*', 'total') const skillUsers = await db.query().from('skill_user').orderBy('id', 'asc') @@ -2420,8 +2369,8 @@ test.group('Model | ManyToMany | persist', (group) => { // assert.lengthOf(skillUsers, 1) // assert.equal(skillUsers[0].user_id, user.id) // assert.equal(skillUsers[0].skill_id, skill.id) -// assert.isUndefined(user.$trx) -// assert.isUndefined(skill.$trx) +// assert.isUndefined(user.trx) +// assert.isUndefined(skill.trx) // }) // test('create many of related instance', async (assert) => { @@ -2472,9 +2421,9 @@ test.group('Model | ManyToMany | persist', (group) => { // assert.equal(skillUsers[1].user_id, user.id) // assert.equal(skillUsers[1].skill_id, skill1.id) -// assert.isUndefined(user.$trx) -// assert.isUndefined(skill.$trx) -// assert.isUndefined(skill1.$trx) +// assert.isUndefined(user.trx) +// assert.isUndefined(skill.trx) +// assert.isUndefined(skill1.trx) // }) // }) @@ -2532,7 +2481,7 @@ test.group('Model | ManyToMany | persist', (group) => { // assert.equal(skillUsers[1].user_id, user.id) // assert.equal(skillUsers[1].skill_id, 2) -// assert.isUndefined(user.$trx) +// assert.isUndefined(user.trx) // }) // test('attach pivot ids avoid duplicates', async (assert) => { @@ -2573,7 +2522,7 @@ test.group('Model | ManyToMany | persist', (group) => { // assert.equal(skillUsers[1].user_id, user.id) // assert.equal(skillUsers[1].skill_id, 2) -// assert.isUndefined(user.$trx) +// assert.isUndefined(user.trx) // }) // test('fail attach when parent model has not been persisted', async (assert) => { @@ -2652,7 +2601,7 @@ test.group('Model | ManyToMany | persist', (group) => { // assert.equal(skillUsers[1].skill_id, 2) // assert.equal(skillUsers[1].proficiency, 'Beginner') -// assert.isUndefined(user.$trx) +// assert.isUndefined(user.trx) // }) // }) @@ -2797,7 +2746,7 @@ test.group('Model | ManyToMany | persist', (group) => { // assert.equal(skillUsers[0].user_id, user.id) // assert.equal(skillUsers[0].skill_id, 2) -// assert.isUndefined(user.$trx) +// assert.isUndefined(user.trx) // }) // test('fail detach when parent is not persisted', async (assert) => { diff --git a/test/orm/model-query-builder.spec.ts b/test/orm/model-query-builder.spec.ts index ffb0eb6c..1fcc0413 100644 --- a/test/orm/model-query-builder.spec.ts +++ b/test/orm/model-query-builder.spec.ts @@ -50,7 +50,7 @@ test.group('Model query builder', (group) => { public username: string } - User.$boot() + User.boot() assert.instanceOf(User.query(), ModelQueryBuilder) }) @@ -63,7 +63,7 @@ test.group('Model query builder', (group) => { public username: string } - User.$boot() + User.boot() assert.equal(User.query().knexQuery['_single'].table, 'users') }) @@ -76,7 +76,7 @@ test.group('Model query builder', (group) => { public username: string } - User.$boot() + User.boot() await db.insertQuery().table('users').insert([{ username: 'virk' }, { username: 'nikk' }]) const users = await User.query().where('username', 'virk') @@ -94,14 +94,14 @@ test.group('Model query builder', (group) => { public username: string } - User.$boot() + User.boot() await db.insertQuery().table('users').insert([{ username: 'virk' }, { username: 'nikk' }]) const users = await User.query({ connection: 'secondary' }).where('username', 'virk') assert.lengthOf(users, 1) assert.instanceOf(users[0], User) assert.deepEqual(users[0].$attributes, { id: 1, username: 'virk' }) - assert.deepEqual(users[0].$options!.connection, 'secondary') + assert.deepEqual(users[0].options!.connection, 'secondary') }) test('pass sideloaded attributes to the model instance', async (assert) => { @@ -113,7 +113,7 @@ test.group('Model query builder', (group) => { public username: string } - User.$boot() + User.boot() await db.insertQuery().table('users').insert([{ username: 'virk' }, { username: 'nikk' }]) const users = await User @@ -124,7 +124,7 @@ test.group('Model query builder', (group) => { assert.lengthOf(users, 1) assert.instanceOf(users[0], User) assert.deepEqual(users[0].$attributes, { id: 1, username: 'virk' }) - assert.deepEqual(users[0].$sideloaded, { loggedInUser: { id: 1 } }) + assert.deepEqual(users[0].sideloaded, { loggedInUser: { id: 1 } }) }) test('pass custom profiler to the model instance', async (assert) => { @@ -136,7 +136,7 @@ test.group('Model query builder', (group) => { public username: string } - User.$boot() + User.boot() await db.insertQuery().table('users').insert([{ username: 'virk' }, { username: 'nikk' }]) const profiler = getProfiler() @@ -144,7 +144,7 @@ test.group('Model query builder', (group) => { assert.lengthOf(users, 1) assert.instanceOf(users[0], User) assert.deepEqual(users[0].$attributes, { id: 1, username: 'virk' }) - assert.deepEqual(users[0].$options!.profiler, profiler) + assert.deepEqual(users[0].options!.profiler, profiler) }) test('perform update using model query builder', async (assert) => { @@ -156,7 +156,7 @@ test.group('Model query builder', (group) => { public username: string } - User.$boot() + User.boot() await db.insertQuery().table('users').insert([{ username: 'virk' }, { username: 'nikk' }]) const rows = await User.query().where('username', 'virk').update({ username: 'hvirk' }) @@ -176,7 +176,7 @@ test.group('Model query builder', (group) => { public username: string } - User.$boot() + User.boot() await db.insertQuery().table('users').insert([{ username: 'virk', points: 1 }]) const rows = await User.query().where('username', 'virk').increment('points', 1) @@ -196,7 +196,7 @@ test.group('Model query builder', (group) => { public username: string } - User.$boot() + User.boot() await db.insertQuery().table('users').insert([{ username: 'virk', points: 3 }]) const rows = await User.query().where('username', 'virk').decrement('points', 1) @@ -216,7 +216,7 @@ test.group('Model query builder', (group) => { public username: string } - User.$boot() + User.boot() await db.insertQuery().table('users').insert([{ username: 'virk' }, { username: 'nikk' }]) const rows = await User.query().where('username', 'virk').del()