Skip to content
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

Implement filter pushdown #3482

Merged
merged 26 commits into from
Oct 9, 2023
Merged
Show file tree
Hide file tree
Changes from 24 commits
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
57 changes: 36 additions & 21 deletions internal/backends/postgresql/collection.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@
return nil, lazyerrors.Error(err)
}

if params == nil {
params = new(backends.QueryParams)
}

Check warning on line 61 in internal/backends/postgresql/collection.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/collection.go#L59-L61

Added lines #L59 - L61 were not covered by tests

if p == nil {
return &backends.QueryResult{
Iter: newQueryIterator(ctx, nil),
Expand All @@ -73,14 +77,18 @@
}, nil
}

// TODO https://github.com/FerretDB/FerretDB/issues/3414
q := fmt.Sprintf(
`SELECT %s FROM %s`,
metadata.DefaultColumn,
pgx.Identifier{c.dbName, meta.TableName}.Sanitize(),
)
q := prepareSelectClause(c.dbName, meta.TableName)

var placeholder metadata.Placeholder

Check warning on line 82 in internal/backends/postgresql/collection.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/collection.go#L80-L82

Added lines #L80 - L82 were not covered by tests

rows, err := p.Query(ctx, q)
where, args, err := prepareWhereClause(&placeholder, params.Filter)
if err != nil {
return nil, lazyerrors.Error(err)
}

Check warning on line 87 in internal/backends/postgresql/collection.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/collection.go#L84-L87

Added lines #L84 - L87 were not covered by tests

q += where

rows, err := p.Query(ctx, q, args...)

Check warning on line 91 in internal/backends/postgresql/collection.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/collection.go#L89-L91

Added lines #L89 - L91 were not covered by tests
if err != nil {
return nil, lazyerrors.Error(err)
}
Expand Down Expand Up @@ -251,8 +259,10 @@
return nil, lazyerrors.Error(err)
}

res := new(backends.ExplainResult)

Check warning on line 263 in internal/backends/postgresql/collection.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/collection.go#L262-L263

Added lines #L262 - L263 were not covered by tests
if p == nil {
return new(backends.ExplainResult), nil
return res, nil

Check warning on line 265 in internal/backends/postgresql/collection.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/collection.go#L265

Added line #L265 was not covered by tests
}

meta, err := c.r.CollectionGet(ctx, c.dbName, c.name)
Expand All @@ -261,20 +271,25 @@
}

if meta == nil {
return &backends.ExplainResult{
QueryPlanner: must.NotFail(types.NewDocument()),
}, nil
res.QueryPlanner = must.NotFail(types.NewDocument())
return res, nil

Check warning on line 275 in internal/backends/postgresql/collection.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/collection.go#L274-L275

Added lines #L274 - L275 were not covered by tests
}

// TODO https://github.com/FerretDB/FerretDB/issues/3414
q := fmt.Sprintf(
`EXPLAIN (VERBOSE true, FORMAT JSON) SELECT %s FROM %s`,
metadata.DefaultColumn,
pgx.Identifier{c.dbName, meta.TableName}.Sanitize(),
)
q := `EXPLAIN (VERBOSE true, FORMAT JSON) ` + prepareSelectClause(c.dbName, meta.TableName)

var placeholder metadata.Placeholder

where, args, err := prepareWhereClause(&placeholder, params.Filter)
if err != nil {
return nil, lazyerrors.Error(err)
}

Check warning on line 285 in internal/backends/postgresql/collection.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/collection.go#L278-L285

Added lines #L278 - L285 were not covered by tests

res.QueryPushdown = where != ""

q += where

Check warning on line 289 in internal/backends/postgresql/collection.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/collection.go#L287-L289

Added lines #L287 - L289 were not covered by tests

var b []byte
err = p.QueryRow(ctx, q).Scan(&b)
err = p.QueryRow(ctx, q, args...).Scan(&b)

Check warning on line 292 in internal/backends/postgresql/collection.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/collection.go#L292

Added line #L292 was not covered by tests

if err != nil {
return nil, lazyerrors.Error(err)
Expand All @@ -285,9 +300,9 @@
return nil, lazyerrors.Error(err)
}

return &backends.ExplainResult{
QueryPlanner: must.NotFail(types.NewDocument("Plan", queryPlan)),
}, nil
res.QueryPlanner = queryPlan

return res, nil

Check warning on line 305 in internal/backends/postgresql/collection.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/collection.go#L303-L305

Added lines #L303 - L305 were not covered by tests
}

// Stats implements backends.Collection interface.
Expand Down
228 changes: 228 additions & 0 deletions internal/backends/postgresql/query.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
// Copyright 2021 FerretDB Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package postgresql

import (
"errors"
"fmt"
"strings"
"time"

"github.com/jackc/pgx/v5"

"github.com/FerretDB/FerretDB/internal/backends/postgresql/metadata"
"github.com/FerretDB/FerretDB/internal/handlers/sjson"
"github.com/FerretDB/FerretDB/internal/types"
"github.com/FerretDB/FerretDB/internal/util/iterator"
"github.com/FerretDB/FerretDB/internal/util/lazyerrors"
"github.com/FerretDB/FerretDB/internal/util/must"
)

// prepareSelectClause returns simple SELECT clause for provided db and table name,
// that can be used to construct the SQL query.
func prepareSelectClause(db, table string) string {
return fmt.Sprintf(
`SELECT %s FROM %s`,
metadata.DefaultColumn,
pgx.Identifier{db, table}.Sanitize(),
)

Check warning on line 40 in internal/backends/postgresql/query.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/query.go#L35-L40

Added lines #L35 - L40 were not covered by tests
}

// prepareWhereClause adds WHERE clause with given filters to the query and returns the query and arguments.
func prepareWhereClause(p *metadata.Placeholder, sqlFilters *types.Document) (string, []any, error) {
var filters []string
var args []any

iter := sqlFilters.Iterator()
defer iter.Close()

// iterate through root document
for {
rootKey, rootVal, err := iter.Next()
if err != nil {
if errors.Is(err, iterator.ErrIteratorDone) {
break
}

return "", nil, lazyerrors.Error(err)

Check warning on line 59 in internal/backends/postgresql/query.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/query.go#L59

Added line #L59 was not covered by tests
}

// don't pushdown $comment, it's attached to query in handlers
if strings.HasPrefix(rootKey, "$") {
continue
}

path, err := types.NewPathFromString(rootKey)

var pe *types.PathError

switch {
case err == nil:
// Handle dot notation.
// TODO https://github.com/FerretDB/FerretDB/issues/2069
if path.Len() > 1 {
continue
}
case errors.As(err, &pe):
// ignore empty key error, otherwise return error
if pe.Code() != types.ErrPathElementEmpty {
return "", nil, lazyerrors.Error(err)
}
default:
panic("Invalid error type: PathError expected")

Check warning on line 84 in internal/backends/postgresql/query.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/query.go#L78-L84

Added lines #L78 - L84 were not covered by tests
}

switch v := rootVal.(type) {
case *types.Document:
iter := v.Iterator()
defer iter.Close()

// iterate through subdocument, as it may contain operators
for {
k, v, err := iter.Next()
if err != nil {
if errors.Is(err, iterator.ErrIteratorDone) {
break
}

return "", nil, lazyerrors.Error(err)

Check warning on line 100 in internal/backends/postgresql/query.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/query.go#L100

Added line #L100 was not covered by tests
}

switch k {
case "$eq":
if f, a := filterEqual(p, rootKey, v); f != "" {
filters = append(filters, f)
args = append(args, a...)
}

case "$ne":
sql := `NOT ( ` +
// does document contain the key,
// it is necessary, as NOT won't work correctly if the key does not exist.
`_jsonb ? %[1]s AND ` +
// does the value under the key is equal to filter value
`_jsonb->%[1]s @> %[2]s AND ` +
// does the value type is equal to the filter's one
`_jsonb->'$s'->'p'->%[1]s->'t' = '"%[3]s"' )`

switch v := v.(type) {
case *types.Document, *types.Array, types.Binary,
types.NullType, types.Regex, types.Timestamp:

Check warning on line 122 in internal/backends/postgresql/query.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/query.go#L122

Added line #L122 was not covered by tests
// type not supported for pushdown

case float64, bool, int32, int64:
filters = append(filters, fmt.Sprintf(sql, p.Next(), p.Next(), sjson.GetTypeOfValue(v)))
args = append(args, rootKey, v)

case string, types.ObjectID, time.Time:
filters = append(filters, fmt.Sprintf(sql, p.Next(), p.Next(), sjson.GetTypeOfValue(v)))
args = append(args, rootKey, string(must.NotFail(sjson.MarshalSingleValue(v))))

default:
panic(fmt.Sprintf("Unexpected type of value: %v", v))

Check warning on line 134 in internal/backends/postgresql/query.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/query.go#L133-L134

Added lines #L133 - L134 were not covered by tests
}

default:
// $gt and $lt
// TODO https://github.com/FerretDB/FerretDB/issues/1875
continue

Check warning on line 140 in internal/backends/postgresql/query.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/query.go#L137-L140

Added lines #L137 - L140 were not covered by tests
}
}

case *types.Array, types.Binary, types.NullType, types.Regex, types.Timestamp:

Check warning on line 144 in internal/backends/postgresql/query.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/query.go#L144

Added line #L144 was not covered by tests
// type not supported for pushdown

case float64, string, types.ObjectID, bool, time.Time, int32, int64:
if f, a := filterEqual(p, rootKey, v); f != "" {
filters = append(filters, f)
args = append(args, a...)
}

default:
panic(fmt.Sprintf("Unexpected type of value: %v", v))

Check warning on line 154 in internal/backends/postgresql/query.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/query.go#L153-L154

Added lines #L153 - L154 were not covered by tests
}
}

var filter string
if len(filters) > 0 {
filter = ` WHERE ` + strings.Join(filters, " AND ")
}

return filter, args, nil
}

// filterEqual returns the proper SQL filter with arguments that filters documents
// where the value under k is equal to v.
func filterEqual(p *metadata.Placeholder, k string, v any) (filter string, args []any) {
// Select if value under the key is equal to provided value.
sql := `_jsonb->%[1]s @> %[2]s`

switch v := v.(type) {
case *types.Document, *types.Array, types.Binary,
types.NullType, types.Regex, types.Timestamp:

Check warning on line 174 in internal/backends/postgresql/query.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/query.go#L174

Added line #L174 was not covered by tests
// type not supported for pushdown

case float64:
// If value is not safe double, fetch all numbers out of safe range.
switch {
case v > types.MaxSafeDouble:
sql = `_jsonb->%[1]s > %[2]s`
v = types.MaxSafeDouble

case v < -types.MaxSafeDouble:
sql = `_jsonb->%[1]s < %[2]s`
v = -types.MaxSafeDouble

Check warning on line 186 in internal/backends/postgresql/query.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/query.go#L184-L186

Added lines #L184 - L186 were not covered by tests
default:
// don't change the default eq query
rumyantseva marked this conversation as resolved.
Show resolved Hide resolved
}

filter = fmt.Sprintf(sql, p.Next(), p.Next())
args = append(args, k, v)

case string, types.ObjectID, time.Time:
// don't change the default eq query
filter = fmt.Sprintf(sql, p.Next(), p.Next())
args = append(args, k, string(must.NotFail(sjson.MarshalSingleValue(v))))

case bool, int32:
// don't change the default eq query
filter = fmt.Sprintf(sql, p.Next(), p.Next())
args = append(args, k, v)

case int64:
maxSafeDouble := int64(types.MaxSafeDouble)

// If value cannot be safe double, fetch all numbers out of the safe range.
switch {
case v > maxSafeDouble:
sql = `_jsonb->%[1]s > %[2]s`
v = maxSafeDouble

Check warning on line 211 in internal/backends/postgresql/query.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/query.go#L209-L211

Added lines #L209 - L211 were not covered by tests

case v < -maxSafeDouble:
sql = `_jsonb->%[1]s < %[2]s`
v = -maxSafeDouble

Check warning on line 215 in internal/backends/postgresql/query.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/query.go#L213-L215

Added lines #L213 - L215 were not covered by tests
default:
// don't change the default eq query
rumyantseva marked this conversation as resolved.
Show resolved Hide resolved
}

filter = fmt.Sprintf(sql, p.Next(), p.Next())
args = append(args, k, v)

default:
panic(fmt.Sprintf("Unexpected type of value: %v", v))

Check warning on line 224 in internal/backends/postgresql/query.go

View check run for this annotation

Codecov / codecov/patch

internal/backends/postgresql/query.go#L223-L224

Added lines #L223 - L224 were not covered by tests
}

return
}
Loading
Loading