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
1.7 KiB

import {TableRef, QuerySource} from '../types.ts'
/**
* Query builder mixin for queries that resolve table names.
*/
export class TableRefBuilder {
/**
* Resolve the raw table name to a table reference.
* @param {string} from
* @return TableRef
*/
resolve_table_name(from: string): TableRef {
const parts = from.split('.')
const ref: any = {}
if ( parts.length > 1 ) {
ref.database = parts[0]
ref.table = parts[1]
} else {
ref.table = parts[0]
}
const alias_parts = ref.table.split(/\s+/)
if ( alias_parts.length > 1 ) {
ref.table = alias_parts[0]
ref.alias = alias_parts[1]
}
return ref as TableRef
}
/**
* Serialize a table ref to its raw SQL form.
* @param {TableRef} ref
* @return string
*/
serialize_table_ref(ref: TableRef): string {
return `${ref.database ? ref.database+'.' : ''}${ref.table}${ref.alias ? ' '+ref.alias : ''}`
}
/**
* Convert a query source and alias to a table ref.
* @param {QuerySource} source
* @param {string} [alias]
* @return TableRef
*/
source_alias_to_table_ref(source: QuerySource, alias?: string) {
let string = ''
if ( typeof source === 'string' ) {
string = source
if ( typeof alias === 'string' ) string += ` ${alias}`
}
else if ( typeof source === 'object' ) {
string = `${source.ref}`
if ( source.alias ) string += ` ${source.alias}`
else if ( typeof alias === 'string' ) string += ` ${alias}`
}
return this.resolve_table_name(string)
}
}