dialect/sql/sqljson: add ValueIsNotNull predicate (#3058)

* dialect/sql: add json ValueIsNotNull predicate

* get rid of false positive dupl linter warning

* add json valueIsNotNull case to integration tests

* fix rejects
This commit is contained in:
Ronen Lubin
2022-11-02 11:18:15 +02:00
committed by GitHub
parent 35d0d4c3db
commit 5d4f02620d
3 changed files with 47 additions and 1 deletions

View File

@@ -62,6 +62,31 @@ func ValueIsNull(column string, opts ...Option) *sql.Predicate {
})
}
// ValueIsNotNull return a predicate for checking that a JSON value
// (returned by the path) is not null literal (JSON "null").
//
// sqljson.ValueIsNotNull("a", sqljson.Path("b"))
func ValueIsNotNull(column string, opts ...Option) *sql.Predicate {
return sql.P(func(b *sql.Builder) {
switch b.Dialect() {
case dialect.Postgres:
valuePath(b, column, append(opts, Cast("jsonb"))...)
b.WriteOp(sql.OpNEQ).WriteString("'null'::jsonb")
case dialect.SQLite:
path := identPath(column, opts...)
path.mysqlFunc("JSON_TYPE", b)
b.WriteOp(sql.OpNEQ).WriteString("'null'")
case dialect.MySQL:
path := identPath(column, opts...)
b.WriteString("NOT(JSON_CONTAINS").Wrap(func(b *sql.Builder) {
b.Ident(column).Comma()
b.WriteString("'null'").Comma()
path.mysqlPath(b)
}).WriteString(")")
}
})
}
// ValueEQ return a predicate for checking that a JSON value
// (returned by the path) is equal to the given argument.
//