The SQLite json_object function.
json_object
NOTE: This helper only works correctly if you've installed the ParseJSONResultsPlugin. Otherwise the nested selections will be returned as JSON strings.
ParseJSONResultsPlugin
The plugin can be installed like this:
import * as Sqlite from 'better-sqlite3'import { Kysely, ParseJSONResultsPlugin, SqliteDialect } from 'kysely'import type { Database } from 'type-editor' // imaginary moduleconst db = new Kysely<Database>({ dialect: new SqliteDialect({ database: new Sqlite(':memory:') }), plugins: [new ParseJSONResultsPlugin()]}) Copy
import * as Sqlite from 'better-sqlite3'import { Kysely, ParseJSONResultsPlugin, SqliteDialect } from 'kysely'import type { Database } from 'type-editor' // imaginary moduleconst db = new Kysely<Database>({ dialect: new SqliteDialect({ database: new Sqlite(':memory:') }), plugins: [new ParseJSONResultsPlugin()]})
import { sql } from 'kysely'import { jsonBuildObject } from 'kysely/helpers/sqlite'const result = await db .selectFrom('person') .select((eb) => [ 'id', jsonBuildObject({ first: eb.ref('first_name'), last: eb.ref('last_name'), full: sql<string>`first_name || ' ' || last_name` }).as('name') ]) .execute()result[0]?.idresult[0]?.name.firstresult[0]?.name.lastresult[0]?.name.full Copy
import { sql } from 'kysely'import { jsonBuildObject } from 'kysely/helpers/sqlite'const result = await db .selectFrom('person') .select((eb) => [ 'id', jsonBuildObject({ first: eb.ref('first_name'), last: eb.ref('last_name'), full: sql<string>`first_name || ' ' || last_name` }).as('name') ]) .execute()result[0]?.idresult[0]?.name.firstresult[0]?.name.lastresult[0]?.name.full
The generated SQL (SQLite):
select "id", json_object( 'first', first_name, 'last', last_name, 'full', "first_name" || ' ' || "last_name") as "name"from "person" Copy
select "id", json_object( 'first', first_name, 'last', last_name, 'full', "first_name" || ' ' || "last_name") as "name"from "person"
The SQLite
json_objectfunction.NOTE: This helper only works correctly if you've installed the
ParseJSONResultsPlugin. Otherwise the nested selections will be returned as JSON strings.The plugin can be installed like this:
Examples
The generated SQL (SQLite):