diff --git a/app/index.ts b/app/index.ts index a9b7b77..2ed0d40 100755 --- a/app/index.ts +++ b/app/index.ts @@ -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()) diff --git a/orm/src/builder/type/Select.ts b/orm/src/builder/type/Select.ts index 9f5e559..020a35f 100644 --- a/orm/src/builder/type/Select.ts +++ b/orm/src/builder/type/Select.ts @@ -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 extends ConnectionExecutable { ].filter(x => String(x).trim()).join(`\n${indent}`) } - field(field: string) { - if ( !this._fields.includes(field) ) { + field(field: string | Select, as?: string) { + if ( field instanceof Select ) { + this._fields.push(`${escape(field)}${as ? ' AS '+as : ''}`) + } else { this._fields.push(field) } + return this } diff --git a/orm/src/builder/types.ts b/orm/src/builder/types.ts index e0a18a6..cc15193 100644 --- a/orm/src/builder/types.ts +++ b/orm/src/builder/types.ts @@ -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 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(',')})`