Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add eb.jsonPath<$>. #791

Merged
merged 7 commits into from
Dec 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 43 additions & 3 deletions src/expression/expression-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,12 @@ import {
OperatorNode,
UnaryOperator,
} from '../operation-node/operator-node.js'
import { SqlBool } from '../util/type-utils.js'
import { IsNever, SqlBool } from '../util/type-utils.js'
import { parseUnaryOperation } from '../parser/unary-operation-parser.js'
import {
ExtractTypeFromValueExpression,
parseSafeImmediateValue,
parseValueExpression,
parseValueExpressionOrList,
} from '../parser/value-parser.js'
import { NOOP_QUERY_EXECUTOR } from '../query-executor/noop-query-executor.js'
import { CaseBuilder } from '../query-builder/case-builder.js'
Expand Down Expand Up @@ -86,6 +85,8 @@ import {
} from '../parser/tuple-parser.js'
import { TupleNode } from '../operation-node/tuple-node.js'
import { Selectable } from '../util/column-type.js'
import { JSONPathNode } from '../operation-node/json-path-node.js'
import { KyselyTypeError } from '../util/type-error.js'

export interface ExpressionBuilder<DB, TB extends keyof DB> {
/**
Expand Down Expand Up @@ -385,7 +386,8 @@ export interface ExpressionBuilder<DB, TB extends keyof DB> {
* a non-type-safe version of this method see {@link sql}'s version.
*
* Additionally, this method can be used to reference nested JSON properties or
* array elements. See {@link JSONPathBuilder} for more information.
* array elements. See {@link JSONPathBuilder} for more information. For regular
* JSON path expressions you can use {@link jsonPath}.
*
* ### Examples
*
Expand Down Expand Up @@ -470,6 +472,36 @@ export interface ExpressionBuilder<DB, TB extends keyof DB> {
op: JSONOperatorWith$
): JSONPathBuilder<ExtractTypeFromReferenceExpression<DB, TB, RE>>

/**
* Creates a JSON path expression with provided column as root document (the $).
*
* For a JSON reference expression, see {@link ref}.
*
* ### Examples
*
* ```ts
* db.updateTable('person')
* .set('experience', (eb) => eb.fn('json_set', [
* 'experience',
* eb.jsonPath<'experience'>().at('last').key('title'),
* eb.val('CEO')
* ]))
* .where('id', '=', id)
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* update `person`
* set `experience` = json_set(`experience`, '$[last].title', ?)
* where `id` = ?
* ```
*/
jsonPath<$ extends StringReference<DB, TB> = never>(): IsNever<$> extends true
? KyselyTypeError<"You must provide a column reference as this method's $ generic">
: JSONPathBuilder<ExtractTypeFromReferenceExpression<DB, TB, $>>

/**
* Creates a table reference.
*
Expand Down Expand Up @@ -1175,6 +1207,14 @@ export function createExpressionBuilder<DB, TB extends keyof DB>(
return new JSONPathBuilder(parseJSONReference(reference, op))
},

jsonPath<
$ extends StringReference<DB, TB> = never
>(): IsNever<$> extends true
? KyselyTypeError<"You must provide a column reference as this method's $ generic">
: JSONPathBuilder<ExtractTypeFromReferenceExpression<DB, TB, $>> {
return new JSONPathBuilder(JSONPathNode.create()) as any
},

table<T extends TB & string>(
table: T
): ExpressionWrapper<DB, TB, Selectable<DB[T]>> {
Expand Down
37 changes: 23 additions & 14 deletions src/query-builder/json-path-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ import { OperationNode } from '../operation-node/operation-node.js'
import { ValueNode } from '../operation-node/value-node.js'

export class JSONPathBuilder<S, O = S> {
readonly #node: JSONReferenceNode
readonly #node: JSONReferenceNode | JSONPathNode

constructor(node: JSONReferenceNode) {
constructor(node: JSONReferenceNode | JSONPathNode) {
this.#node = node
}

Expand Down Expand Up @@ -167,18 +167,27 @@ export class JSONPathBuilder<S, O = S> {
legType: JSONPathLegType,
value: string | number
): TraversedJSONPathBuilder<any, any> {
if (JSONReferenceNode.is(this.#node)) {
return new TraversedJSONPathBuilder(
JSONReferenceNode.cloneWithTraversal(
this.#node,
JSONPathNode.is(this.#node.traversal)
? JSONPathNode.cloneWithLeg(
this.#node.traversal,
JSONPathLegNode.create(legType, value)
)
: JSONOperatorChainNode.cloneWithValue(
this.#node.traversal,
ValueNode.createImmediate(value)
)
)
)
}

return new TraversedJSONPathBuilder(
JSONReferenceNode.cloneWithTraversal(
JSONPathNode.cloneWithLeg(
this.#node,
JSONPathNode.is(this.#node.traversal)
? JSONPathNode.cloneWithLeg(
this.#node.traversal,
JSONPathLegNode.create(legType, value)
)
: JSONOperatorChainNode.cloneWithValue(
this.#node.traversal,
ValueNode.createImmediate(value)
)
JSONPathLegNode.create(legType, value)
)
)
}
Expand All @@ -188,9 +197,9 @@ export class TraversedJSONPathBuilder<S, O>
extends JSONPathBuilder<S, O>
implements AliasableExpression<O>
{
readonly #node: JSONReferenceNode
readonly #node: JSONReferenceNode | JSONPathNode

constructor(node: JSONReferenceNode) {
constructor(node: JSONReferenceNode | JSONPathNode) {
super(node)
this.#node = node
}
Expand Down
36 changes: 34 additions & 2 deletions test/node/src/json-traversal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ for (const dialect of DIALECTS.filter((dialect) => dialect !== 'mssql')) {
})

if (dialect === 'mysql' || dialect === 'sqlite') {
describe('JSON Path syntax ($)', () => {
describe('JSON reference using JSON Path syntax ($)', () => {
const jsonOperator = dialect === 'mysql' ? '->$' : '->>$'

it(`should execute a query with column${jsonOperator}.key in select clause`, async () => {
Expand Down Expand Up @@ -377,10 +377,42 @@ for (const dialect of DIALECTS.filter((dialect) => dialect !== 'mssql')) {
expect(results[2].profile.auth.login_count).to.equal(12)
})
})

describe('Standalone JSON path syntax ($)', () => {
it('should execute a query with json_set function', async () => {
const lastItem = dialect === 'mysql' ? 'last' : '#-1'

const query = ctx.db
.updateTable('person_metadata')
.set('experience', (eb) =>
eb.fn('json_set', [
'experience',
eb.jsonPath<'experience'>().at(lastItem).key('establishment'),
eb.val('Papa Johns'),
])
)
.where('person_id', '=', 911)

testSql(query, dialect, {
postgres: NOT_SUPPORTED,
mysql: {
parameters: ['Papa Johns', 911],
sql: "update `person_metadata` set `experience` = json_set(`experience`, '$[last].establishment', ?) where `person_id` = ?",
},
mssql: NOT_SUPPORTED,
sqlite: {
parameters: ['Papa Johns', 911],
sql: `update "person_metadata" set "experience" = json_set("experience", '$[#-1].establishment', ?) where "person_id" = ?`,
},
})

await query.execute()
})
})
}

if (dialect === 'postgres' || dialect === 'sqlite') {
describe('PostgreSQL-style syntax (->->->>)', () => {
describe('JSON reference using PostgreSQL-style syntax (->->->>)', () => {
const jsonOperator = dialect === 'postgres' ? '->' : '->>'

it(`should execute a query with column${jsonOperator}key in select clause`, async () => {
Expand Down
25 changes: 22 additions & 3 deletions test/typings/test-d/json-traversal.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { expectError, expectType } from 'tsd'
import { Kysely } from '..'
import { Database } from '../shared'
import { ExpressionBuilder, JSONPathBuilder, Kysely } from '..'
import { Database, PersonMetadata } from '../shared'
import { expect } from 'chai'
import { KyselyTypeError } from '../../../dist/cjs/util/type-error'

async function testJSONTraversal(db: Kysely<Database>) {
async function testJSONReference(db: Kysely<Database>) {
const [r1] = await db
.selectFrom('person_metadata')
.select((eb) => eb.ref('website', '->>$').key('url').as('website_url'))
Expand Down Expand Up @@ -193,3 +195,20 @@ async function testJSONTraversal(db: Kysely<Database>) {
.execute()
)
}

async function testJSONPath(eb: ExpressionBuilder<Database, keyof Database>) {
expectType<JSONPathBuilder<PersonMetadata['experience']>>(
eb.jsonPath<'experience'>()
)

expectType<JSONPathBuilder<PersonMetadata['experience']>>(
eb.jsonPath<'person_metadata.experience'>()
)

expectError(eb.jsonPath('experience'))
expectError(eb.jsonPath('person_metadata.experience'))
expectType<
KyselyTypeError<"You must provide a column reference as this method's $ generic">
>(eb.jsonPath())
expectError(eb.jsonPath<'NO_SUCH_COLUMN'>())
}
Loading