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.

61 lines
2.2 KiB

import ConnectionMutable from './ConnectionMutable.ts'
import {WhereBuilder} from './WhereBuilder.ts'
import {applyMixins} from '../../../../lib/src/support/mixins.ts'
import {QuerySource, WhereStatement, FieldSet} from '../types.ts'
import {TableRefBuilder} from './TableRefBuilder.ts'
import {MalformedSQLGrammarError} from './Select.ts'
import {Scope} from '../Scope.ts'
export class Delete<T> extends ConnectionMutable<T> {
protected _target?: QuerySource = undefined
protected _wheres: WhereStatement[] = []
protected _scopes: Scope[] = []
protected _fields: string[] = []
protected _only: boolean = false
sql(level = 0): string {
const indent = Array(level * 2).fill(' ').join('')
if ( typeof this._target === 'undefined' )
throw new MalformedSQLGrammarError('No table reference has been provided.')
const table_ref = this.source_alias_to_table_ref(this._target)
const wheres = this.wheres_to_sql(this._wheres, level + 1)
const returning_fields = this._fields.join(', ')
return [
`DELETE FROM ${this._only ? 'ONLY ' : ''}${this.serialize_table_ref(table_ref)}`,
...(wheres.trim() ? ['WHERE', wheres] : []),
...(returning_fields.trim() ? [`RETURNING ${returning_fields}`] : []),
].filter(x => String(x).trim()).join(`\n${indent}`)
}
only() {
this._only = true
return this
}
from(source: QuerySource, alias?: string) {
if ( !alias ) this._target = source
else this._target = { ref: source, alias }
return this
}
returning(...fields: FieldSet[]) {
for ( const field_set of fields ) {
if ( typeof field_set === 'string' ) {
if ( !this._fields.includes(field_set) )
this._fields.push(field_set)
} else {
for ( const field of field_set ) {
if ( !this._fields.includes(field) )
this._fields.push(field)
}
}
}
return this
}
}
export interface Delete<T> extends WhereBuilder, TableRefBuilder {}
applyMixins(Delete, [WhereBuilder, TableRefBuilder])