Skip to content

feat: add WithPgPlaceholder() option #7

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

Merged
merged 2 commits into from
Aug 16, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
13 changes: 12 additions & 1 deletion mql.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ type WhereClause struct {
}

// Parse will parse the query and use the provided database model to create a
// where clause. Supported options: WithColumnMap, WithIgnoreFields
// where clause. Supported options: WithColumnMap, WithIgnoreFields,
// WithConverter, WithPgPlaceholder
func Parse(query string, model any, opt ...Option) (*WhereClause, error) {
const op = "mql.Parse"
switch {
Expand All @@ -40,6 +41,16 @@ func Parse(query string, model any, opt ...Option) (*WhereClause, error) {
if err != nil {
return nil, fmt.Errorf("%s: %w", op, err)
}
opts, err := getOpts(opt...)
if err != nil {
return nil, fmt.Errorf("%s: %w", op, err)
}
if opts.withPgPlaceholder {
for i := 0; i < len(e.Args); i++ {
placeholder := fmt.Sprintf("$%d", i+1)
e.Condition = strings.Replace(e.Condition, "?", placeholder, 1)
}
}
return e, nil
}

Expand Down
10 changes: 10 additions & 0 deletions mql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,16 @@ func TestParse(t *testing.T) {
Args: []any{"%alice%"},
},
},
{
name: "success-WithPgPlaceholder",
query: "name=bob or (name%alice or name=eve)",
model: testModel{},
opts: []mql.Option{mql.WithPgPlaceholders()},
want: &mql.WhereClause{
Condition: "(name=$1 or (name like $2 or name=$3))",
Args: []any{"bob", "%alice%", "eve"},
},
},
{
name: "err-leftExpr-without-op",
query: "age (name=alice)",
Expand Down
11 changes: 11 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ type options struct {
withValidateConvertFn ValidateConvertFunc
withValidateConvertColumn string
withIgnoredFields []string
withPgPlaceholder bool
}

// Option - how options are passed as args
Expand Down Expand Up @@ -91,3 +92,13 @@ func WithIgnoredFields(fieldName ...string) Option {
return nil
}
}

// WithPgPlaceholders will use parameters placeholders that are compatible with
// the postgres pg driver which requires a placeholder like $1 instead of ?.
// See: https://pkg.go.dev/github.com/lib/pq
func WithPgPlaceholders() Option {
return func(o *options) error {
o.withPgPlaceholder = true
return nil
}
}