You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
2.2 KiB
70 lines
2.2 KiB
import {Model} from './Model'
|
|
import {AbstractBuilder} from '../builder/AbstractBuilder'
|
|
import {AbstractResultIterable} from '../builder/result/AbstractResultIterable'
|
|
import {Instantiable, StaticClass} from '../../di'
|
|
import {ModelResultIterable} from './ModelResultIterable'
|
|
import {Collection} from '../../util'
|
|
import {ConstraintOperator, ModelKey, ModelKeys} from '../types'
|
|
import {EscapeValue} from '../dialect/SQLDialect'
|
|
|
|
/**
|
|
* Implementation of the abstract builder whose results yield instances of a given Model, `T`.
|
|
*/
|
|
export class ModelBuilder<T extends Model<T>> extends AbstractBuilder<T> {
|
|
constructor(
|
|
/** The model class that is created for results of this query. */
|
|
protected readonly ModelClass: StaticClass<T, typeof Model> & Instantiable<T>,
|
|
) {
|
|
super()
|
|
}
|
|
|
|
public getNewInstance(): AbstractBuilder<T> {
|
|
return this.app().make<ModelBuilder<T>>(ModelBuilder)
|
|
}
|
|
|
|
public getResultIterable(): AbstractResultIterable<T> {
|
|
return this.app().make<ModelResultIterable<T>>(ModelResultIterable, this, this.registeredConnection, this.ModelClass)
|
|
}
|
|
|
|
/**
|
|
* Apply a WHERE...IN... constraint on the primary key of the model.
|
|
* @param keys
|
|
*/
|
|
public whereKey(keys: ModelKeys): this {
|
|
return this.whereIn(
|
|
this.ModelClass.qualifyKey(),
|
|
this.normalizeModelKeys(keys),
|
|
)
|
|
}
|
|
|
|
/**
|
|
* Apply a where constraint on the column corresponding the the specified
|
|
* property on the model.
|
|
* @param propertyName
|
|
* @param operator
|
|
* @param operand
|
|
*/
|
|
public whereProperty(propertyName: string, operator: ConstraintOperator, operand?: EscapeValue): this {
|
|
return this.where(
|
|
this.ModelClass.propertyToColumn(propertyName),
|
|
operator,
|
|
operand,
|
|
)
|
|
}
|
|
|
|
/**
|
|
* Given some format of keys of the model, try to normalize them to a flat array.
|
|
* @param keys
|
|
* @protected
|
|
*/
|
|
protected normalizeModelKeys(keys: ModelKeys): ModelKey[] {
|
|
if ( Array.isArray(keys) ) {
|
|
return keys
|
|
} else if ( keys instanceof Collection ) {
|
|
return keys.all()
|
|
}
|
|
|
|
return [keys]
|
|
}
|
|
}
|