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.

119 lines
3.2 KiB

import {EscapedValue, FieldSet, QuerySource} from './types.ts'
import {Select} from './type/Select.ts'
import RawValue from './RawValue.ts'
import {Statement} from './Statement.ts'
import {Update} from './type/Update.ts'
import {Insert} from './type/Insert.ts'
import {Delete} from './type/Delete.ts'
import {Truncate} from './type/Truncate.ts'
/**
* Wrap a string so it gets included in the query unescaped.
* @param {string} value
* @return RawValue
*/
export function raw(value: string) {
return new RawValue(value)
}
/**
* Error thrown when an interpolated statement has an incorrect number of arguments.
* @extends Error
*/
export class IncorrectInterpolationError extends Error {
constructor(expected: number, received: number) {
super(`Unable to interpolate arguments into query. Expected ${expected} argument${expected === 1 ? '' : 's'}, but received ${received}.`)
}
}
/**
* Base query builder class used to start various types of queries.
*/
export class Builder<T> {
// create table, alter table, drop table, select
/**
* Get a new SELECT statement.
* @param {...FieldSet} fields
* @return Select
*/
public select(...fields: FieldSet[]): Select<T> {
fields = fields.flat()
const select = new Select<T>()
return select.fields(...fields)
}
/**
* Get a new UPDATE statement.
* @param {QuerySource} [target]
* @param {string} [alias]
* @return Update
*/
public update(target?: QuerySource, alias?: string): Update<T> {
const update = new Update<T>()
if ( target ) update.to(target, alias)
return update
}
/**
* Get a new DELETE statement.
* @param {QuerySource} [target]
* @param {string} [alias]
* @return Delete
*/
public delete(target?: QuerySource, alias?: string): Delete<T> {
const del = new Delete<T>()
if ( target ) del.from(target, alias)
return del
}
/**
* Get a new INSERT statement.
* @param {QuerySource} [target]
* @param {string} [alias]
* @return Insert
*/
public insert(target?: QuerySource, alias?: string): Insert<T> {
const insert = new Insert<T>()
if ( target ) insert.into(target, alias)
return insert
}
/**
* Get a new raw SQL statement.
* @param {string} statement
* @param {...EscapedValue} interpolations
* @return Statement
*/
public statement(statement: string, ...interpolations: EscapedValue[]): Statement<T> {
return new Statement<T>(statement, interpolations)
}
/**
* Get a new TRUNCATE statement.
* @param {QuerySource} [target]
* @param {string} [alias]
* @return Truncate
*/
public truncate(target?: QuerySource, alias?: string): Truncate<T> {
return new Truncate<T>(target, alias)
}
/**
* Wrap a string so it gets included in the query unescaped.
* @param {string} value
* @return RawValue
*/
public static raw(value: string) {
return new RawValue(value)
}
/**
* Get the 'DEFAULT' operator, raw.
* @return RawValue
*/
public static default() {
return this.raw('DEFAULT')
}
}