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.
lib/src/orm/connection/Connection.ts

100 lines
2.7 KiB

import {Awaitable, Collection, ErrorWithContext} from '../../util'
import {QueryResult, QueryRow} from '../types'
import {SQLDialect} from '../dialect/SQLDialect'
import {AppClass} from '../../lifecycle/AppClass'
import {Inject, Injectable} from '../../di'
import {QueryExecutedEvent} from './event/QueryExecutedEvent'
import {Schema} from '../schema/Schema'
import {Bus} from '../../support/bus'
import {ModelField} from '../model/Field'
/**
* Error thrown when a connection is used before it is ready.
* @extends Error
*/
export class ConnectionNotReadyError extends ErrorWithContext {
constructor(name = '', context: {[key: string]: any} = {}) {
super(`The connection ${name} is not ready and cannot execute queries.`)
this.context = context
}
}
/**
* Abstract base class for database connections.
* @abstract
*/
@Injectable()
export abstract class Connection extends AppClass {
@Inject()
protected readonly bus!: Bus
constructor(
/**
* The name of this connection
* @type string
*/
public readonly name: string,
/**
* This connection's config object
*/
public readonly config: any = {},
) {
super()
}
public abstract dialect(): SQLDialect
/**
* Open the connection.
* @return Promise<void>
*/
public abstract init(): Promise<void>
/**
* Execute an SQL query and get the result.
* @param {string} query
* @return Promise<QueryResult>
*/
public abstract query(query: string): Promise<QueryResult>
/**
* Close the connection.
* @return Promise<void>
*/
public abstract close(): Promise<void>
/**
* Get a Schema on this connection.
* @param name
*/
public abstract schema(name?: string): Schema
/**
* Execute all queries logged to this connection during the closure
* as a transaction in the database.
* @param closure
*/
public abstract asTransaction<T>(closure: () => Awaitable<T>): Awaitable<T>
/**
* Normalize a query row before it is used by the framework.
* This helps account for differences in return values from the dialects.
* @param row
* @param fields
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public normalizeRow(row: QueryRow, fields: Collection<ModelField>): QueryRow {
return row
}
/**
* Fire a QueryExecutedEvent for the given query string.
* @param query
* @protected
*/
protected async queryExecuted(query: string): Promise<void> {
const event = new QueryExecutedEvent(this.name, this, query)
await this.bus.push(event)
}
}