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.

129 lines
3.2 KiB

import ConnectionMutable from './ConnectionMutable.ts'
import {MalformedSQLGrammarError} from './Select.ts'
import {TableRefBuilder} from './TableRefBuilder.ts'
import {applyMixins} from '../../../../lib/src/support/mixins.ts'
import {QuerySource} from '../types.ts'
/**
* Base query builder class for TRUNCATE queries.
* @extends ConnectionMutable
* @extends TableRefBuilder
*/
export class Truncate<T> extends ConnectionMutable<T> {
/**
* The source to be truncated.
* @type QuerySource
*/
protected _source?: QuerySource
/**
* Include the ONLY clause?
* @type boolean
*/
protected _only: boolean = false
/**
* Include the RESTART clause?
* @type boolean
*/
protected _restart: boolean = false
/**
* Include the CONTINUE clause?
* @type boolean
*/
protected _continue: boolean = false
/**
* Include the CASCADE clause?
* @type boolean
*/
protected _cascade: boolean = false
/**
* Include the RESTRICT clause?
* @type boolean
*/
protected _restrict: boolean = false
constructor(table?: QuerySource, alias?: string) {
super()
if ( table ) this.table(table, alias)
}
sql(level: number = 0): string {
const indent = Array(level).fill(' ').join('')
if ( typeof this._source === 'undefined' )
throw new MalformedSQLGrammarError(`No table reference has been provided.`)
const table_ref = this.source_alias_to_table_ref(this._source)
let identity = ''
if ( this._continue ) identity = 'CONTINUE IDENTITY '
else if ( this._restart ) identity = 'RESTART IDENTITY '
let cascade_redirect = ''
if ( this._cascade ) cascade_redirect = 'CASCADE '
else if ( this._restrict ) cascade_redirect = 'RESTRICT'
return [
`TRUNCATE TABLE ${this._only ? 'ONLY ' : ''}${this.serialize_table_ref(table_ref)}`,
`${identity}${cascade_redirect}`,
].filter(x => String(x).trim()).join(`\n${indent}`)
}
/**
* Set the table to be truncated.
* @param {QuerySource} source
* @param {string} [alias]
* @return self
*/
table(source: QuerySource, alias?: string) {
if ( !alias ) this._source = source
else this._source = { ref: source, alias }
return this
}
/**
* Restart the ID column. This adds the RESTART clause.
* @return self
*/
restart_identity() {
this._continue = false
this._restart = true
return this
}
/**
* Continue the ID column. This adds the CONTINUE clause.
* @return self
*/
continue_identity() {
this._continue = true
this._restart = false
return this
}
/**
* Add the CASCADE clause.
* @return self
*/
cascade() {
this._cascade = true
this._restrict = false
return this
}
/**
* Add the RESTRICT clause.
* @return self
*/
restrict() {
this._cascade = false
this._restrict = true
return this
}
}
export interface Truncate<T> extends TableRefBuilder {}
applyMixins(Truncate, [TableRefBuilder])