Skip to content

Commit fa247ec

Browse files
committed
feat: add WithPgPlaceholder() option
1 parent f38bfb1 commit fa247ec

File tree

3 files changed

+33
-1
lines changed

3 files changed

+33
-1
lines changed

mql.go

+12-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ type WhereClause struct {
1818
}
1919

2020
// Parse will parse the query and use the provided database model to create a
21-
// where clause. Supported options: WithColumnMap, WithIgnoreFields
21+
// where clause. Supported options: WithColumnMap, WithIgnoreFields,
22+
// WithConverter, WithPgPlaceholder
2223
func Parse(query string, model any, opt ...Option) (*WhereClause, error) {
2324
const op = "mql.Parse"
2425
switch {
@@ -40,6 +41,16 @@ func Parse(query string, model any, opt ...Option) (*WhereClause, error) {
4041
if err != nil {
4142
return nil, fmt.Errorf("%s: %w", op, err)
4243
}
44+
opts, err := getOpts(opt...)
45+
if err != nil {
46+
return nil, fmt.Errorf("%s: %w", op, err)
47+
}
48+
if opts.withPgPlaceholder {
49+
for i := 0; i < len(e.Args); i++ {
50+
placeholder := fmt.Sprintf("$%d", i+1)
51+
e.Condition = strings.Replace(e.Condition, "?", placeholder, 1)
52+
}
53+
}
4354
return e, nil
4455
}
4556

mql_test.go

+10
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,16 @@ func TestParse(t *testing.T) {
6666
Args: []any{"%alice%"},
6767
},
6868
},
69+
{
70+
name: "success-WithPgPlaceholder",
71+
query: "name=bob or (name%alice or name=eve)",
72+
model: testModel{},
73+
opts: []mql.Option{mql.WithPgPlaceholders()},
74+
want: &mql.WhereClause{
75+
Condition: "(name=$1 or (name like $2 or name=$3))",
76+
Args: []any{"bob", "%alice%", "eve"},
77+
},
78+
},
6979
{
7080
name: "err-leftExpr-without-op",
7181
query: "age (name=alice)",

options.go

+11
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ type options struct {
1313
withValidateConvertFn ValidateConvertFunc
1414
withValidateConvertColumn string
1515
withIgnoredFields []string
16+
withPgPlaceholder bool
1617
}
1718

1819
// Option - how options are passed as args
@@ -91,3 +92,13 @@ func WithIgnoredFields(fieldName ...string) Option {
9192
return nil
9293
}
9394
}
95+
96+
// WithPgPlaceholders will use parameters placeholders that are compatible with
97+
// the postgres pg driver which requires a placeholder like $1 instead of ?.
98+
// See: https://pkg.go.dev/github.com/lib/pq
99+
func WithPgPlaceholders() Option {
100+
return func(o *options) error {
101+
o.withPgPlaceholder = true
102+
return nil
103+
}
104+
}

0 commit comments

Comments
 (0)