Add support for subqueries

This commit is contained in:
Garrett Mills 2020-08-16 10:08:27 -05:00
parent 809af8063f
commit dc6ba53380
Signed by: garrettmills
GPG Key ID: D2BF5FBA8298F246
3 changed files with 12 additions and 23 deletions

View File

@ -18,21 +18,3 @@ await scaffolding.up()
*/
const app = make(Application, units)
await app.run()
import UserModel from './models/User.model.ts'
import ObjectResultOperator from "../orm/src/builder/type/result/ObjectResultOperator.ts";
// const users = await UserModel.find_one({ username: 'garrettmills' })
const sel = UserModel.select('*').with('login_attempts').where('username', '=', 'garrettmills')
console.log(sel)
console.log(sel.clone())
const gm = await sel.results().first()
console.log(gm)
const la = (await gm.login_attempts()).first()
console.log(la)
console.log(await la.user())
// console.log(await las.fetchRelated())

View File

@ -4,7 +4,8 @@ import {
WhereStatement,
TableRef,
OrderStatement,
OrderDirection, HavingStatement
OrderDirection, HavingStatement,
escape,
} from '../types.ts'
import {WhereBuilder} from './WhereBuilder.ts'
import {applyMixins} from '../../../../lib/src/support/mixins.ts'
@ -72,10 +73,13 @@ export class Select<T> extends ConnectionExecutable<T> {
].filter(x => String(x).trim()).join(`\n${indent}`)
}
field(field: string) {
if ( !this._fields.includes(field) ) {
field(field: string | Select<any>, as?: string) {
if ( field instanceof Select ) {
this._fields.push(`${escape(field)}${as ? ' AS '+as : ''}`)
} else {
this._fields.push(field)
}
return this
}

View File

@ -1,5 +1,6 @@
import {WhereOperator} from '../../../lib/src/collection/Where.ts'
import RawValue from './RawValue.ts'
import {Select} from "./type/Select.ts";
export type FieldSet = string | string[]
export type QuerySource = string | { ref: QuerySource, alias: string }
@ -20,7 +21,7 @@ export type HavingGroup = WhereGroup
export type HavingStatement = HavingClause | HavingGroup
export type SQLHavingOperator = SQLWhereOperator
export type EscapedValue = string | number | boolean | Date | RawValue | EscapedValue[]
export type EscapedValue = string | number | boolean | Date | RawValue | EscapedValue[] | Select<any>
export type FieldValue = { field: string, value: EscapedValue }
export type FieldValueObject = { [field: string]: EscapedValue }
@ -76,7 +77,9 @@ export function isWhereStatement(something: any): something is WhereStatement {
}
export function escape(value: EscapedValue): string {
if ( value instanceof RawValue ) {
if ( value instanceof Select ) {
return `(${value.sql(5)})`
} else if ( value instanceof RawValue ) {
return value.value
} else if ( Array.isArray(value) ) {
return `(${value.map(escape).join(',')})`