import { Container, Constructor, IContainer, Class } from '@spinajs/di'; import { ColumnType, QueryMethod, SortOrder, WhereBoolean, SqlOperator, JoinMethod } from './enums.js'; import { IColumnsBuilder, ICompilerOutput, ILimitBuilder, IOrderByBuilder, IQueryBuilder, IQueryLimit, ISort, IWhereBuilder, QueryContext, IJoinBuilder, IBuilderMiddleware, IWithRecursiveBuilder, ReferentialAction, IGroupByBuilder, IUpdateResult, DefaultValueBuilder, ColumnAlterationType, QueryMiddleware, IBuilder, IDeleteQueryBuilder, IUpdateQueryBuilder, ISelectQueryBuilder, IJoinStatementOptions } from './interfaces.js'; import { ColumnStatement, IQueryStatement, Wrap } from './statements.js'; import { ModelDataWithRelationDataSearchable, PickRelations, Unbox, WhereFunction } from './types.js'; import type { OrmDriver } from './driver.js'; import { ModelBase } from './model.js'; import { IOrmRelation } from './relations.js'; import { DateTime } from 'luxon'; import { Lazy } from '@spinajs/util'; /** * Trick typescript by using the inbuilt interface inheritance and declaration merging * for builder classes. * * We use mixins to extend functionality of builder eg. insert query builder uses function from columns builder * and so on... */ export interface InsertQueryBuilder extends IColumnsBuilder { } export interface DeleteQueryBuilder extends IDeleteQueryBuilder { } export interface UpdateQueryBuilder extends IUpdateQueryBuilder { } export interface SelectQueryBuilder extends IColumnsBuilder, IOrderByBuilder, ILimitBuilder, IWhereBuilder, IJoinBuilder, IWithRecursiveBuilder, IGroupByBuilder { } export declare class Builder implements IBuilder { protected _driver: OrmDriver; protected _container: IContainer; protected _model?: Constructor; protected _nonSelect: boolean; protected _middlewares: IBuilderMiddleware[]; protected _queryMiddlewares: QueryMiddleware[]; protected _asRaw: boolean; QueryContext: QueryContext; get Driver(): OrmDriver; get Container(): IContainer; get Model(): Constructor | undefined; constructor(container: IContainer, driver: OrmDriver, model?: Constructor); /** * Memoized result of {@link execute}. A builder executes at most once; awaiting * it again resolves with the same value instead of re-running the query. * Call `clone()` first if you genuinely need a second round-trip. */ protected _executionPromise: Promise | null; /** * The execution engine. Sends the compiled query to the driver, applies the * result middlewares, hydrates models and awaits the post-hydration middlewares. * * Always *returns* its value — the caller's promise chain is what propagates it. * Subclasses override this (not `execute()`) so that their extra work also lands * inside the memo. */ protected _run(): Promise; /** * Executes the query. The single entry point for execution — `then()` delegates here. * The underlying work runs exactly once per builder instance; subsequent calls resolve * with the memoized result. */ execute(): Promise; then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null): PromiseLike; catch(onrejected?: ((reason: any) => TResult | PromiseLike) | null): Promise; finally(onfinally?: (() => void) | null): Promise; middleware(middleware: IBuilderMiddleware): this; /** * Builds query that is ready to use in DB */ toDB(): ICompilerOutput | ICompilerOutput[]; } /** * Base class for queires. Implements basic query functionality * */ export declare class QueryBuilder extends Builder implements IQueryBuilder { protected _method: QueryMethod; protected _table: string; protected _tableAlias: string; protected _database: string; constructor(container: IContainer, driver: OrmDriver, model?: Constructor); /** * SQL table name that query is executed on * * @example * SELECT * FROM `users` */ get Table(): string; /** * DB table alias */ get TableAlias(): string; /** * SQL schema/database name that query is executed on. * * @example * SELECT * FROM `spinejs`.`users` as u */ get Database(): string; /** * Sets schema to this query. * * @param database - schema or database name in database */ database(database: string): this; /** * Sets table that query is executed on * * @param table - sql table name * @param alias - sql table alias * * @example * * this.setTable("user","u") * */ setTable(table: string, alias?: string): this; /** * Sets table alias for query * * @param alias - sql table alias */ setAlias(alias: string): this; from(table: string, alias?: string): this; } export declare class LimitBuilder implements ILimitBuilder { protected _first: boolean; protected _limit: IQueryLimit; constructor(); take(count: number): this; skip(count: number): this; takeFirst(): this; first(): Promise; firstOrFail(): Promise; orThrow(error: Error | ((output: ICompilerOutput) => Error)): Promise; firstOrThrow(error: Error | ((output: ICompilerOutput) => Error)): Promise; getLimits(): IQueryLimit; } /** * The sort direction a caller meant. Case is not the caller's business - `asc` off a query string * and `SortOrder.ASC` are one order - but anything else would reach the statement verbatim. */ export declare function sortOrderOf(order?: string | SortOrder | null): SortOrder; export declare class OrderByBuilder implements IOrderByBuilder { protected _sorts: ISort[]; protected _orderable: string[]; constructor(); /** * Identifiers this query yields that are no columns of its model - the aliases of a raw select, * which nothing can read back out of the SQL. Declaring them at the point they are selected is * what lets {@link SelectQueryBuilder.validateSorts} keep checking a query that selects raw SQL * instead of waving it through. */ orderable(...columns: string[]): this; getOrderable(): string[]; /** * Appends to this query's ORDER BY. Takes a column with a direction, one sort object, or a list * of them - a list is how a caller expresses "what was asked for, then the fallback": an entry * with no column is dropped, and a column already sorted on is not repeated, so * `order([requested, { column: 'id', order: SortOrder.DESC }])` orders by the request when there * is one and by `id` either way, which is what keeps paging stable. * * `Relation.column` orders by a column of a to-one relation, which rides in this query as a * join. A to-many relation is fetched by a query of its own, where ordering rearranges the * children and leaves this result set as it was, so it is refused rather than silently ignored. */ order(column: string, direction?: SortOrder): this; order(sort: Partial | Array | null | undefined> | null | undefined): this; orderBy(column: string): this; orderByDescending(column: string): this; /** * Refuses `Relation.column` where the relation is not to-one. Unknown relations are left to * `populate()`, which names them in its own error. */ protected _assertOrderableRelation(relation: string, column: string): void; /** * Returns the FIRST sort entry (or null) for backward compat with dialect * packages that emit a single ORDER BY column. Use getSorts() for all entries. */ getSort(): ISort | null; /** * Returns all sort entries (multi-column ORDER BY), skipping empty columns. */ getSorts(): ISort[]; } export declare class ColumnsBuilder implements IColumnsBuilder { protected _container: Container; protected _columns: IQueryStatement[]; protected _tableAlias: string; protected _model?: Constructor; constructor(); /** * Clears all select clauses from the query. * * @example * * query.columns() * */ clearColumns(): this; columns(names: string[]): this; select(column: string | RawQuery | Map, alias?: string): this; getColumns(): IQueryStatement[]; } export declare class RawQuery { get Query(): string; get Bindings(): any[]; static create(query: string, bindings?: any[]): RawQuery; private _query; private _bindings; constructor(query: string, bindings?: any[]); } export declare class GroupByBuilder implements IGroupByBuilder { protected _container: Container; protected _groupStatements: IQueryStatement[]; get GroupStatements(): IQueryStatement[]; clearGroupBy(): this; groupBy(expression: string | RawQuery): this; } export declare class JoinBuilder implements IJoinBuilder { protected _model?: Constructor; get JoinStatements(): IQueryStatement[]; protected _joinStatements: IQueryStatement[]; protected _container: Container; protected _tableAlias: string; constructor(container: Container); clearJoins(): this; innerJoin(arg1: string | IJoinStatementOptions | Constructor | RawQuery, arg2?: (this: IWhereBuilder) => void, arg3?: (this: ISelectQueryBuilder) => void): this; leftJoin(arg1: string | IJoinStatementOptions | Constructor | RawQuery, arg2?: (this: IWhereBuilder) => void, arg3?: (this: ISelectQueryBuilder) => void): this; leftOuterJoin(arg1: string | IJoinStatementOptions | Constructor | RawQuery, arg2?: (this: IWhereBuilder) => void, arg3?: (this: ISelectQueryBuilder) => void): this; rightJoin(arg1: string | IJoinStatementOptions | Constructor | RawQuery, arg2?: (this: IWhereBuilder) => void, arg3?: (this: ISelectQueryBuilder) => void): this; rightOuterJoin(arg1: string | IJoinStatementOptions | Constructor | RawQuery, arg2?: (this: IWhereBuilder) => void, arg3?: (this: ISelectQueryBuilder) => void): this; fullOuterJoin(arg1: string | IJoinStatementOptions | Constructor | RawQuery, arg2?: (this: IWhereBuilder) => void, arg3?: (this: ISelectQueryBuilder) => void): this; crossJoin(arg1: string | IJoinStatementOptions | Constructor | RawQuery, arg2?: (this: IWhereBuilder) => void, arg3?: (this: ISelectQueryBuilder) => void): this; join(method: JoinMethod, arg1: string | IJoinStatementOptions | Constructor | RawQuery, arg2?: (this: IWhereBuilder) => void, arg3?: (this: ISelectQueryBuilder) => void): this; } export declare class WithRecursiveBuilder implements IWithRecursiveBuilder { protected _container: Container; protected _cteStatement: IQueryStatement | undefined; get CteRecursive(): IQueryStatement | undefined; withRecursive(rcKeyName: string, pkName: string): this; /** * Drops the recursive CTE from this builder. * * `WithRecursiveStatement.build()` compiles two CLONES of the owning query — the anchor * member and the recursive member of the CTE. `clone()` copies `_cteStatement`, so each * clone was still marked recursive and compiling it re-entered `build()`, which cloned * again: an unbounded mutual recursion between `toDB()` and the recursive compiler that * ended in a stack overflow rather than a query. The two member queries are by definition * not themselves recursive, so the statement clears the flag on its clones. * * Named alongside `clearJoins()` / `clearWhere()`, which `build()` already uses to strip the * parts of the parent query each member must not inherit. */ clearRecursive(): this; } export declare class WhereBuilder implements IWhereBuilder { protected _statements: IQueryStatement[]; protected _boolean: WhereBoolean; protected _container: Container; protected _model: Constructor; protected _parent: WhereBuilder; protected _tableAlias: string; get TableAlias(): string; get Model(): Constructor>; get Container(): Container; get Statements(): IQueryStatement[]; get Op(): WhereBoolean; constructor(parent: WhereBuilder); clone

>(_parent: P): WhereBuilder; /** * The builder this one is nested in, or `undefined` for a top level builder. * * Exposed so a statement that owns a nested where-builder can re-attach a clone of it to * the same parent when it is cloned without being handed one. */ get Parent(): IWhereBuilder | undefined; /** * Pushes a statement onto this builder, stamping it with the currently pending * boolean connector (set by {@link orWhere}/{@link andWhere}). The pending * connector applies to the NEXT pushed statement only and resets to AND * afterwards, so `where(a).where(b).orWhere(c).where(d)` compiles to * `a AND b OR c AND d` rather than rewriting the whole clause. */ protected pushStatement(statement: IQueryStatement): this; when(condition: boolean, callback?: WhereFunction, callbackElse?: WhereFunction): this; where(column: string | boolean | WhereFunction | Lazy | RawQuery | Wrap | Partial>> | PickRelations, operator?: SqlOperator | any, value?: any): this; orWhere(column: string | boolean | WhereFunction | Lazy | RawQuery | Wrap | Partial>>, ..._args: any[]): this; andWhere(column: string | boolean | WhereFunction | Lazy | RawQuery | Wrap | Partial>>, ..._args: any[]): this; whereObject(obj: any): this; whereNotNull(column: string): this; whereNull(column: string): this; whereNot(column: string, val: any): this; whereIn(column: string, val: any[] | ISelectQueryBuilder): this; whereNotIn(column: string, val: any[] | ISelectQueryBuilder): this; whereExist(query: ISelectQueryBuilder | string, callback?: WhereFunction): this; whereNotExists(query: ISelectQueryBuilder | string, callback?: WhereFunction): this; /** * Shared implementation for {@link whereExist} / {@link whereNotExists}. * * For a ready sub-query it pushes an {@link ExistsQueryStatement} directly. For a relation * name it resolves the matching {@link ExistsRelationHandler} from the container (one per * {@link RelationType}) and lets it either mutate this builder or return a correlated * sub-query that we then wrap in EXISTS / NOT EXISTS. * * @param query relation name or a ready sub-query * @param negated `true` for NOT EXISTS, `false` for EXISTS * @param callback optional where-callback applied to the relation sub-query */ protected buildExistsClause(query: ISelectQueryBuilder | string, negated: boolean, callback?: WhereFunction): this; whereBetween(column: string, val: any[]): this; whereNotBetween(column: string, val: any[]): this; whereOnJoin(callback: WhereFunction): this; whereInSet(column: string, val: any[]): this; whereNotInSet(column: string, val: any[]): this; clearWhere(): this; } export declare class SelectQueryBuilder extends QueryBuilder { /** * column query props */ protected _distinct: boolean; protected _columns: IQueryStatement[]; /** * limit query props */ protected _fail: boolean; protected _first: boolean; protected _limit: IQueryLimit; /** * order by query props */ protected _sorts: ISort[]; protected _orderable: string[]; /** * where query props */ protected _statements: IQueryStatement[]; protected _boolean: WhereBoolean; protected _joinStatements: IQueryStatement[]; protected _groupStatements: IQueryStatement[]; protected _cteStatement: IQueryStatement | undefined; protected _relations: IOrmRelation[]; protected _owner: IOrmRelation | undefined; /** * The outer builder this query is correlated to, set when this query is the sub-select of a * correlated EXISTS ( see {@link ExistsRelationHandler} ). * * The correlation predicate — `. = .` — cannot be * frozen into a string when the sub-query is built, because the outer alias is often assigned * afterwards ( `populate()` calls `setAlias()` ). It is therefore emitted from a lazy * statement that reads the outer alias at COMPILE time, and this field is the link it reads * it through. * * It is a field rather than a closure variable precisely so that `clone()` can REBIND it: a * cloned query must correlate against ITSELF, not against the query it was cloned from. A * closure could not be rebound, and the clone silently kept pointing at the original — see * `ExistsQueryStatement.clone()`. */ protected _correlationSource: IWhereBuilder | undefined; get Statements(): IQueryStatement[]; /** * The outer builder this query is correlated to, or `undefined` when it is not a correlated * sub-query. */ get CorrelationSource(): IWhereBuilder | undefined; /** * Marks this query as the correlated sub-select of `builder`. * * Called both when the sub-query is first built and every time the OWNING query is cloned, * so the clone's sub-query correlates to the clone. */ correlateWith(builder: IWhereBuilder | undefined): this; get Owner(): IOrmRelation | undefined; this: this; get IsDistinct(): boolean; get Relations(): IOrmRelation[]; /** * `applyMiddlewares` is false ONLY for {@link clone}. A clone is not a new query: every * statement, column, join and relation it ends up with is copied from the source builder, * which already went through `afterQueryCreation`. Running the middlewares again here * produced their constraints twice — once on the clone (immediately overwritten by the * copy below) and once carried over from the source — so a custom rbac hook fired twice per * clone, and any side effect it has ( a lookup, a counter, a registered relation ) happened * twice while its query effect was silently discarded. * * This is not a rare path: `SqlLazyQueryStatement.build()` clones the builder at COMPILE * time to evaluate a deferred `Lazy` callback in isolation, so every query carrying a * `Lazy` where-statement hit it on every compile. */ constructor(container: IContainer, driver: OrmDriver, model?: Constructor, owner?: IOrmRelation, applyMiddlewares?: boolean); asRaw(): Promise; setAlias(alias?: string): this; clone(): this; protected _getRelationInstance(relation: string): IOrmRelation; populate<_R = this>(relation: Constructor): this; populate(relation?: string | string[] | null, callback?: (this: SelectQueryBuilder, relation: IOrmRelation) => void): this; populate(relation: {}, callback?: (this: SelectQueryBuilder, relation: IOrmRelation) => void): this; mergeBuilder(builder: SelectQueryBuilder, includeStatements?: boolean): void; mergeRelations(builder: SelectQueryBuilder): void; mergeStatements(builder: SelectQueryBuilder, callback?: (statement: IQueryStatement) => boolean): void; /** * Includes soft-deleted rows in the result set by removing the default * `DeletedAt IS NULL` filter added by createQuery for @SoftDelete models. */ withDeleted(): this; /** * Includes archived rows in the result set by removing the default `ArchivedAt IS NULL` * filter added by createQuery for @Archived models. Mirror of {@link withDeleted}. */ withArchived(): this; min(column: string, as?: string): this; max(column: string, as?: string): this; count(column?: string, as?: string): this; selectCount(column?: string, as?: string): Promise; sum(column: string, as?: string): this; avg(column: string, as?: string): this; distinct(): this; toDB(): ICompilerOutput; /** * A sort column usually arrives from a request. Unchecked it reaches the database as an * unknown identifier and comes back as a driver error instead of a bad argument. * Select aliases stay sortable, and a raw select opts the query out - its aliases are not visible here. */ validateSorts(): void; all(): Promise; resultExists(): Promise; /** * Overrides the engine rather than `execute()` so that the `takeFirst()` unwrapping * happens *inside* the memo. `beforeQueryExecution` is dispatched by `Builder._run()` * for every builder type, so it still fires once per builder rather than once per await. */ protected _run(): Promise; } export declare class SelectQueryBuilderC extends SelectQueryBuilder { } export declare class DeleteQueryBuilder extends QueryBuilder { /** * where query props */ protected _statements: IQueryStatement[]; protected _boolean: WhereBoolean; protected _limit: IQueryLimit; private this; constructor(container: Container, driver: OrmDriver, model: Constructor); toDB(): ICompilerOutput; } export declare class OnDuplicateQueryBuilder { protected _column: string[]; protected _parent: QueryBuilder; protected _columnsToUpdate: Array; protected _container: IContainer; protected _returning: string[]; constructor(container: IContainer, insertQueryBuilder: QueryBuilder, column?: string | string[], returning?: string[]); getReturning(): string[]; getColumn(): string[]; getColumnsToUpdate(): (string | RawQuery)[]; getParent(): QueryBuilder; update(columns: string[] | RawQuery[]): this; execute(): Promise; then(onfulfilled?: ((value: any) => TResult1 | PromiseLike) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null): PromiseLike; toDB(): ICompilerOutput | ICompilerOutput[]; } export declare class UpdateQueryBuilder extends QueryBuilder { /** * where query props */ protected _statements: IQueryStatement[]; protected _boolean: WhereBoolean; protected _value: {}; get Value(): {}; this: this; constructor(container: Container, driver: OrmDriver, model: Constructor); in(name: string): this; update(value: {}): this; toDB(): ICompilerOutput; } export declare class InsertQueryBuilder extends QueryBuilder { DuplicateQueryBuilder: OnDuplicateQueryBuilder; protected _values: any[][]; protected _columns: ColumnStatement[]; protected _ignore: boolean; protected _update: boolean; protected _replace: boolean; protected _returning: string[]; this: this; get Values(): any[][]; get Ignore(): boolean; get Update(): boolean; get Replace(): boolean; /** Columns requested via {@link returning}. Empty when no RETURNING clause was asked for. */ get Returning(): string[]; constructor(container: Container, driver: OrmDriver, model: Constructor); /** * The value of `column` on every row about to be inserted, in row order. Empty when the * payload does not carry that column at all. * * The read counterpart of {@link forceColumn}, and the only sane way for a * `beforeQueryExecution` hook to inspect what is being written: the payload lives in two * parallel structures ( `_columns` and one array per row ), so every caller would * otherwise repeat the same index lookup. * * @param column - column to read off each row */ getColumnValues(column: string): unknown[]; /** * Forces `column` to `value` on every row of the payload, overwriting whatever the caller * supplied. * * This is the write path for a policy that must not be negotiable — rbac's `createOwn` * ownership stamp. `values()` cannot serve: it appends rows and takes the column list from * its own argument, so calling it a second time adds a row rather than amending the * existing ones. * * @param column - column to overwrite on every row * @param value - value to force */ forceColumn(column: string, value: unknown): this; /** * Sets insert to ignore on duplicate */ orIgnore(): this; orReplace(): this; /** * Asks the dialect to echo the given columns of every inserted row back. * * @throws NotSupported on drivers whose `supportedFeatures().insertReturning` is false — * silently doing nothing is how this API was a no-op on MySQL and MSSQL for years. */ returning(columns: string[]): this; values(data: {} | Array<{}>): this; into(table: string, schema?: string): this; onDuplicate(column?: string | string[]): OnDuplicateQueryBuilder; toDB(): ICompilerOutput; } export declare class IndexQueryBuilder extends Builder { Name: string; Unique: boolean; Table: string; Columns: string[]; constructor(container: Container, driver: OrmDriver); name(name: string): this; unique(): this; table(name: string): this; columns(colNames: string[]): this; toDB(): ICompilerOutput; } export declare class ForeignKeyBuilder { ForeignKeyField: string; Table: string; PrimaryKey: string; OnDeleteAction: ReferentialAction; OnUpdateAction: ReferentialAction; constructor(); /** * * Referenced field in child table * * @param fkName - name of foreign field in child table */ foreignKey(fkName: string): this; /** * * Referenced parent table & key * * @param table - parent table * @param pKey - parant table key field */ references(table: string, pKey: string): this; /** * * On delete action * * @param action - action to take on delete */ onDelete(action: ReferentialAction): this; /** * * On update action * * @param action - action to take on update */ onUpdate(action: ReferentialAction): this; /** * Shorhand for on update and on delete cascade settings */ cascade(): this; } export declare class ColumnQueryBuilder { protected container: IContainer; Name: string; Unique: boolean; Unsigned: boolean; AutoIncrement: boolean; Default: DefaultValueBuilder; PrimaryKey: boolean; Comment: string; Charset: string; Collation: string; NotNull: boolean; Type: ColumnType; Args: any[]; /** * When false the column compiler must not emit an inline PRIMARY KEY; the table compiler * emits a table-level constraint instead. Dialects that cannot express a composite key * inline ( SQLite ) clear this. Defaults to true. */ InlinePrimaryKey: boolean; constructor(container: IContainer, name: string, type: ColumnType, ...args: any[]); notNull(): this; unique(): this; unsigned(): this; autoIncrement(): this; default(): DefaultValueBuilder; primaryKey(): this; comment(comment: string): this; charset(charset: string): this; collation(collation: string): this; } export declare class AlterColumnQueryBuilder extends ColumnQueryBuilder { AlterType: ColumnAlterationType; AfterColumn: string; OldName: string; constructor(container: IContainer, name: string, type: ColumnType, ...args: any[]); addColumn(): this; modify(): this; rename(newName: string): this; after(columnName: string): this; } export declare class TableExistsQueryBuilder extends QueryBuilder { constructor(container: Container, driver: OrmDriver, name: string); toDB(): ICompilerOutput; } export declare class DropTableQueryBuilder extends QueryBuilder { Exists: boolean; constructor(container: Container, driver: OrmDriver, name: string, database?: string); ifExists(): this; toDB(): ICompilerOutput; } export declare class DropViewQueryBuilder extends QueryBuilder { Exists: boolean; constructor(container: Container, driver: OrmDriver, name: string, database?: string); ifExists(): this; toDB(): ICompilerOutput; } export type ViewAlgorithm = 'UNDEFINED' | 'MERGE' | 'TEMPTABLE'; export type ViewSecurity = 'DEFINER' | 'INVOKER'; export type ViewCheckOption = 'CASCADED' | 'LOCAL'; /** * CREATE VIEW. Which optional clauses exist is the dialect's business: a driver's compiler * throws MethodNotImplemented for a clause its engine does not have. */ export declare class CreateViewQueryBuilder extends QueryBuilder { Replace: boolean; IfNotExists: boolean; Temporary: boolean; Columns: string[]; Algorithm?: ViewAlgorithm; Security?: ViewSecurity; /** `true` is the plain `WITH CHECK OPTION` */ CheckOption?: ViewCheckOption | true; Body?: SelectQueryBuilder | RawQuery; constructor(container: Container, driver: OrmDriver, name: string, database?: string); orReplace(): this; ifNotExists(): this; temporary(): this; columns(names: string[]): this; algorithm(algorithm: ViewAlgorithm): this; security(security: ViewSecurity): this; checkOption(option?: ViewCheckOption): this; /** * @param body - callback receiving a fresh select builder, a ready select builder, or raw SQL */ as(body: ((select: SelectQueryBuilder) => void) | SelectQueryBuilder | RawQuery): this; toDB(): ICompilerOutput; } /** * Creates a whole database ( schema in some engines ), eg. * * CREATE DATABASE IF NOT EXISTS `db` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci * * Not every engine supports this - sqlite has no notion of a server side database, * and its driver rejects the statement instead of emitting SQL it cannot run. */ export declare class CreateDatabaseQueryBuilder extends QueryBuilder { /** * Name of the database to create. Kept apart from `Database` of the base builder, * which qualifies a table with the database it lives in - here the database IS the subject. */ Name: string; Exists: boolean; Charset: string; Collation: string; constructor(container: Container, driver: OrmDriver, name: string); /** * Adds IF NOT EXISTS clause, so creating an already existing database is not an error. */ ifNotExists(): this; /** * Default character set of the database eg. utf8mb4 */ charset(charset: string): this; /** * Default collation of the database eg. utf8mb4_unicode_ci */ collation(collation: string): this; toDB(): ICompilerOutput; } export declare class DropDatabaseQueryBuilder extends QueryBuilder { Name: string; Exists: boolean; constructor(container: Container, driver: OrmDriver, name: string); /** * Adds IF EXISTS clause, so dropping a missing database is not an error. */ ifExists(): this; toDB(): ICompilerOutput; } export declare class AlterTableQueryBuilder extends QueryBuilder { protected _columns: ColumnQueryBuilder[]; NewTableName: string; DroppedColumns: string[]; get Columns(): ColumnQueryBuilder[]; constructor(container: Container, driver: OrmDriver, name: string); int: (name: string) => AlterColumnQueryBuilder; bigint: (name: string) => AlterColumnQueryBuilder; tinyint: (name: string) => AlterColumnQueryBuilder; smallint: (name: string) => AlterColumnQueryBuilder; mediumint: (name: string) => AlterColumnQueryBuilder; text: (name: string) => AlterColumnQueryBuilder; tinytext: (name: string) => AlterColumnQueryBuilder; mediumtext: (name: string) => AlterColumnQueryBuilder; smalltext: (name: string) => AlterColumnQueryBuilder; longtext: (name: string) => AlterColumnQueryBuilder; string: (name: string, length?: number) => AlterColumnQueryBuilder; float: (name: string, precision?: number, scale?: number) => AlterColumnQueryBuilder; double: (name: string, precision?: number, scale?: number) => AlterColumnQueryBuilder; decimal: (name: string, precision?: number, scale?: number) => AlterColumnQueryBuilder; boolean: (name: string) => AlterColumnQueryBuilder; bit: (name: string) => AlterColumnQueryBuilder; date: (name: string) => AlterColumnQueryBuilder; dateTime: (name: string) => AlterColumnQueryBuilder; time: (name: string) => AlterColumnQueryBuilder; timestamp: (name: string) => AlterColumnQueryBuilder; enum: (name: string, values: any[]) => AlterColumnQueryBuilder; json: (name: string) => AlterColumnQueryBuilder; binary: (name: string, size: number) => AlterColumnQueryBuilder; tinyblob: (name: string) => AlterColumnQueryBuilder; mediumblob: (name: string) => AlterColumnQueryBuilder; longblob: (name: string) => AlterColumnQueryBuilder; /** * Renames table * * @param newTableName - new table name */ rename(newTableName: string): void; dropColumn(column: string): void; toDB(): ICompilerOutput[]; } export declare class TableQueryBuilder extends QueryBuilder { int: (name: string) => ColumnQueryBuilder; bigint: (name: string) => ColumnQueryBuilder; tinyint: (name: string) => ColumnQueryBuilder; smallint: (name: string) => ColumnQueryBuilder; mediumint: (name: string) => ColumnQueryBuilder; text: (name: string) => ColumnQueryBuilder; tinytext: (name: string) => ColumnQueryBuilder; mediumtext: (name: string) => ColumnQueryBuilder; smalltext: (name: string) => ColumnQueryBuilder; longtext: (name: string) => ColumnQueryBuilder; string: (name: string, length?: number) => ColumnQueryBuilder; /** * Alias for binary(name, 16 ) - uuids are stored as 16-byte BINARY to match * the UuidConverter ( which writes a dashed uuid as a 16-byte buffer ). */ uuid(name: string): ColumnQueryBuilder; float: (name: string, precision?: number, scale?: number) => ColumnQueryBuilder; double: (name: string, precision?: number, scale?: number) => ColumnQueryBuilder; decimal: (name: string, precision?: number, scale?: number) => ColumnQueryBuilder; boolean: (name: string) => ColumnQueryBuilder; bit: (name: string) => ColumnQueryBuilder; date: (name: string) => ColumnQueryBuilder; dateTime: (name: string) => ColumnQueryBuilder; time: (name: string) => ColumnQueryBuilder; timestamp: (name: string) => ColumnQueryBuilder; enum: (name: string, values: any[]) => ColumnQueryBuilder; json: (name: string) => ColumnQueryBuilder; binary: (name: string, size: number) => ColumnQueryBuilder; tinyblob: (name: string) => ColumnQueryBuilder; mediumblob: (name: string) => ColumnQueryBuilder; longblob: (name: string) => ColumnQueryBuilder; ifExists(): TableQueryBuilder; /** * Mark table as temporary */ temporary(): TableQueryBuilder; /** * Turn on history trackign for this table * Each change & row will be tracked, and all history of changes can be accessed */ trackHistory(): this; set: (name: string, allowed: string[]) => ColumnQueryBuilder; get Columns(): ColumnQueryBuilder[]; get ForeignKeys(): ForeignKeyBuilder[]; protected _columns: ColumnQueryBuilder[]; protected _foreignKeys: ForeignKeyBuilder[]; protected _comment: string; protected _charset: string; protected _checkExists: boolean; protected _temporary: boolean; protected _trackHistory: boolean; get CheckExists(): boolean; get Temporary(): boolean; get TrackHistory(): boolean; constructor(container: Container, driver: OrmDriver, name: string); increments(name: string): ColumnQueryBuilder; comment(comment: string): void; charset(charset: string): void; foreignKey(foreignKey: string): ForeignKeyBuilder; toDB(): ICompilerOutput | ICompilerOutput[]; } export declare class TruncateTableQueryBuilder extends QueryBuilder { protected container: Container; protected driver: OrmDriver; constructor(container: Container, driver: OrmDriver); toDB(): ICompilerOutput; } export declare class CloneTableQueryBuilder extends QueryBuilder { protected container: Container; protected driver: OrmDriver; protected _cloneSrc: string; protected _temporary: boolean; protected _shallow: boolean; protected _filter: SelectQueryBuilder; get CloneSource(): string; get Temporary(): boolean; get Shallow(): boolean; get Filter(): SelectQueryBuilder; constructor(container: Container, driver: OrmDriver); /** * Clones table structure without data * Shorthand for createTable(( table) => table.clone("new")); * * @param srcTable - source table name * @param newTable - target table name */ shallowClone(srcTable: string, newTable: string): this; /** * Clones table with data * * @param srcTable - source table name * @param newTable - target table name * @param filter - data filter, set null if all data is to be cloned */ deepClone(srcTable: string, newTable: string, filter?: (query: SelectQueryBuilder) => void): Promise; toDB(): ICompilerOutput[]; } export type EventIntervalUnit = 'YEAR' | 'QUARTER' | 'MONTH' | 'WEEK' | 'DAY' | 'HOUR' | 'MINUTE' | 'SECOND'; export interface IEventInterval { Value: number; Unit: EventIntervalUnit; } /** * A job scheduled inside the database engine. Engines without native events throw * MethodNotImplemented at compile time - check `supportedFeatures().events` first. */ export declare class EventQueryBuilder extends QueryBuilder { Every?: IEventInterval; FromNow?: IEventInterval; At?: DateTime; Starts?: DateTime; Ends?: DateTime; Preserve: boolean; Enabled: boolean; IfNotExists: boolean; Comment?: string; Actions: (RawQuery | QueryBuilder)[]; constructor(container: Container, driver: OrmDriver, name: string); /** Repeat with the given interval */ every(value: number, unit: EventIntervalUnit): this; /** Run once at a point in time */ at(dateTime: DateTime): this; /** Run once, the given interval from now */ fromNow(value: number, unit: EventIntervalUnit): this; starts(dateTime: DateTime): this; ends(dateTime: DateTime): this; /** Keep the event after its last run ( ON COMPLETION PRESERVE ) */ preserve(): this; disabled(): this; ifNotExists(): this; comment(comment: string): this; /** * One action is emitted as given - a statement, or raw SQL carrying its own BEGIN ... END. * Several actions are wrapped in BEGIN ... END. */ do(sql: RawQuery | QueryBuilder | (RawQuery | QueryBuilder)[]): this; toDB(): ICompilerOutput; private assertNoSchedule; } export declare class DropEventQueryBuilder extends QueryBuilder { Exists: boolean; constructor(container: Container, driver: OrmDriver, name: string); ifExists(): this; toDB(): ICompilerOutput; } export declare class SchemaQueryBuilder { protected container: Container; protected driver: OrmDriver; constructor(container: Container, driver: OrmDriver); createTable(name: string, callback: (table: TableQueryBuilder) => void): TableQueryBuilder; cloneTable(callback: (clone: CloneTableQueryBuilder) => void): CloneTableQueryBuilder; alterTable(name: string, callback: (table: AlterTableQueryBuilder) => void): AlterTableQueryBuilder; dropTable(name: string, schema?: string): DropTableQueryBuilder; createView(name: string, callback: (view: CreateViewQueryBuilder) => void): CreateViewQueryBuilder; dropView(name: string, schema?: string): DropViewQueryBuilder; /** * Creates database eg. * * CREATE DATABASE IF NOT EXISTS `db` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci * * @param name - database name * @param callback - optional callback, options can also be set fluently on returned builder */ createDatabase(name: string, callback?: (database: CreateDatabaseQueryBuilder) => void): CreateDatabaseQueryBuilder; /** * Drops whole database with all its content. * * @param name - database name */ dropDatabase(name: string): DropDatabaseQueryBuilder; tableExists(name: string, schema?: string): Promise; createEvent(name: string, callback: (event: EventQueryBuilder) => void): EventQueryBuilder; dropEvent(name: string): DropEventQueryBuilder; /** * Executes raw SQL statement on the database. * Use this for custom DDL operations or database-specific commands. * * @param query - raw query string or RawQuery instance * @param bindings - optional binding parameters */ raw(query: string | RawQuery, bindings?: any[]): RawSchemaQueryBuilder; } /** * Query builder for executing raw SQL statements within schema context. * Useful for custom DDL operations, database-specific commands, or * any SQL that doesn't fit into the standard schema methods. */ export declare class RawSchemaQueryBuilder extends QueryBuilder { protected container: Container; protected driver: OrmDriver; Query: string; Bindings: any[]; constructor(container: Container, driver: OrmDriver, query: string, bindings?: any[]); toDB(): ICompilerOutput; } export declare function _descriptor(model: Class): import("./interfaces.js").IModelDescriptor | null; /** * Helper function to create query based on model * * @param model - source model for query * @param query - query class * @param injectModel - should inject model information into query, if not, query will return raw data * * @returns */ export declare function createQuery(model: Class, query: Class, injectModel?: boolean): { query: import("@spinajs/di").ResolveResult; description: import("./interfaces.js").IModelDescriptor; model: Class; container: IContainer; }; //# sourceMappingURL=builders.d.ts.map