mirror of
https://github.com/ent/ent.git
synced 2026-04-28 13:40:56 +03:00
dialect/sql/sqljson: support comparing values with null literal
This commit is contained in:
committed by
Ariel Mashraki
parent
f6c9428978
commit
0c5398a11d
@@ -26,6 +26,30 @@ func HasKey(column string, opts ...Option) *sql.Predicate {
|
||||
})
|
||||
}
|
||||
|
||||
// ValueIsNull return a predicate for checking that a JSON value
|
||||
// (returned by the path) is a null literal (JSON "null").
|
||||
//
|
||||
// In order to check if the column is NULL (database NULL), or if
|
||||
// the JSON key exists, use sql.IsNull or sqljson.HasKey.
|
||||
//
|
||||
// sqljson.ValueIsNull("a", sqljson.Path("b"))
|
||||
//
|
||||
func ValueIsNull(column string, opts ...Option) *sql.Predicate {
|
||||
return nullP(sql.OpEQ, column, opts...)
|
||||
}
|
||||
|
||||
// ValueNotNull return a predicate for checking that a JSON value
|
||||
// (returned by the path) is not a null literal (JSON "null").
|
||||
//
|
||||
// In order to check if the column is not NULL (database NULL), or
|
||||
// if the JSON key exists, use sql.NotNull or sqljson.HasKey.
|
||||
//
|
||||
// sqljson.ValueNotNull("a", sqljson.Path("b"))
|
||||
//
|
||||
func ValueNotNull(column string, opts ...Option) *sql.Predicate {
|
||||
return nullP(sql.OpNEQ, column, opts...)
|
||||
}
|
||||
|
||||
// ValueEQ return a predicate for checking that a JSON value
|
||||
// (returned by the path) is equal to the given argument.
|
||||
//
|
||||
@@ -424,6 +448,28 @@ func ParsePath(dotpath string) ([]string, error) {
|
||||
return path, nil
|
||||
}
|
||||
|
||||
// nullP creates a predicate that compares (using the given operator)
|
||||
// the JSON value to the JSON null literal.
|
||||
func nullP(op sql.Op, column string, opts ...Option) *sql.Predicate {
|
||||
return sql.P(func(b *sql.Builder) {
|
||||
switch b.Dialect() {
|
||||
case dialect.MySQL:
|
||||
ValuePath(b, column, opts...)
|
||||
b.WriteOp(op).WriteString("CAST('null' AS JSON)")
|
||||
case dialect.Postgres:
|
||||
ValuePath(b, column, append(opts, Cast("jsonb"))...)
|
||||
b.WriteOp(op).WriteString("'null'::jsonb")
|
||||
case dialect.SQLite:
|
||||
path := &PathOptions{Ident: column}
|
||||
for i := range opts {
|
||||
opts[i](path)
|
||||
}
|
||||
path.mysqlFunc("JSON_TYPE", b)
|
||||
b.WriteOp(op).WriteString("'null'")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// normalizePG adds cast option to the JSON path is the argument type is
|
||||
// not string, in order to avoid "missing type casts" error in Postgres.
|
||||
func normalizePG(b *sql.Builder, arg interface{}, opts []Option) ([]Option, interface{}) {
|
||||
|
||||
Reference in New Issue
Block a user