mirror of
https://github.com/ent/ent.git
synced 2026-04-28 21:50:56 +03:00
dialect/sql/sqljson: fix sqlite haskey and add docs
This commit is contained in:
committed by
Ariel Mashraki
parent
3ba2b4e173
commit
0dd7b0d7c3
@@ -21,8 +21,24 @@ import (
|
||||
//
|
||||
func HasKey(column string, opts ...Option) *sql.Predicate {
|
||||
return sql.P(func(b *sql.Builder) {
|
||||
ValuePath(b, column, opts...)
|
||||
b.WriteOp(sql.OpNotNull)
|
||||
switch b.Dialect() {
|
||||
case dialect.SQLite:
|
||||
b.Nested(func(b *sql.Builder) {
|
||||
b.Join(
|
||||
sql.Or(
|
||||
// The result is NULL for JSON null.
|
||||
sql.P(func(b *sql.Builder) {
|
||||
ValuePath(b, column, opts...)
|
||||
b.WriteOp(sql.OpNotNull)
|
||||
}),
|
||||
ValueIsNull(column, opts...),
|
||||
),
|
||||
)
|
||||
})
|
||||
default:
|
||||
ValuePath(b, column, opts...)
|
||||
b.WriteOp(sql.OpNotNull)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -51,11 +51,38 @@ func TestWritePath(t *testing.T) {
|
||||
wantQuery: "SELECT * FROM `test` WHERE JSON_EXTRACT(`j`, \"$.a.*.c\") IS NOT NULL",
|
||||
},
|
||||
{
|
||||
input: sql.Dialect(dialect.Postgres).
|
||||
input: sql.Select("*").
|
||||
From(sql.Table("test")).
|
||||
Where(sqljson.HasKey("j", sqljson.DotPath("a.*.c"))),
|
||||
wantQuery: "SELECT * FROM `test` WHERE JSON_EXTRACT(`j`, \"$.a.*.c\") IS NOT NULL",
|
||||
},
|
||||
{
|
||||
input: sql.Dialect(dialect.SQLite).
|
||||
Select("*").
|
||||
From(sql.Table("test")).
|
||||
Where(sqljson.HasKey("j", sqljson.DotPath("a.b.c"))),
|
||||
wantQuery: `SELECT * FROM "test" WHERE "j"->'a'->'b'->'c' IS NOT NULL`,
|
||||
Where(sqljson.HasKey("j", sqljson.DotPath("attributes[1].body"))),
|
||||
wantQuery: "SELECT * FROM `test` WHERE (JSON_EXTRACT(`j`, \"$.attributes[1].body\") IS NOT NULL OR JSON_TYPE(`j`, \"$.attributes[1].body\") = 'null')",
|
||||
},
|
||||
{
|
||||
input: sql.Dialect(dialect.SQLite).
|
||||
Select("*").
|
||||
From(sql.Table("test")).
|
||||
Where(sqljson.HasKey("j", sqljson.DotPath("a.*.c"))),
|
||||
wantQuery: "SELECT * FROM `test` WHERE (JSON_EXTRACT(`j`, \"$.a.*.c\") IS NOT NULL OR JSON_TYPE(`j`, \"$.a.*.c\") = 'null')",
|
||||
},
|
||||
{
|
||||
input: sql.Dialect(dialect.SQLite).
|
||||
Select("*").
|
||||
From(sql.Table("test")).
|
||||
Where(
|
||||
sql.And(
|
||||
sql.GT("id", 100),
|
||||
sqljson.HasKey("j", sqljson.DotPath("a.*.c")),
|
||||
sql.EQ("active", true),
|
||||
),
|
||||
),
|
||||
wantQuery: "SELECT * FROM `test` WHERE `id` > ? AND (JSON_EXTRACT(`j`, \"$.a.*.c\") IS NOT NULL OR JSON_TYPE(`j`, \"$.a.*.c\") = 'null') AND `active` = ?",
|
||||
wantArgs: []interface{}{100, true},
|
||||
},
|
||||
{
|
||||
input: sql.Dialect(dialect.Postgres).
|
||||
|
||||
Reference in New Issue
Block a user