UNPKG

lakutata

Version:

An IoC-based universal application framework.

1,349 lines (1,328 loc) 91.8 kB
import { DataSource } from './TypeDef.internal.33.js'; import { ObjectLiteral, EntityTarget } from './TypeDef.internal.36.js'; import { QueryRunner } from './TypeDef.internal.40.js'; import { RelationMetadata, EntityMetadata, ColumnMetadata } from './TypeDef.internal.47.js'; import { OrderByCondition, FindManyOptions, FindOptionsSelect, FindOptionsRelations, FindOptionsOrder, FindOptionsWhere } from './TypeDef.internal.74.js'; import { RelationIdAttribute } from './TypeDef.internal.89.js'; import { RelationCountAttribute } from './TypeDef.internal.90.js'; import { UpsertType } from './TypeDef.internal.44.js'; import { ReadStream } from 'fs'; import { UpdateResult, DeleteResult, InsertResult } from './TypeDef.internal.81.js'; import { ReturningType } from './TypeDef.internal.45.js'; /** * Make all properties in T optional. Deep version. */ type QueryDeepPartialEntity<T> = _QueryDeepPartialEntity<ObjectLiteral extends T ? unknown : T>; type _QueryDeepPartialEntity<T> = { [P in keyof T]?: (T[P] extends Array<infer U> ? Array<_QueryDeepPartialEntity<U>> : T[P] extends ReadonlyArray<infer U> ? ReadonlyArray<_QueryDeepPartialEntity<U>> : _QueryDeepPartialEntity<T[P]>) | (() => string); }; type InsertOrUpdateOptions = { /** * If true, postgres will skip the update if no values would be changed (reduces writes) */ skipUpdateIfNoValuesChanged?: boolean; /** * If included, postgres will apply the index predicate to a conflict target (partial index) */ indexPredicate?: string; upsertType?: UpsertType; }; /** * Wraps entities and creates getters/setters for their relations * to be able to lazily load relations when accessing these relations. */ declare class RelationLoader { private connection; constructor(connection: DataSource); /** * Loads relation data for the given entity and its relation. */ load(relation: RelationMetadata, entityOrEntities: ObjectLiteral | ObjectLiteral[], queryRunner?: QueryRunner, queryBuilder?: SelectQueryBuilder<any>): Promise<any[]>; /** * Loads data for many-to-one and one-to-one owner relations. * * (ow) post.category<=>category.post * loaded: category from post * example: SELECT category.id AS category_id, category.name AS category_name FROM category category * INNER JOIN post Post ON Post.category=category.id WHERE Post.id=1 */ loadManyToOneOrOneToOneOwner(relation: RelationMetadata, entityOrEntities: ObjectLiteral | ObjectLiteral[], queryRunner?: QueryRunner, queryBuilder?: SelectQueryBuilder<any>): Promise<any>; /** * Loads data for one-to-many and one-to-one not owner relations. * * SELECT post * FROM post post * WHERE post.[joinColumn.name] = entity[joinColumn.referencedColumn] */ loadOneToManyOrOneToOneNotOwner(relation: RelationMetadata, entityOrEntities: ObjectLiteral | ObjectLiteral[], queryRunner?: QueryRunner, queryBuilder?: SelectQueryBuilder<any>): Promise<any>; /** * Loads data for many-to-many owner relations. * * SELECT category * FROM category category * INNER JOIN post_categories post_categories * ON post_categories.postId = :postId * AND post_categories.categoryId = category.id */ loadManyToManyOwner(relation: RelationMetadata, entityOrEntities: ObjectLiteral | ObjectLiteral[], queryRunner?: QueryRunner, queryBuilder?: SelectQueryBuilder<any>): Promise<any>; /** * Loads data for many-to-many not owner relations. * * SELECT post * FROM post post * INNER JOIN post_categories post_categories * ON post_categories.postId = post.id * AND post_categories.categoryId = post_categories.categoryId */ loadManyToManyNotOwner(relation: RelationMetadata, entityOrEntities: ObjectLiteral | ObjectLiteral[], queryRunner?: QueryRunner, queryBuilder?: SelectQueryBuilder<any>): Promise<any>; /** * Wraps given entity and creates getters/setters for its given relation * to be able to lazily load data when accessing this relation. */ enableLazyLoad(relation: RelationMetadata, entity: ObjectLiteral, queryRunner?: QueryRunner): void; } /** * Loads relation ids for the given entities. */ declare class RelationIdLoader { private connection; protected queryRunner?: QueryRunner | undefined; constructor(connection: DataSource, queryRunner?: QueryRunner | undefined); /** * Loads relation ids of the given entity or entities. */ load(relation: RelationMetadata, entityOrEntities: ObjectLiteral | ObjectLiteral[], relatedEntityOrRelatedEntities?: ObjectLiteral | ObjectLiteral[]): Promise<any[]>; /** * Loads relation ids of the given entities and groups them into the object with parent and children. * * todo: extract this method? */ loadManyToManyRelationIdsAndGroup<E1 extends ObjectLiteral, E2 extends ObjectLiteral>(relation: RelationMetadata, entitiesOrEntities: E1 | E1[], relatedEntityOrEntities?: E2 | E2[], queryBuilder?: SelectQueryBuilder<any>): Promise<{ entity: E1; related?: E2 | E2[]; }[]>; /** * Loads relation ids of the given entities and maps them into the given entity property. async loadManyToManyRelationIdsAndMap( relation: RelationMetadata, entityOrEntities: ObjectLiteral|ObjectLiteral[], mapToEntityOrEntities: ObjectLiteral|ObjectLiteral[], propertyName: string ): Promise<void> { const relationIds = await this.loadManyToManyRelationIds(relation, entityOrEntities, mapToEntityOrEntities); const mapToEntities = mapToEntityOrEntities instanceof Array ? mapToEntityOrEntities : [mapToEntityOrEntities]; const junctionMetadata = relation.junctionEntityMetadata!; const mainAlias = junctionMetadata.name; const columns = relation.isOwning ? junctionMetadata.inverseColumns : junctionMetadata.ownerColumns; const inverseColumns = relation.isOwning ? junctionMetadata.ownerColumns : junctionMetadata.inverseColumns; mapToEntities.forEach(mapToEntity => { mapToEntity[propertyName] = []; relationIds.forEach(relationId => { const match = inverseColumns.every(column => { return column.referencedColumn!.getEntityValue(mapToEntity) === relationId[mainAlias + "_" + column.propertyName]; }); if (match) { if (columns.length === 1) { mapToEntity[propertyName].push(relationId[mainAlias + "_" + columns[0].propertyName]); } else { const value = {}; columns.forEach(column => { column.referencedColumn!.setEntityValue(value, relationId[mainAlias + "_" + column.propertyName]); }); mapToEntity[propertyName].push(value); } } }); }); }*/ /** * Loads relation ids for the many-to-many relation. */ protected loadForManyToMany(relation: RelationMetadata, entities: ObjectLiteral[], relatedEntities?: ObjectLiteral[]): Promise<any[]>; /** * Loads relation ids for the many-to-one and one-to-one owner relations. */ protected loadForManyToOneAndOneToOneOwner(relation: RelationMetadata, entities: ObjectLiteral[], relatedEntities?: ObjectLiteral[]): Promise<any[]>; /** * Loads relation ids for the one-to-many and one-to-one not owner relations. */ protected loadForOneToManyAndOneToOneNotOwner(relation: RelationMetadata, entities: ObjectLiteral[], relatedEntities?: ObjectLiteral[]): Promise<any[]>; } interface QueryBuilderCteOptions { /** * Supported only by Postgres currently * Oracle users should use query with undocumented materialize hint */ materialized?: boolean; /** * Supported by Postgres, SQLite, MySQL and MariaDB * SQL Server automatically detects recursive queries */ recursive?: boolean; /** * Overwrite column names * If number of columns returned doesn't work, it throws */ columnNames?: string[]; } /** */ declare class Alias { type: "from" | "select" | "join" | "other"; name: string; /** * Table on which this alias is applied. * Used only for aliases which select custom tables. */ tablePath?: string; /** * If this alias is for sub query. */ subQuery?: string; constructor(alias?: Alias); private _metadata?; get target(): Function | string; get hasMetadata(): boolean; set metadata(metadata: EntityMetadata); get metadata(): EntityMetadata; } /** * Stores all join attributes which will be used to build a JOIN query. */ declare class JoinAttribute { private connection; private queryExpressionMap; /** * Join direction. */ direction: "LEFT" | "INNER"; /** * Alias of the joined (destination) table. */ alias: Alias; /** * Joined table, entity target, or relation in "post.category" format. */ entityOrProperty: Function | string; /** * Extra condition applied to "ON" section of join. */ condition?: string; /** * Property + alias of the object where to joined data should be mapped. */ mapToProperty?: string; /** * Indicates if user maps one or many objects from the join. */ isMappingMany?: boolean; /** * Useful when the joined expression is a custom query to support mapping. */ mapAsEntity?: Function | string; constructor(connection: DataSource, queryExpressionMap: QueryExpressionMap, joinAttribute?: JoinAttribute); get isMany(): boolean; isSelectedCache: boolean; isSelectedEvaluated: boolean; /** * Indicates if this join is selected. */ get isSelected(): boolean; /** * Name of the table which we should join. */ get tablePath(): string; /** * Alias of the parent of this join. * For example, if we join ("post.category", "categoryAlias") then "post" is a parent alias. * This value is extracted from entityOrProperty value. * This is available when join was made using "post.category" syntax. */ get parentAlias(): string | undefined; /** * Relation property name of the parent. * This is used to understand what is joined. * For example, if we join ("post.category", "categoryAlias") then "category" is a relation property. * This value is extracted from entityOrProperty value. * This is available when join was made using "post.category" syntax. */ get relationPropertyPath(): string | undefined; relationCache: RelationMetadata | undefined; relationEvaluated: boolean; /** * Relation of the parent. * This is used to understand what is joined. * This is available when join was made using "post.category" syntax. * Relation can be undefined if entityOrProperty is regular entity or custom table. */ get relation(): RelationMetadata | undefined; /** * Metadata of the joined entity. * If table without entity was joined, then it will return undefined. */ get metadata(): EntityMetadata | undefined; /** * Generates alias of junction table, whose ids we get. */ get junctionAlias(): string; get mapToPropertyParentAlias(): string | undefined; get mapToPropertyPropertyName(): string | undefined; } interface SelectQuery { selection: string; aliasName?: string; virtual?: boolean; } type SelectQueryBuilderOption = "disable-global-order" | "create-pojo"; type WrappingOperator = "not" | "brackets"; type PredicateOperator = "lessThan" | "lessThanOrEqual" | "moreThan" | "moreThanOrEqual" | "equal" | "notEqual" | "ilike" | "like" | "between" | "in" | "any" | "isNull" | "arrayContains" | "arrayContainedBy" | "arrayOverlap" | "and" | "jsonContains" | "or"; interface WherePredicateOperator { operator: PredicateOperator; parameters: string[]; } interface WhereWrappingOperator { operator: WrappingOperator; condition: WhereClauseCondition; } interface WhereClause { type: "simple" | "and" | "or"; condition: WhereClauseCondition; } type WhereClauseCondition = string | WherePredicateOperator | WhereWrappingOperator | WhereClause[]; /** * Contains all properties of the QueryBuilder that needs to be build a final query. */ declare class QueryExpressionMap { protected connection: DataSource; /** * Strategy to load relations. */ relationLoadStrategy: "join" | "query"; /** * Indicates if QueryBuilder used to select entities and not a raw results. */ queryEntity: boolean; /** * Main alias is a main selection object selected by QueryBuilder. */ mainAlias?: Alias; /** * All aliases (including main alias) used in the query. */ aliases: Alias[]; /** * Represents query type. QueryBuilder is able to build SELECT, UPDATE and DELETE queries. */ queryType: "select" | "update" | "delete" | "insert" | "relation" | "soft-delete" | "restore"; /** * Data needs to be SELECT-ed. */ selects: SelectQuery[]; /** * Max execution time in millisecond. */ maxExecutionTime: number; /** * Whether SELECT is DISTINCT. */ selectDistinct: boolean; /** * SELECT DISTINCT ON query (postgres). */ selectDistinctOn: string[]; /** * FROM-s to be selected. */ /** * If update query was used, it needs "update set" - properties which will be updated by this query. * If insert query was used, it needs "insert set" - values that needs to be inserted. */ valuesSet?: ObjectLiteral | ObjectLiteral[]; /** * Optional returning (or output) clause for insert, update or delete queries. */ returning: string | string[]; /** * Extra returning columns to be added to the returning statement if driver supports it. */ extraReturningColumns: ColumnMetadata[]; /** * Optional on conflict statement used in insertion query in postgres. */ onConflict: string; /** * Optional on ignore statement used in insertion query in databases. */ onIgnore: boolean; /** * Optional on update statement used in insertion query in databases. */ onUpdate: { conflict?: string | string[]; columns?: string[]; overwrite?: string[]; skipUpdateIfNoValuesChanged?: boolean; indexPredicate?: string; upsertType?: UpsertType; }; /** * JOIN queries. */ joinAttributes: JoinAttribute[]; /** * RelationId queries. */ relationIdAttributes: RelationIdAttribute[]; /** * Relation count queries. */ relationCountAttributes: RelationCountAttribute[]; /** * WHERE queries. */ wheres: WhereClause[]; /** * HAVING queries. */ havings: { type: "simple" | "and" | "or"; condition: string; }[]; /** * ORDER BY queries. */ orderBys: OrderByCondition; /** * GROUP BY queries. */ groupBys: string[]; /** * LIMIT query. */ limit?: number; /** * OFFSET query. */ offset?: number; /** * Number of rows to skip of result using pagination. */ skip?: number; /** * Number of rows to take using pagination. */ take?: number; /** * Use certain index for the query. * * SELECT * FROM table_name USE INDEX (col1_index, col2_index) WHERE col1=1 AND col2=2 AND col3=3; */ useIndex?: string; /** * Locking mode. */ lockMode?: "optimistic" | "pessimistic_read" | "pessimistic_write" | "dirty_read" | "pessimistic_partial_write" | "pessimistic_write_or_fail" | "for_no_key_update" | "for_key_share"; /** * Current version of the entity, used for locking. */ lockVersion?: number | Date; /** * Tables to be specified in the "FOR UPDATE OF" clause, referred by their alias */ lockTables?: string[]; /** * Modify behavior when encountering locked rows. NOWAIT or SKIP LOCKED */ onLocked?: "nowait" | "skip_locked"; /** * Indicates if soft-deleted rows should be included in entity result. * By default the soft-deleted rows are not included. */ withDeleted: boolean; /** * Parameters used to be escaped in final query. */ parameters: ObjectLiteral; /** * Indicates if alias, table names and column names will be escaped by driver, or not. * * todo: rename to isQuotingDisabled, also think if it should be named "escaping" */ disableEscaping: boolean; /** * Indicates if virtual columns should be included in entity result. * * todo: what to do with it? is it properly used? what about persistence? */ enableRelationIdValues: boolean; /** * Extra where condition appended to the end of original where conditions with AND keyword. * Original condition will be wrapped into brackets. */ extraAppendedAndWhereCondition: string; /** * Indicates if query builder creates a subquery. */ subQuery: boolean; /** * Indicates if property names are prefixed with alias names during property replacement. * By default this is enabled, however we need this because aliases are not supported in UPDATE and DELETE queries, * but user can use them in WHERE expressions. */ aliasNamePrefixingEnabled: boolean; /** * Indicates if query result cache is enabled or not. * It is undefined by default to avoid overriding the `alwaysEnabled` config */ cache?: boolean; /** * Time in milliseconds in which cache will expire. * If not set then global caching time will be used. */ cacheDuration: number; /** * Cache id. * Used to identifier your cache queries. */ cacheId: string; /** * Options that define QueryBuilder behaviour. */ options: SelectQueryBuilderOption[]; /** * Property path of relation to work with. * Used in relational query builder. */ relationPropertyPath: string; /** * Entity (target) which relations will be updated. */ of: any | any[]; /** * List of columns where data should be inserted. * Used in INSERT query. */ insertColumns: string[]; /** * Used if user wants to update or delete a specific entities. */ whereEntities: ObjectLiteral[]; /** * Indicates if entity must be updated after insertion / updation. * This may produce extra query or use RETURNING / OUTPUT statement (depend on database). */ updateEntity: boolean; /** * Indicates if listeners and subscribers must be called before and after query execution. */ callListeners: boolean; /** * Indicates if query must be wrapped into transaction. */ useTransaction: boolean; /** * Indicates if query should be time travel query * https://www.cockroachlabs.com/docs/stable/as-of-system-time.html */ timeTravel?: boolean | string; /** * Extra parameters. * * @deprecated Use standard parameters instead */ nativeParameters: ObjectLiteral; /** * Query Comment to include extra information for debugging or other purposes. */ comment?: string; /** * Items from an entity that have been locally generated & are recorded here for later use. * Examples include the UUID generation when the database does not natively support it. * These are included in the entity index order. */ locallyGenerated: { [key: number]: ObjectLiteral; }; commonTableExpressions: { queryBuilder: QueryBuilder<any> | string; alias: string; options: QueryBuilderCteOptions; }[]; constructor(connection: DataSource); /** * Get all ORDER BY queries - if order by is specified by user then it uses them, * otherwise it uses default entity order by if it was set. */ get allOrderBys(): OrderByCondition; /** * Creates a main alias and adds it to the current expression map. */ setMainAlias(alias: Alias): Alias; /** * Creates a new alias and adds it to the current expression map. */ createAlias(options: { type: "from" | "select" | "join" | "other"; name?: string; target?: Function | string; tablePath?: string; subQuery?: string; metadata?: EntityMetadata; }): Alias; /** * Finds alias with the given name. * If alias was not found it throw an exception. */ findAliasByName(aliasName: string): Alias; findColumnByAliasExpression(aliasExpression: string): ColumnMetadata | undefined; /** * Gets relation metadata of the relation this query builder works with. * * todo: add proper exceptions */ get relationMetadata(): RelationMetadata; /** * Copies all properties of the current QueryExpressionMap into a new one. * Useful when QueryBuilder needs to create a copy of itself. */ clone(): QueryExpressionMap; } /** * Syntax sugar. * Allows to use brackets in WHERE expressions for better syntax. */ declare class Brackets { readonly "@instanceof": symbol; /** * WHERE expression that will be taken into brackets. */ whereFactory: (qb: WhereExpressionBuilder) => any; /** * Given WHERE query builder that will build a WHERE expression that will be taken into brackets. */ constructor(whereFactory: (qb: WhereExpressionBuilder) => any); } /** * Query Builders can implement this interface to support where expression */ interface WhereExpressionBuilder { /** * Sets WHERE condition in the query builder. * If you had previously WHERE expression defined, * calling this function will override previously set WHERE conditions. * Additionally you can add parameters used in where expression. */ where(where: string, parameters?: ObjectLiteral): this; /** * Sets WHERE condition in the query builder. * If you had previously WHERE expression defined, * calling this function will override previously set WHERE conditions. * Additionally you can add parameters used in where expression. */ where(where: Brackets, parameters?: ObjectLiteral): this; /** * Sets WHERE condition in the query builder. * If you had previously WHERE expression defined, * calling this function will override previously set WHERE conditions. * Additionally you can add parameters used in where expression. */ where(where: ObjectLiteral, parameters?: ObjectLiteral): this; /** * Sets WHERE condition in the query builder. * If you had previously WHERE expression defined, * calling this function will override previously set WHERE conditions. * Additionally you can add parameters used in where expression. */ where(where: ObjectLiteral[], parameters?: ObjectLiteral): this; /** * Sets WHERE condition in the query builder. * If you had previously WHERE expression defined, * calling this function will override previously set WHERE conditions. * Additionally you can add parameters used in where expression. */ where(subQuery: (qb: this) => string, parameters?: ObjectLiteral): this; /** * Adds new AND WHERE condition in the query builder. * Additionally you can add parameters used in where expression. */ andWhere(where: string, parameters?: ObjectLiteral): this; /** * Adds new AND WHERE condition in the query builder. * Additionally you can add parameters used in where expression. */ andWhere(where: Brackets, parameters?: ObjectLiteral): this; /** * Adds new AND WHERE condition in the query builder. * Additionally you can add parameters used in where expression. */ andWhere(where: ObjectLiteral, parameters?: ObjectLiteral): this; /** * Adds new AND WHERE condition in the query builder. * Additionally you can add parameters used in where expression. */ andWhere(where: ObjectLiteral[], parameters?: ObjectLiteral): this; /** * Adds new AND WHERE condition in the query builder. * Additionally you can add parameters used in where expression. */ andWhere(subQuery: (qb: this) => string, parameters?: ObjectLiteral): this; /** * Adds new OR WHERE condition in the query builder. * Additionally you can add parameters used in where expression. */ orWhere(where: string, parameters?: ObjectLiteral): this; /** * Adds new OR WHERE condition in the query builder. * Additionally you can add parameters used in where expression. */ orWhere(where: Brackets, parameters?: ObjectLiteral): this; /** * Adds new OR WHERE condition in the query builder. * Additionally you can add parameters used in where expression. */ orWhere(where: ObjectLiteral, parameters?: ObjectLiteral): this; /** * Adds new OR WHERE condition in the query builder. * Additionally you can add parameters used in where expression. */ orWhere(where: ObjectLiteral[], parameters?: ObjectLiteral): this; /** * Adds new OR WHERE condition in the query builder. * Additionally you can add parameters used in where expression. */ orWhere(subQuery: (qb: this) => string, parameters?: ObjectLiteral): this; /** * Sets WHERE condition in the query builder with a condition for the given ids. * If you had previously WHERE expression defined, * calling this function will override previously set WHERE conditions. * * Ids are mixed. * It means if you have single primary key you can pass a simple id values, for example [1, 2, 3]. * If you have multiple primary keys you need to pass object with property names and values specified, * for example [{ firstId: 1, secondId: 2 }, { firstId: 2, secondId: 3 }, ...] */ whereInIds(ids: any | any[]): this; /** * Adds new AND WHERE with conditions for the given ids. * * Ids are mixed. * It means if you have single primary key you can pass a simple id values, for example [1, 2, 3]. * If you have multiple primary keys you need to pass object with property names and values specified, * for example [{ firstId: 1, secondId: 2 }, { firstId: 2, secondId: 3 }, ...] */ andWhereInIds(ids: any | any[]): this; /** * Adds new OR WHERE with conditions for the given ids. * * Ids are mixed. * It means if you have single primary key you can pass a simple id values, for example [1, 2, 3]. * If you have multiple primary keys you need to pass object with property names and values specified, * for example [{ firstId: 1, secondId: 2 }, { firstId: 2, secondId: 3 }, ...] */ orWhereInIds(ids: any | any[]): this; } /** * Allows to build complex sql queries in a fashion way and execute those queries. */ declare class UpdateQueryBuilder<Entity extends ObjectLiteral> extends QueryBuilder<Entity> implements WhereExpressionBuilder { readonly "@instanceof": symbol; constructor(connectionOrQueryBuilder: DataSource | QueryBuilder<any>, queryRunner?: QueryRunner); /** * Gets generated SQL query without parameters being replaced. */ getQuery(): string; /** * Executes sql generated by query builder and returns raw database results. */ execute(): Promise<UpdateResult>; /** * Values needs to be updated. */ set(values: QueryDeepPartialEntity<Entity>): this; /** * Sets WHERE condition in the query builder. * If you had previously WHERE expression defined, * calling this function will override previously set WHERE conditions. * Additionally you can add parameters used in where expression. */ where(where: string | ((qb: this) => string) | Brackets | ObjectLiteral | ObjectLiteral[], parameters?: ObjectLiteral): this; /** * Adds new AND WHERE condition in the query builder. * Additionally you can add parameters used in where expression. */ andWhere(where: string | ((qb: this) => string) | Brackets | ObjectLiteral | ObjectLiteral[], parameters?: ObjectLiteral): this; /** * Adds new OR WHERE condition in the query builder. * Additionally you can add parameters used in where expression. */ orWhere(where: string | ((qb: this) => string) | Brackets | ObjectLiteral | ObjectLiteral[], parameters?: ObjectLiteral): this; /** * Sets WHERE condition in the query builder with a condition for the given ids. * If you had previously WHERE expression defined, * calling this function will override previously set WHERE conditions. */ whereInIds(ids: any | any[]): this; /** * Adds new AND WHERE with conditions for the given ids. */ andWhereInIds(ids: any | any[]): this; /** * Adds new OR WHERE with conditions for the given ids. */ orWhereInIds(ids: any | any[]): this; /** * Optional returning/output clause. * This will return given column values. */ output(columns: string[]): this; /** * Optional returning/output clause. * Returning is a SQL string containing returning statement. */ output(output: string): this; /** * Optional returning/output clause. */ output(output: string | string[]): this; /** * Optional returning/output clause. * This will return given column values. */ returning(columns: string[]): this; /** * Optional returning/output clause. * Returning is a SQL string containing returning statement. */ returning(returning: string): this; /** * Optional returning/output clause. */ returning(returning: string | string[]): this; /** * Sets ORDER BY condition in the query builder. * If you had previously ORDER BY expression defined, * calling this function will override previously set ORDER BY conditions. * * Calling order by without order set will remove all previously set order bys. */ orderBy(): this; /** * Sets ORDER BY condition in the query builder. * If you had previously ORDER BY expression defined, * calling this function will override previously set ORDER BY conditions. */ orderBy(sort: string, order?: "ASC" | "DESC", nulls?: "NULLS FIRST" | "NULLS LAST"): this; /** * Sets ORDER BY condition in the query builder. * If you had previously ORDER BY expression defined, * calling this function will override previously set ORDER BY conditions. */ orderBy(order: OrderByCondition): this; /** * Adds ORDER BY condition in the query builder. */ addOrderBy(sort: string, order?: "ASC" | "DESC", nulls?: "NULLS FIRST" | "NULLS LAST"): this; /** * Sets LIMIT - maximum number of rows to be selected. */ limit(limit?: number): this; /** * Indicates if entity must be updated after update operation. * This may produce extra query or use RETURNING / OUTPUT statement (depend on database). * Enabled by default. */ whereEntity(entity: Entity | Entity[]): this; /** * Indicates if entity must be updated after update operation. * This may produce extra query or use RETURNING / OUTPUT statement (depend on database). * Enabled by default. */ updateEntity(enabled: boolean): this; /** * Creates UPDATE express used to perform insert query. */ protected createUpdateExpression(): string; /** * Creates "ORDER BY" part of SQL query. */ protected createOrderByExpression(): string; /** * Creates "LIMIT" parts of SQL query. */ protected createLimitExpression(): string; /** * Gets array of values need to be inserted into the target table. */ protected getValueSet(): ObjectLiteral; } /** * Allows to build complex sql queries in a fashion way and execute those queries. */ declare class DeleteQueryBuilder<Entity extends ObjectLiteral> extends QueryBuilder<Entity> implements WhereExpressionBuilder { readonly "@instanceof": symbol; constructor(connectionOrQueryBuilder: DataSource | QueryBuilder<any>, queryRunner?: QueryRunner); /** * Gets generated SQL query without parameters being replaced. */ getQuery(): string; /** * Executes sql generated by query builder and returns raw database results. */ execute(): Promise<DeleteResult>; /** * Specifies FROM which entity's table select/update/delete will be executed. * Also sets a main string alias of the selection data. */ from<T extends ObjectLiteral>(entityTarget: EntityTarget<T>, aliasName?: string): DeleteQueryBuilder<T>; /** * Sets WHERE condition in the query builder. * If you had previously WHERE expression defined, * calling this function will override previously set WHERE conditions. * Additionally you can add parameters used in where expression. */ where(where: Brackets | string | ((qb: this) => string) | ObjectLiteral | ObjectLiteral[], parameters?: ObjectLiteral): this; /** * Adds new AND WHERE condition in the query builder. * Additionally you can add parameters used in where expression. */ andWhere(where: Brackets | string | ((qb: this) => string) | ObjectLiteral | ObjectLiteral[], parameters?: ObjectLiteral): this; /** * Adds new OR WHERE condition in the query builder. * Additionally you can add parameters used in where expression. */ orWhere(where: Brackets | string | ((qb: this) => string) | ObjectLiteral | ObjectLiteral[], parameters?: ObjectLiteral): this; /** * Sets WHERE condition in the query builder with a condition for the given ids. * If you had previously WHERE expression defined, * calling this function will override previously set WHERE conditions. */ whereInIds(ids: any | any[]): this; /** * Adds new AND WHERE with conditions for the given ids. */ andWhereInIds(ids: any | any[]): this; /** * Adds new OR WHERE with conditions for the given ids. */ orWhereInIds(ids: any | any[]): this; /** * Optional returning/output clause. * This will return given column values. */ output(columns: string[]): this; /** * Optional returning/output clause. * Returning is a SQL string containing returning statement. */ output(output: string): this; /** * Optional returning/output clause. */ output(output: string | string[]): this; /** * Optional returning/output clause. * This will return given column values. */ returning(columns: string[]): this; /** * Optional returning/output clause. * Returning is a SQL string containing returning statement. */ returning(returning: string): this; /** * Optional returning/output clause. */ returning(returning: string | string[]): this; /** * Creates DELETE express used to perform query. */ protected createDeleteExpression(): string; } /** * Allows to build complex sql queries in a fashion way and execute those queries. */ declare class SoftDeleteQueryBuilder<Entity extends ObjectLiteral> extends QueryBuilder<Entity> implements WhereExpressionBuilder { readonly "@instanceof": symbol; constructor(connectionOrQueryBuilder: DataSource | QueryBuilder<any>, queryRunner?: QueryRunner); /** * Gets generated SQL query without parameters being replaced. */ getQuery(): string; /** * Executes sql generated by query builder and returns raw database results. */ execute(): Promise<UpdateResult>; /** * Specifies FROM which entity's table select/update/delete/soft-delete will be executed. * Also sets a main string alias of the selection data. */ from<T extends ObjectLiteral>(entityTarget: EntityTarget<T>, aliasName?: string): SoftDeleteQueryBuilder<T>; /** * Sets WHERE condition in the query builder. * If you had previously WHERE expression defined, * calling this function will override previously set WHERE conditions. * Additionally you can add parameters used in where expression. */ where(where: string | ((qb: this) => string) | Brackets | ObjectLiteral | ObjectLiteral[], parameters?: ObjectLiteral): this; /** * Adds new AND WHERE condition in the query builder. * Additionally you can add parameters used in where expression. */ andWhere(where: string | ((qb: this) => string) | Brackets | ObjectLiteral | ObjectLiteral[], parameters?: ObjectLiteral): this; /** * Adds new OR WHERE condition in the query builder. * Additionally you can add parameters used in where expression. */ orWhere(where: string | ((qb: this) => string) | Brackets | ObjectLiteral | ObjectLiteral[], parameters?: ObjectLiteral): this; /** * Adds new AND WHERE with conditions for the given ids. */ whereInIds(ids: any | any[]): this; /** * Adds new AND WHERE with conditions for the given ids. */ andWhereInIds(ids: any | any[]): this; /** * Adds new OR WHERE with conditions for the given ids. */ orWhereInIds(ids: any | any[]): this; /** * Optional returning/output clause. * This will return given column values. */ output(columns: string[]): this; /** * Optional returning/output clause. * Returning is a SQL string containing returning statement. */ output(output: string): this; /** * Optional returning/output clause. */ output(output: string | string[]): this; /** * Optional returning/output clause. * This will return given column values. */ returning(columns: string[]): this; /** * Optional returning/output clause. * Returning is a SQL string containing returning statement. */ returning(returning: string): this; /** * Optional returning/output clause. */ returning(returning: string | string[]): this; /** * Sets ORDER BY condition in the query builder. * If you had previously ORDER BY expression defined, * calling this function will override previously set ORDER BY conditions. * * Calling order by without order set will remove all previously set order bys. */ orderBy(): this; /** * Sets ORDER BY condition in the query builder. * If you had previously ORDER BY expression defined, * calling this function will override previously set ORDER BY conditions. */ orderBy(sort: string, order?: "ASC" | "DESC", nulls?: "NULLS FIRST" | "NULLS LAST"): this; /** * Sets ORDER BY condition in the query builder. * If you had previously ORDER BY expression defined, * calling this function will override previously set ORDER BY conditions. */ orderBy(order: OrderByCondition): this; /** * Adds ORDER BY condition in the query builder. */ addOrderBy(sort: string, order?: "ASC" | "DESC", nulls?: "NULLS FIRST" | "NULLS LAST"): this; /** * Sets LIMIT - maximum number of rows to be selected. */ limit(limit?: number): this; /** * Indicates if entity must be updated after update operation. * This may produce extra query or use RETURNING / OUTPUT statement (depend on database). * Enabled by default. */ whereEntity(entity: Entity | Entity[]): this; /** * Indicates if entity must be updated after update operation. * This may produce extra query or use RETURNING / OUTPUT statement (depend on database). * Enabled by default. */ updateEntity(enabled: boolean): this; /** * Creates UPDATE express used to perform insert query. */ protected createUpdateExpression(): string; /** * Creates "ORDER BY" part of SQL query. */ protected createOrderByExpression(): string; /** * Creates "LIMIT" parts of SQL query. */ protected createLimitExpression(): string; } /** * Allows to build complex sql queries in a fashion way and execute those queries. */ declare class InsertQueryBuilder<Entity extends ObjectLiteral> extends QueryBuilder<Entity> { readonly "@instanceof": symbol; /** * Gets generated SQL query without parameters being replaced. */ getQuery(): string; /** * Executes sql generated by query builder and returns raw database results. */ execute(): Promise<InsertResult>; /** * Specifies INTO which entity's table insertion will be executed. */ into<T extends ObjectLiteral>(entityTarget: EntityTarget<T>, columns?: string[]): InsertQueryBuilder<T>; /** * Values needs to be inserted into table. */ values(values: QueryDeepPartialEntity<Entity> | QueryDeepPartialEntity<Entity>[]): this; /** * Optional returning/output clause. * This will return given column values. */ output(columns: string[]): this; /** * Optional returning/output clause. * Returning is a SQL string containing returning statement. */ output(output: string): this; /** * Optional returning/output clause. */ output(output: string | string[]): this; /** * Optional returning/output clause. * This will return given column values. */ returning(columns: string[]): this; /** * Optional returning/output clause. * Returning is a SQL string containing returning statement. */ returning(returning: string): this; /** * Optional returning/output clause. */ returning(returning: string | string[]): this; /** * Indicates if entity must be updated after insertion operations. * This may produce extra query or use RETURNING / OUTPUT statement (depend on database). * Enabled by default. */ updateEntity(enabled: boolean): this; /** * Adds additional ON CONFLICT statement supported in postgres and cockroach. * * @deprecated Use `orIgnore` or `orUpdate` */ onConflict(statement: string): this; /** * Adds additional ignore statement supported in databases. */ orIgnore(statement?: string | boolean): this; /** * @deprecated * * `.orUpdate({ columns: [ "is_updated" ] }).setParameter("is_updated", value)` * * is now `.orUpdate(["is_updated"])` * * `.orUpdate({ conflict_target: ['date'], overwrite: ['title'] })` * * is now `.orUpdate(['title'], ['date'])` * */ orUpdate(statement?: { columns?: string[]; overwrite?: string[]; conflict_target?: string | string[]; }): this; orUpdate(overwrite: string[], conflictTarget?: string | string[], orUpdateOptions?: InsertOrUpdateOptions): this; /** * Creates INSERT express used to perform insert query. */ protected createInsertExpression(): string; /** * Gets list of columns where values must be inserted to. */ protected getInsertedColumns(): ColumnMetadata[]; /** * Creates a columns string where values must be inserted to for INSERT INTO expression. */ protected createColumnNamesExpression(): string; /** * Creates list of values needs to be inserted in the VALUES expression. */ protected createValuesExpression(): string; /** * Gets array of values need to be inserted into the target table. */ protected getValueSets(): ObjectLiteral[]; /** * Checks if column is an auto-generated primary key, but the current insertion specifies a value for it. * * @param column */ protected isOverridingAutoIncrementBehavior(column: ColumnMetadata): boolean; } /** * Allows to work with entity relations and perform specific operations with those relations. * * todo: add transactions everywhere */ declare class RelationQueryBuilder<Entity extends ObjectLiteral> extends QueryBuilder<Entity> { readonly "@instanceof": symbol; /** * Gets generated SQL query without parameters being replaced. */ getQuery(): string; /** * Sets entity (target) which relations will be updated. */ of(entity: any | any[]): this; /** * Sets entity relation's value. * Value can be entity, entity id or entity id map (if entity has composite ids). * Works only for many-to-one and one-to-one relations. * For many-to-many and one-to-many relations use #add and #remove methods instead. */ set(value: any): Promise<void>; /** * Adds (binds) given value to entity relation. * Value can be entity, entity id or entity id map (if entity has composite ids). * Value also can be array of entities, array of entity ids or array of entity id maps (if entity has composite ids). * Works only for many-to-many and one-to-many relations. * For many-to-one and one-to-one use #set method instead. */ add(value: any | any[]): Promise<void>; /** * Removes (unbinds) given value from entity relation. * Value can be entity, entity id or entity id map (if entity has composite ids). * Value also can be array of entities, array of entity ids or array of entity id maps (if entity has composite ids). * Works only for many-to-many and one-to-many relations. * For many-to-one and one-to-one use #set method instead. */ remove(value: any | any[]): Promise<void>; /** * Adds (binds) and removes (unbinds) given values to/from entity relation. * Value can be entity, entity id or entity id map (if entity has composite ids). * Value also can be array of entities, array of entity ids or array of entity id maps (if entity has composite ids). * Works only for many-to-many and one-to-many relations. * For many-to-one and one-to-one use #set method instead. */ addAndRemove(added: any | any[], removed: any | any[]): Promise<void>; /** * Gets entity's relation id. async getId(): Promise<any> { }*/ /** * Gets entity's relation ids. async getIds(): Promise<any[]> { return []; }*/ /** * Loads a single entity (relational) from the relation. * You can also provide id of relational entity to filter by. */ loadOne<T = any>(): Promise<T | undefined>; /** * Loads many entities (relational) from the relation. * You can also provide ids of relational entities to filter by. */ loadMany<T = any>(): Promise<T[]>; } /** * Syntax sugar. * Allows to use negate brackets in WHERE expressions for better syntax. */ declare class NotBrackets extends Brackets { readonly "@instanceof": symbol; } /** * Allows to build complex sql queries in a fashion way and execute those queries. */ declare abstract class QueryBuilder<Entity extends ObjectLiteral> { readonly "@instanceof": symbol; /** * Connection on which QueryBuilder was created. */ readonly connection: DataSource; /** * Contains all properties of the QueryBuilder that needs to be build a final query. */ readonly expressionMap: QueryExpressionMap; /** * Query runner used to execute query builder query. */ protected queryRunner?: QueryRunner; /** * If QueryBuilder was created in a subquery mode then its parent QueryBuilder (who created subquery) will be stored here. */ protected parentQueryBuilder: QueryBuilder<any>; /** * Memo to help keep place of current parameter index for `createParameter` */ private parameterIndex; /** * Contains all registered query builder classes. */ private static queryBuilderRegistry; /** * QueryBuilder can be initialized from given Connection and QueryRunner objects or from given other QueryBuilder. */ constructor(queryBuilder: QueryBuilder<any>); /** * QueryBuilder can be initialized from given Connection and QueryRunner objects or from given other QueryBuilder. */ constructor(connection: DataSource, queryRunner?: QueryRunner); static registerQueryBuilderClass(name: string, factory: any): void; /** * Gets generated SQL query without parameters being replaced. */ abstract getQuery(): string; /** * Gets the main alias string used in this query builder. */ get alias(): string; /** * Creates SELECT query. * Replaces all previous selections if they exist. */ select(): SelectQueryBuilder<Entity>; /** * Creates SELECT query and selects given data. * Replaces all previous selections if they exist. */ select(selection: string, selectionAliasName?: string): SelectQueryBuilder<Entity>; /** * Creates SELECT query and selects given data. * Replaces all previous selections if they exist. */ select(selection: string[]): SelectQueryBuilder<Entity>; /** * Creates INSERT query. */ insert(): InsertQueryBuilder<Entity>; /** * Creates UPDATE query and applies given update values. */ update(): UpdateQueryBuilder<Entity>; /** * Creates UPDATE query and applies given update values. */ update(updateSet: QueryDeepPartialEntity<Entity>): UpdateQueryBuilder<Entity>; /** * Creates UPDATE query for the given entity and applies given update values. */