diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/go.sum b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..a92f768e60f084b42661848ff2828be637d9bfac --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/go.sum @@ -0,0 +1,10 @@ +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw= +github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o= +github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk= +github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/insert.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/insert.go new file mode 100644 index 0000000000000000000000000000000000000000..97870783aad362fc20fb246ca128fefca341e637 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/insert.go @@ -0,0 +1,298 @@ +package squirrel + +import ( + "bytes" + "database/sql" + "errors" + "fmt" + "io" + "sort" + "strings" + + "github.com/lann/builder" +) + +type insertData struct { + PlaceholderFormat PlaceholderFormat + RunWith BaseRunner + Prefixes []Sqlizer + StatementKeyword string + Options []string + Into string + Columns []string + Values [][]interface{} + Suffixes []Sqlizer + Select *SelectBuilder +} + +func (d *insertData) Exec() (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return ExecWith(d.RunWith, d) +} + +func (d *insertData) Query() (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return QueryWith(d.RunWith, d) +} + +func (d *insertData) QueryRow() RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRower) + if !ok { + return &Row{err: RunnerNotQueryRunner} + } + return QueryRowWith(queryRower, d) +} + +func (d *insertData) ToSql() (sqlStr string, args []interface{}, err error) { + if len(d.Into) == 0 { + err = errors.New("insert statements must specify a table") + return + } + if len(d.Values) == 0 && d.Select == nil { + err = errors.New("insert statements must have at least one set of values or select clause") + return + } + + sql := &bytes.Buffer{} + + if len(d.Prefixes) > 0 { + args, err = appendToSql(d.Prefixes, sql, " ", args) + if err != nil { + return + } + + sql.WriteString(" ") + } + + if d.StatementKeyword == "" { + sql.WriteString("INSERT ") + } else { + sql.WriteString(d.StatementKeyword) + sql.WriteString(" ") + } + + if len(d.Options) > 0 { + sql.WriteString(strings.Join(d.Options, " ")) + sql.WriteString(" ") + } + + sql.WriteString("INTO ") + sql.WriteString(d.Into) + sql.WriteString(" ") + + if len(d.Columns) > 0 { + sql.WriteString("(") + sql.WriteString(strings.Join(d.Columns, ",")) + sql.WriteString(") ") + } + + if d.Select != nil { + args, err = d.appendSelectToSQL(sql, args) + } else { + args, err = d.appendValuesToSQL(sql, args) + } + if err != nil { + return + } + + if len(d.Suffixes) > 0 { + sql.WriteString(" ") + args, err = appendToSql(d.Suffixes, sql, " ", args) + if err != nil { + return + } + } + + sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sql.String()) + return +} + +func (d *insertData) appendValuesToSQL(w io.Writer, args []interface{}) ([]interface{}, error) { + if len(d.Values) == 0 { + return args, errors.New("values for insert statements are not set") + } + + io.WriteString(w, "VALUES ") + + valuesStrings := make([]string, len(d.Values)) + for r, row := range d.Values { + valueStrings := make([]string, len(row)) + for v, val := range row { + if vs, ok := val.(Sqlizer); ok { + vsql, vargs, err := vs.ToSql() + if err != nil { + return nil, err + } + valueStrings[v] = vsql + args = append(args, vargs...) + } else { + valueStrings[v] = "?" + args = append(args, val) + } + } + valuesStrings[r] = fmt.Sprintf("(%s)", strings.Join(valueStrings, ",")) + } + + io.WriteString(w, strings.Join(valuesStrings, ",")) + + return args, nil +} + +func (d *insertData) appendSelectToSQL(w io.Writer, args []interface{}) ([]interface{}, error) { + if d.Select == nil { + return args, errors.New("select clause for insert statements are not set") + } + + selectClause, sArgs, err := d.Select.ToSql() + if err != nil { + return args, err + } + + io.WriteString(w, selectClause) + args = append(args, sArgs...) + + return args, nil +} + +// Builder + +// InsertBuilder builds SQL INSERT statements. +type InsertBuilder builder.Builder + +func init() { + builder.Register(InsertBuilder{}, insertData{}) +} + +// Format methods + +// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the +// query. +func (b InsertBuilder) PlaceholderFormat(f PlaceholderFormat) InsertBuilder { + return builder.Set(b, "PlaceholderFormat", f).(InsertBuilder) +} + +// Runner methods + +// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec. +func (b InsertBuilder) RunWith(runner BaseRunner) InsertBuilder { + return setRunWith(b, runner).(InsertBuilder) +} + +// Exec builds and Execs the query with the Runner set by RunWith. +func (b InsertBuilder) Exec() (sql.Result, error) { + data := builder.GetStruct(b).(insertData) + return data.Exec() +} + +// Query builds and Querys the query with the Runner set by RunWith. +func (b InsertBuilder) Query() (*sql.Rows, error) { + data := builder.GetStruct(b).(insertData) + return data.Query() +} + +// QueryRow builds and QueryRows the query with the Runner set by RunWith. +func (b InsertBuilder) QueryRow() RowScanner { + data := builder.GetStruct(b).(insertData) + return data.QueryRow() +} + +// Scan is a shortcut for QueryRow().Scan. +func (b InsertBuilder) Scan(dest ...interface{}) error { + return b.QueryRow().Scan(dest...) +} + +// SQL methods + +// ToSql builds the query into a SQL string and bound args. +func (b InsertBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(insertData) + return data.ToSql() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b InsertBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// Prefix adds an expression to the beginning of the query +func (b InsertBuilder) Prefix(sql string, args ...interface{}) InsertBuilder { + return b.PrefixExpr(Expr(sql, args...)) +} + +// PrefixExpr adds an expression to the very beginning of the query +func (b InsertBuilder) PrefixExpr(expr Sqlizer) InsertBuilder { + return builder.Append(b, "Prefixes", expr).(InsertBuilder) +} + +// Options adds keyword options before the INTO clause of the query. +func (b InsertBuilder) Options(options ...string) InsertBuilder { + return builder.Extend(b, "Options", options).(InsertBuilder) +} + +// Into sets the INTO clause of the query. +func (b InsertBuilder) Into(into string) InsertBuilder { + return builder.Set(b, "Into", into).(InsertBuilder) +} + +// Columns adds insert columns to the query. +func (b InsertBuilder) Columns(columns ...string) InsertBuilder { + return builder.Extend(b, "Columns", columns).(InsertBuilder) +} + +// Values adds a single row's values to the query. +func (b InsertBuilder) Values(values ...interface{}) InsertBuilder { + return builder.Append(b, "Values", values).(InsertBuilder) +} + +// Suffix adds an expression to the end of the query +func (b InsertBuilder) Suffix(sql string, args ...interface{}) InsertBuilder { + return b.SuffixExpr(Expr(sql, args...)) +} + +// SuffixExpr adds an expression to the end of the query +func (b InsertBuilder) SuffixExpr(expr Sqlizer) InsertBuilder { + return builder.Append(b, "Suffixes", expr).(InsertBuilder) +} + +// SetMap set columns and values for insert builder from a map of column name and value +// note that it will reset all previous columns and values was set if any +func (b InsertBuilder) SetMap(clauses map[string]interface{}) InsertBuilder { + // Keep the columns in a consistent order by sorting the column key string. + cols := make([]string, 0, len(clauses)) + for col := range clauses { + cols = append(cols, col) + } + sort.Strings(cols) + + vals := make([]interface{}, 0, len(clauses)) + for _, col := range cols { + vals = append(vals, clauses[col]) + } + + b = builder.Set(b, "Columns", cols).(InsertBuilder) + b = builder.Set(b, "Values", [][]interface{}{vals}).(InsertBuilder) + + return b +} + +// Select set Select clause for insert query +// If Values and Select are used, then Select has higher priority +func (b InsertBuilder) Select(sb SelectBuilder) InsertBuilder { + return builder.Set(b, "Select", &sb).(InsertBuilder) +} + +func (b InsertBuilder) statementKeyword(keyword string) InsertBuilder { + return builder.Set(b, "StatementKeyword", keyword).(InsertBuilder) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/insert_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/insert_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..4541c2fed325335b17253caaf066bcdd043f365b --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/insert_ctx.go @@ -0,0 +1,69 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + + "github.com/lann/builder" +) + +func (d *insertData) ExecContext(ctx context.Context) (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(ExecerContext) + if !ok { + return nil, NoContextSupport + } + return ExecContextWith(ctx, ctxRunner, d) +} + +func (d *insertData) QueryContext(ctx context.Context) (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(QueryerContext) + if !ok { + return nil, NoContextSupport + } + return QueryContextWith(ctx, ctxRunner, d) +} + +func (d *insertData) QueryRowContext(ctx context.Context) RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRowerContext) + if !ok { + if _, ok := d.RunWith.(QueryerContext); !ok { + return &Row{err: RunnerNotQueryRunner} + } + return &Row{err: NoContextSupport} + } + return QueryRowContextWith(ctx, queryRower, d) +} + +// ExecContext builds and ExecContexts the query with the Runner set by RunWith. +func (b InsertBuilder) ExecContext(ctx context.Context) (sql.Result, error) { + data := builder.GetStruct(b).(insertData) + return data.ExecContext(ctx) +} + +// QueryContext builds and QueryContexts the query with the Runner set by RunWith. +func (b InsertBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) { + data := builder.GetStruct(b).(insertData) + return data.QueryContext(ctx) +} + +// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith. +func (b InsertBuilder) QueryRowContext(ctx context.Context) RowScanner { + data := builder.GetStruct(b).(insertData) + return data.QueryRowContext(ctx) +} + +// ScanContext is a shortcut for QueryRowContext().Scan. +func (b InsertBuilder) ScanContext(ctx context.Context, dest ...interface{}) error { + return b.QueryRowContext(ctx).Scan(dest...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/integration/doc.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/integration/doc.go new file mode 100644 index 0000000000000000000000000000000000000000..3796ab9ede31bfc6ce6f0872e70aad4d46a6beb3 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/integration/doc.go @@ -0,0 +1,2 @@ +// This is a tests-only package. +package integration diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/integration/go.mod b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/integration/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..8029ff8c8b17e541eaf93d5b0d3bab3cc33067fc --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/integration/go.mod @@ -0,0 +1,14 @@ +module github.com/Masterminds/squirrel/integration + +go 1.12 + +require ( + github.com/Masterminds/squirrel v1.1.0 + github.com/go-sql-driver/mysql v1.4.1 + github.com/lib/pq v1.2.0 + github.com/mattn/go-sqlite3 v1.13.0 + github.com/stretchr/testify v1.4.0 + google.golang.org/appengine v1.6.5 // indirect +) + +replace github.com/Masterminds/squirrel => ../ diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/integration/go.sum b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/integration/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..0bfcfa9f096176f194a2b5275638d2688cb952a9 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/integration/go.sum @@ -0,0 +1,34 @@ +github.com/Masterminds/squirrel v1.1.0 h1:baP1qLdoQCeTw3ifCdOq2dkYc6vGcmRdaociKLbEJXs= +github.com/Masterminds/squirrel v1.1.0/go.mod h1:yaPeOnPG5ZRwL9oKdTsO/prlkPbXWZlRVMQ/gGlzIuA= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-sql-driver/mysql v1.4.1 h1:g24URVg0OFbNUTx9qqY1IRZ9D9z3iPyi5zKhQZpNwpA= +github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw= +github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o= +github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk= +github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw= +github.com/lib/pq v1.2.0 h1:LXpIM/LZ5xGFhOpXAQUIMM1HdyqzVYM13zNdjCEEcA0= +github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/mattn/go-sqlite3 v1.13.0 h1:LnJI81JidiW9r7pS/hXe6cFeO5EXNq7KbfvoJLRI69c= +github.com/mattn/go-sqlite3 v1.13.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +google.golang.org/appengine v1.6.5 h1:tycE03LOZYQNhDpS27tcQdAzLCVMaj7QT2SXxebnpCM= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/part.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/part.go new file mode 100644 index 0000000000000000000000000000000000000000..c58f68f1a49717818bc349bede5cbf239bb06769 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/part.go @@ -0,0 +1,63 @@ +package squirrel + +import ( + "fmt" + "io" +) + +type part struct { + pred interface{} + args []interface{} +} + +func newPart(pred interface{}, args ...interface{}) Sqlizer { + return &part{pred, args} +} + +func (p part) ToSql() (sql string, args []interface{}, err error) { + switch pred := p.pred.(type) { + case nil: + // no-op + case Sqlizer: + sql, args, err = nestedToSql(pred) + case string: + sql = pred + args = p.args + default: + err = fmt.Errorf("expected string or Sqlizer, not %T", pred) + } + return +} + +func nestedToSql(s Sqlizer) (string, []interface{}, error) { + if raw, ok := s.(rawSqlizer); ok { + return raw.toSqlRaw() + } else { + return s.ToSql() + } +} + +func appendToSql(parts []Sqlizer, w io.Writer, sep string, args []interface{}) ([]interface{}, error) { + for i, p := range parts { + partSql, partArgs, err := nestedToSql(p) + if err != nil { + return nil, err + } else if len(partSql) == 0 { + continue + } + + if i > 0 { + _, err := io.WriteString(w, sep) + if err != nil { + return nil, err + } + } + + _, err = io.WriteString(w, partSql) + if err != nil { + return nil, err + } + args = append(args, partArgs...) + } + return args, nil +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/placeholder.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/placeholder.go new file mode 100644 index 0000000000000000000000000000000000000000..8e97a6c62d4b430def230bd65a84b6e294b11284 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/placeholder.go @@ -0,0 +1,114 @@ +package squirrel + +import ( + "bytes" + "fmt" + "strings" +) + +// PlaceholderFormat is the interface that wraps the ReplacePlaceholders method. +// +// ReplacePlaceholders takes a SQL statement and replaces each question mark +// placeholder with a (possibly different) SQL placeholder. +type PlaceholderFormat interface { + ReplacePlaceholders(sql string) (string, error) +} + +type placeholderDebugger interface { + debugPlaceholder() string +} + +var ( + // Question is a PlaceholderFormat instance that leaves placeholders as + // question marks. + Question = questionFormat{} + + // Dollar is a PlaceholderFormat instance that replaces placeholders with + // dollar-prefixed positional placeholders (e.g. $1, $2, $3). + Dollar = dollarFormat{} + + // Colon is a PlaceholderFormat instance that replaces placeholders with + // colon-prefixed positional placeholders (e.g. :1, :2, :3). + Colon = colonFormat{} + + // AtP is a PlaceholderFormat instance that replaces placeholders with + // "@p"-prefixed positional placeholders (e.g. @p1, @p2, @p3). + AtP = atpFormat{} +) + +type questionFormat struct{} + +func (questionFormat) ReplacePlaceholders(sql string) (string, error) { + return sql, nil +} + +func (questionFormat) debugPlaceholder() string { + return "?" +} + +type dollarFormat struct{} + +func (dollarFormat) ReplacePlaceholders(sql string) (string, error) { + return replacePositionalPlaceholders(sql, "$") +} + +func (dollarFormat) debugPlaceholder() string { + return "$" +} + +type colonFormat struct{} + +func (colonFormat) ReplacePlaceholders(sql string) (string, error) { + return replacePositionalPlaceholders(sql, ":") +} + +func (colonFormat) debugPlaceholder() string { + return ":" +} + +type atpFormat struct{} + +func (atpFormat) ReplacePlaceholders(sql string) (string, error) { + return replacePositionalPlaceholders(sql, "@p") +} + +func (atpFormat) debugPlaceholder() string { + return "@p" +} + +// Placeholders returns a string with count ? placeholders joined with commas. +func Placeholders(count int) string { + if count < 1 { + return "" + } + + return strings.Repeat(",?", count)[1:] +} + +func replacePositionalPlaceholders(sql, prefix string) (string, error) { + buf := &bytes.Buffer{} + i := 0 + for { + p := strings.Index(sql, "?") + if p == -1 { + break + } + + if len(sql[p:]) > 1 && sql[p:p+2] == "??" { // escape ?? => ? + buf.WriteString(sql[:p]) + buf.WriteString("?") + if len(sql[p:]) == 1 { + break + } + sql = sql[p+2:] + } else { + i++ + buf.WriteString(sql[:p]) + fmt.Fprintf(buf, "%s%d", prefix, i) + sql = sql[p+1:] + } + } + + buf.WriteString(sql) + return buf.String(), nil +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/row.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/row.go new file mode 100644 index 0000000000000000000000000000000000000000..74ffda92bde903c1e54282dc59ad6ef5d52e5577 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/row.go @@ -0,0 +1,22 @@ +package squirrel + +// RowScanner is the interface that wraps the Scan method. +// +// Scan behaves like database/sql.Row.Scan. +type RowScanner interface { + Scan(...interface{}) error +} + +// Row wraps database/sql.Row to let squirrel return new errors on Scan. +type Row struct { + RowScanner + err error +} + +// Scan returns Row.err or calls RowScanner.Scan. +func (r *Row) Scan(dest ...interface{}) error { + if r.err != nil { + return r.err + } + return r.RowScanner.Scan(dest...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/select.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/select.go new file mode 100644 index 0000000000000000000000000000000000000000..d55ce4c74079ac0c4dfe3316d6134cb8c2e61262 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/select.go @@ -0,0 +1,403 @@ +package squirrel + +import ( + "bytes" + "database/sql" + "fmt" + "strings" + + "github.com/lann/builder" +) + +type selectData struct { + PlaceholderFormat PlaceholderFormat + RunWith BaseRunner + Prefixes []Sqlizer + Options []string + Columns []Sqlizer + From Sqlizer + Joins []Sqlizer + WhereParts []Sqlizer + GroupBys []string + HavingParts []Sqlizer + OrderByParts []Sqlizer + Limit string + Offset string + Suffixes []Sqlizer +} + +func (d *selectData) Exec() (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return ExecWith(d.RunWith, d) +} + +func (d *selectData) Query() (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return QueryWith(d.RunWith, d) +} + +func (d *selectData) QueryRow() RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRower) + if !ok { + return &Row{err: RunnerNotQueryRunner} + } + return QueryRowWith(queryRower, d) +} + +func (d *selectData) ToSql() (sqlStr string, args []interface{}, err error) { + sqlStr, args, err = d.toSqlRaw() + if err != nil { + return + } + + sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sqlStr) + return +} + +func (d *selectData) toSqlRaw() (sqlStr string, args []interface{}, err error) { + if len(d.Columns) == 0 { + err = fmt.Errorf("select statements must have at least one result column") + return + } + + sql := &bytes.Buffer{} + + if len(d.Prefixes) > 0 { + args, err = appendToSql(d.Prefixes, sql, " ", args) + if err != nil { + return + } + + sql.WriteString(" ") + } + + sql.WriteString("SELECT ") + + if len(d.Options) > 0 { + sql.WriteString(strings.Join(d.Options, " ")) + sql.WriteString(" ") + } + + if len(d.Columns) > 0 { + args, err = appendToSql(d.Columns, sql, ", ", args) + if err != nil { + return + } + } + + if d.From != nil { + sql.WriteString(" FROM ") + args, err = appendToSql([]Sqlizer{d.From}, sql, "", args) + if err != nil { + return + } + } + + if len(d.Joins) > 0 { + sql.WriteString(" ") + args, err = appendToSql(d.Joins, sql, " ", args) + if err != nil { + return + } + } + + if len(d.WhereParts) > 0 { + sql.WriteString(" WHERE ") + args, err = appendToSql(d.WhereParts, sql, " AND ", args) + if err != nil { + return + } + } + + if len(d.GroupBys) > 0 { + sql.WriteString(" GROUP BY ") + sql.WriteString(strings.Join(d.GroupBys, ", ")) + } + + if len(d.HavingParts) > 0 { + sql.WriteString(" HAVING ") + args, err = appendToSql(d.HavingParts, sql, " AND ", args) + if err != nil { + return + } + } + + if len(d.OrderByParts) > 0 { + sql.WriteString(" ORDER BY ") + args, err = appendToSql(d.OrderByParts, sql, ", ", args) + if err != nil { + return + } + } + + if len(d.Limit) > 0 { + sql.WriteString(" LIMIT ") + sql.WriteString(d.Limit) + } + + if len(d.Offset) > 0 { + sql.WriteString(" OFFSET ") + sql.WriteString(d.Offset) + } + + if len(d.Suffixes) > 0 { + sql.WriteString(" ") + + args, err = appendToSql(d.Suffixes, sql, " ", args) + if err != nil { + return + } + } + + sqlStr = sql.String() + return +} + +// Builder + +// SelectBuilder builds SQL SELECT statements. +type SelectBuilder builder.Builder + +func init() { + builder.Register(SelectBuilder{}, selectData{}) +} + +// Format methods + +// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the +// query. +func (b SelectBuilder) PlaceholderFormat(f PlaceholderFormat) SelectBuilder { + return builder.Set(b, "PlaceholderFormat", f).(SelectBuilder) +} + +// Runner methods + +// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec. +// For most cases runner will be a database connection. +// +// Internally we use this to mock out the database connection for testing. +func (b SelectBuilder) RunWith(runner BaseRunner) SelectBuilder { + return setRunWith(b, runner).(SelectBuilder) +} + +// Exec builds and Execs the query with the Runner set by RunWith. +func (b SelectBuilder) Exec() (sql.Result, error) { + data := builder.GetStruct(b).(selectData) + return data.Exec() +} + +// Query builds and Querys the query with the Runner set by RunWith. +func (b SelectBuilder) Query() (*sql.Rows, error) { + data := builder.GetStruct(b).(selectData) + return data.Query() +} + +// QueryRow builds and QueryRows the query with the Runner set by RunWith. +func (b SelectBuilder) QueryRow() RowScanner { + data := builder.GetStruct(b).(selectData) + return data.QueryRow() +} + +// Scan is a shortcut for QueryRow().Scan. +func (b SelectBuilder) Scan(dest ...interface{}) error { + return b.QueryRow().Scan(dest...) +} + +// SQL methods + +// ToSql builds the query into a SQL string and bound args. +func (b SelectBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(selectData) + return data.ToSql() +} + +func (b SelectBuilder) toSqlRaw() (string, []interface{}, error) { + data := builder.GetStruct(b).(selectData) + return data.toSqlRaw() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b SelectBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// Prefix adds an expression to the beginning of the query +func (b SelectBuilder) Prefix(sql string, args ...interface{}) SelectBuilder { + return b.PrefixExpr(Expr(sql, args...)) +} + +// PrefixExpr adds an expression to the very beginning of the query +func (b SelectBuilder) PrefixExpr(expr Sqlizer) SelectBuilder { + return builder.Append(b, "Prefixes", expr).(SelectBuilder) +} + +// Distinct adds a DISTINCT clause to the query. +func (b SelectBuilder) Distinct() SelectBuilder { + return b.Options("DISTINCT") +} + +// Options adds select option to the query +func (b SelectBuilder) Options(options ...string) SelectBuilder { + return builder.Extend(b, "Options", options).(SelectBuilder) +} + +// Columns adds result columns to the query. +func (b SelectBuilder) Columns(columns ...string) SelectBuilder { + parts := make([]interface{}, 0, len(columns)) + for _, str := range columns { + parts = append(parts, newPart(str)) + } + return builder.Extend(b, "Columns", parts).(SelectBuilder) +} + +// RemoveColumns remove all columns from query. +// Must add a new column with Column or Columns methods, otherwise +// return a error. +func (b SelectBuilder) RemoveColumns() SelectBuilder { + return builder.Delete(b, "Columns").(SelectBuilder) +} + +// Column adds a result column to the query. +// Unlike Columns, Column accepts args which will be bound to placeholders in +// the columns string, for example: +// Column("IF(col IN ("+squirrel.Placeholders(3)+"), 1, 0) as col", 1, 2, 3) +func (b SelectBuilder) Column(column interface{}, args ...interface{}) SelectBuilder { + return builder.Append(b, "Columns", newPart(column, args...)).(SelectBuilder) +} + +// From sets the FROM clause of the query. +func (b SelectBuilder) From(from string) SelectBuilder { + return builder.Set(b, "From", newPart(from)).(SelectBuilder) +} + +// FromSelect sets a subquery into the FROM clause of the query. +func (b SelectBuilder) FromSelect(from SelectBuilder, alias string) SelectBuilder { + // Prevent misnumbered parameters in nested selects (#183). + from = from.PlaceholderFormat(Question) + return builder.Set(b, "From", Alias(from, alias)).(SelectBuilder) +} + +// JoinClause adds a join clause to the query. +func (b SelectBuilder) JoinClause(pred interface{}, args ...interface{}) SelectBuilder { + return builder.Append(b, "Joins", newPart(pred, args...)).(SelectBuilder) +} + +// Join adds a JOIN clause to the query. +func (b SelectBuilder) Join(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("JOIN "+join, rest...) +} + +// LeftJoin adds a LEFT JOIN clause to the query. +func (b SelectBuilder) LeftJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("LEFT JOIN "+join, rest...) +} + +// RightJoin adds a RIGHT JOIN clause to the query. +func (b SelectBuilder) RightJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("RIGHT JOIN "+join, rest...) +} + +// InnerJoin adds a INNER JOIN clause to the query. +func (b SelectBuilder) InnerJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("INNER JOIN "+join, rest...) +} + +// CrossJoin adds a CROSS JOIN clause to the query. +func (b SelectBuilder) CrossJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("CROSS JOIN "+join, rest...) +} + +// Where adds an expression to the WHERE clause of the query. +// +// Expressions are ANDed together in the generated SQL. +// +// Where accepts several types for its pred argument: +// +// nil OR "" - ignored. +// +// string - SQL expression. +// If the expression has SQL placeholders then a set of arguments must be passed +// as well, one for each placeholder. +// +// map[string]interface{} OR Eq - map of SQL expressions to values. Each key is +// transformed into an expression like " = ?", with the corresponding value +// bound to the placeholder. If the value is nil, the expression will be " +// IS NULL". If the value is an array or slice, the expression will be " IN +// (?,?,...)", with one placeholder for each item in the value. These expressions +// are ANDed together. +// +// Where will panic if pred isn't any of the above types. +func (b SelectBuilder) Where(pred interface{}, args ...interface{}) SelectBuilder { + if pred == nil || pred == "" { + return b + } + return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(SelectBuilder) +} + +// GroupBy adds GROUP BY expressions to the query. +func (b SelectBuilder) GroupBy(groupBys ...string) SelectBuilder { + return builder.Extend(b, "GroupBys", groupBys).(SelectBuilder) +} + +// Having adds an expression to the HAVING clause of the query. +// +// See Where. +func (b SelectBuilder) Having(pred interface{}, rest ...interface{}) SelectBuilder { + return builder.Append(b, "HavingParts", newWherePart(pred, rest...)).(SelectBuilder) +} + +// OrderByClause adds ORDER BY clause to the query. +func (b SelectBuilder) OrderByClause(pred interface{}, args ...interface{}) SelectBuilder { + return builder.Append(b, "OrderByParts", newPart(pred, args...)).(SelectBuilder) +} + +// OrderBy adds ORDER BY expressions to the query. +func (b SelectBuilder) OrderBy(orderBys ...string) SelectBuilder { + for _, orderBy := range orderBys { + b = b.OrderByClause(orderBy) + } + + return b +} + +// Limit sets a LIMIT clause on the query. +func (b SelectBuilder) Limit(limit uint64) SelectBuilder { + return builder.Set(b, "Limit", fmt.Sprintf("%d", limit)).(SelectBuilder) +} + +// Limit ALL allows to access all records with limit +func (b SelectBuilder) RemoveLimit() SelectBuilder { + return builder.Delete(b, "Limit").(SelectBuilder) +} + +// Offset sets a OFFSET clause on the query. +func (b SelectBuilder) Offset(offset uint64) SelectBuilder { + return builder.Set(b, "Offset", fmt.Sprintf("%d", offset)).(SelectBuilder) +} + +// RemoveOffset removes OFFSET clause. +func (b SelectBuilder) RemoveOffset() SelectBuilder { + return builder.Delete(b, "Offset").(SelectBuilder) +} + +// Suffix adds an expression to the end of the query +func (b SelectBuilder) Suffix(sql string, args ...interface{}) SelectBuilder { + return b.SuffixExpr(Expr(sql, args...)) +} + +// SuffixExpr adds an expression to the end of the query +func (b SelectBuilder) SuffixExpr(expr Sqlizer) SelectBuilder { + return builder.Append(b, "Suffixes", expr).(SelectBuilder) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/select_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/select_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..4c42c13f478965d0dbe206ccf7fbb8e347d726b3 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/select_ctx.go @@ -0,0 +1,69 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + + "github.com/lann/builder" +) + +func (d *selectData) ExecContext(ctx context.Context) (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(ExecerContext) + if !ok { + return nil, NoContextSupport + } + return ExecContextWith(ctx, ctxRunner, d) +} + +func (d *selectData) QueryContext(ctx context.Context) (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(QueryerContext) + if !ok { + return nil, NoContextSupport + } + return QueryContextWith(ctx, ctxRunner, d) +} + +func (d *selectData) QueryRowContext(ctx context.Context) RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRowerContext) + if !ok { + if _, ok := d.RunWith.(QueryerContext); !ok { + return &Row{err: RunnerNotQueryRunner} + } + return &Row{err: NoContextSupport} + } + return QueryRowContextWith(ctx, queryRower, d) +} + +// ExecContext builds and ExecContexts the query with the Runner set by RunWith. +func (b SelectBuilder) ExecContext(ctx context.Context) (sql.Result, error) { + data := builder.GetStruct(b).(selectData) + return data.ExecContext(ctx) +} + +// QueryContext builds and QueryContexts the query with the Runner set by RunWith. +func (b SelectBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) { + data := builder.GetStruct(b).(selectData) + return data.QueryContext(ctx) +} + +// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith. +func (b SelectBuilder) QueryRowContext(ctx context.Context) RowScanner { + data := builder.GetStruct(b).(selectData) + return data.QueryRowContext(ctx) +} + +// ScanContext is a shortcut for QueryRowContext().Scan. +func (b SelectBuilder) ScanContext(ctx context.Context, dest ...interface{}) error { + return b.QueryRowContext(ctx).Scan(dest...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/squirrel.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/squirrel.go new file mode 100644 index 0000000000000000000000000000000000000000..46d456eb620c09b20161711440ffbef0d091fafd --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/squirrel.go @@ -0,0 +1,183 @@ +// Package squirrel provides a fluent SQL generator. +// +// See https://github.com/Masterminds/squirrel for examples. +package squirrel + +import ( + "bytes" + "database/sql" + "fmt" + "strings" + + "github.com/lann/builder" +) + +// Sqlizer is the interface that wraps the ToSql method. +// +// ToSql returns a SQL representation of the Sqlizer, along with a slice of args +// as passed to e.g. database/sql.Exec. It can also return an error. +type Sqlizer interface { + ToSql() (string, []interface{}, error) +} + +// rawSqlizer is expected to do what Sqlizer does, but without finalizing placeholders. +// This is useful for nested queries. +type rawSqlizer interface { + toSqlRaw() (string, []interface{}, error) +} + +// Execer is the interface that wraps the Exec method. +// +// Exec executes the given query as implemented by database/sql.Exec. +type Execer interface { + Exec(query string, args ...interface{}) (sql.Result, error) +} + +// Queryer is the interface that wraps the Query method. +// +// Query executes the given query as implemented by database/sql.Query. +type Queryer interface { + Query(query string, args ...interface{}) (*sql.Rows, error) +} + +// QueryRower is the interface that wraps the QueryRow method. +// +// QueryRow executes the given query as implemented by database/sql.QueryRow. +type QueryRower interface { + QueryRow(query string, args ...interface{}) RowScanner +} + +// BaseRunner groups the Execer and Queryer interfaces. +type BaseRunner interface { + Execer + Queryer +} + +// Runner groups the Execer, Queryer, and QueryRower interfaces. +type Runner interface { + Execer + Queryer + QueryRower +} + +// WrapStdSql wraps a type implementing the standard SQL interface with methods that +// squirrel expects. +func WrapStdSql(stdSql StdSql) Runner { + return &stdsqlRunner{stdSql} +} + +// StdSql encompasses the standard methods of the *sql.DB type, and other types that +// wrap these methods. +type StdSql interface { + Query(string, ...interface{}) (*sql.Rows, error) + QueryRow(string, ...interface{}) *sql.Row + Exec(string, ...interface{}) (sql.Result, error) +} + +type stdsqlRunner struct { + StdSql +} + +func (r *stdsqlRunner) QueryRow(query string, args ...interface{}) RowScanner { + return r.StdSql.QueryRow(query, args...) +} + +func setRunWith(b interface{}, runner BaseRunner) interface{} { + switch r := runner.(type) { + case StdSqlCtx: + runner = WrapStdSqlCtx(r) + case StdSql: + runner = WrapStdSql(r) + } + return builder.Set(b, "RunWith", runner) +} + +// RunnerNotSet is returned by methods that need a Runner if it isn't set. +var RunnerNotSet = fmt.Errorf("cannot run; no Runner set (RunWith)") + +// RunnerNotQueryRunner is returned by QueryRow if the RunWith value doesn't implement QueryRower. +var RunnerNotQueryRunner = fmt.Errorf("cannot QueryRow; Runner is not a QueryRower") + +// ExecWith Execs the SQL returned by s with db. +func ExecWith(db Execer, s Sqlizer) (res sql.Result, err error) { + query, args, err := s.ToSql() + if err != nil { + return + } + return db.Exec(query, args...) +} + +// QueryWith Querys the SQL returned by s with db. +func QueryWith(db Queryer, s Sqlizer) (rows *sql.Rows, err error) { + query, args, err := s.ToSql() + if err != nil { + return + } + return db.Query(query, args...) +} + +// QueryRowWith QueryRows the SQL returned by s with db. +func QueryRowWith(db QueryRower, s Sqlizer) RowScanner { + query, args, err := s.ToSql() + return &Row{RowScanner: db.QueryRow(query, args...), err: err} +} + +// DebugSqlizer calls ToSql on s and shows the approximate SQL to be executed +// +// If ToSql returns an error, the result of this method will look like: +// "[ToSql error: %s]" or "[DebugSqlizer error: %s]" +// +// IMPORTANT: As its name suggests, this function should only be used for +// debugging. While the string result *might* be valid SQL, this function does +// not try very hard to ensure it. Additionally, executing the output of this +// function with any untrusted user input is certainly insecure. +func DebugSqlizer(s Sqlizer) string { + sql, args, err := s.ToSql() + if err != nil { + return fmt.Sprintf("[ToSql error: %s]", err) + } + + var placeholder string + downCast, ok := s.(placeholderDebugger) + if !ok { + placeholder = "?" + } else { + placeholder = downCast.debugPlaceholder() + } + // TODO: dedupe this with placeholder.go + buf := &bytes.Buffer{} + i := 0 + for { + p := strings.Index(sql, placeholder) + if p == -1 { + break + } + if len(sql[p:]) > 1 && sql[p:p+2] == "??" { // escape ?? => ? + buf.WriteString(sql[:p]) + buf.WriteString("?") + if len(sql[p:]) == 1 { + break + } + sql = sql[p+2:] + } else { + if i+1 > len(args) { + return fmt.Sprintf( + "[DebugSqlizer error: too many placeholders in %#v for %d args]", + sql, len(args)) + } + buf.WriteString(sql[:p]) + fmt.Fprintf(buf, "'%v'", args[i]) + // advance our sql string "cursor" beyond the arg we placed + sql = sql[p+1:] + i++ + } + } + if i < len(args) { + return fmt.Sprintf( + "[DebugSqlizer error: not enough placeholders in %#v for %d args]", + sql, len(args)) + } + // "append" any remaning sql that won't need interpolating + buf.WriteString(sql) + return buf.String() +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/squirrel_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/squirrel_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..c20148ad33c76cf86b64f4f0dd88f8a9f1c96dd7 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/squirrel_ctx.go @@ -0,0 +1,93 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + "errors" +) + +// NoContextSupport is returned if a db doesn't support Context. +var NoContextSupport = errors.New("DB does not support Context") + +// ExecerContext is the interface that wraps the ExecContext method. +// +// Exec executes the given query as implemented by database/sql.ExecContext. +type ExecerContext interface { + ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) +} + +// QueryerContext is the interface that wraps the QueryContext method. +// +// QueryContext executes the given query as implemented by database/sql.QueryContext. +type QueryerContext interface { + QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) +} + +// QueryRowerContext is the interface that wraps the QueryRowContext method. +// +// QueryRowContext executes the given query as implemented by database/sql.QueryRowContext. +type QueryRowerContext interface { + QueryRowContext(ctx context.Context, query string, args ...interface{}) RowScanner +} + +// RunnerContext groups the Runner interface, along with the Context versions of each of +// its methods +type RunnerContext interface { + Runner + QueryerContext + QueryRowerContext + ExecerContext +} + +// WrapStdSqlCtx wraps a type implementing the standard SQL interface plus the context +// versions of the methods with methods that squirrel expects. +func WrapStdSqlCtx(stdSqlCtx StdSqlCtx) RunnerContext { + return &stdsqlCtxRunner{stdSqlCtx} +} + +// StdSqlCtx encompasses the standard methods of the *sql.DB type, along with the Context +// versions of those methods, and other types that wrap these methods. +type StdSqlCtx interface { + StdSql + QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error) + QueryRowContext(context.Context, string, ...interface{}) *sql.Row + ExecContext(context.Context, string, ...interface{}) (sql.Result, error) +} + +type stdsqlCtxRunner struct { + StdSqlCtx +} + +func (r *stdsqlCtxRunner) QueryRow(query string, args ...interface{}) RowScanner { + return r.StdSqlCtx.QueryRow(query, args...) +} + +func (r *stdsqlCtxRunner) QueryRowContext(ctx context.Context, query string, args ...interface{}) RowScanner { + return r.StdSqlCtx.QueryRowContext(ctx, query, args...) +} + +// ExecContextWith ExecContexts the SQL returned by s with db. +func ExecContextWith(ctx context.Context, db ExecerContext, s Sqlizer) (res sql.Result, err error) { + query, args, err := s.ToSql() + if err != nil { + return + } + return db.ExecContext(ctx, query, args...) +} + +// QueryContextWith QueryContexts the SQL returned by s with db. +func QueryContextWith(ctx context.Context, db QueryerContext, s Sqlizer) (rows *sql.Rows, err error) { + query, args, err := s.ToSql() + if err != nil { + return + } + return db.QueryContext(ctx, query, args...) +} + +// QueryRowContextWith QueryRowContexts the SQL returned by s with db. +func QueryRowContextWith(ctx context.Context, db QueryRowerContext, s Sqlizer) RowScanner { + query, args, err := s.ToSql() + return &Row{RowScanner: db.QueryRowContext(ctx, query, args...), err: err} +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/statement.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/statement.go new file mode 100644 index 0000000000000000000000000000000000000000..9420c67f8e921e04876efea27bec4a5c5cd4921d --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/statement.go @@ -0,0 +1,104 @@ +package squirrel + +import "github.com/lann/builder" + +// StatementBuilderType is the type of StatementBuilder. +type StatementBuilderType builder.Builder + +// Select returns a SelectBuilder for this StatementBuilderType. +func (b StatementBuilderType) Select(columns ...string) SelectBuilder { + return SelectBuilder(b).Columns(columns...) +} + +// Insert returns a InsertBuilder for this StatementBuilderType. +func (b StatementBuilderType) Insert(into string) InsertBuilder { + return InsertBuilder(b).Into(into) +} + +// Replace returns a InsertBuilder for this StatementBuilderType with the +// statement keyword set to "REPLACE". +func (b StatementBuilderType) Replace(into string) InsertBuilder { + return InsertBuilder(b).statementKeyword("REPLACE").Into(into) +} + +// Update returns a UpdateBuilder for this StatementBuilderType. +func (b StatementBuilderType) Update(table string) UpdateBuilder { + return UpdateBuilder(b).Table(table) +} + +// Delete returns a DeleteBuilder for this StatementBuilderType. +func (b StatementBuilderType) Delete(from string) DeleteBuilder { + return DeleteBuilder(b).From(from) +} + +// PlaceholderFormat sets the PlaceholderFormat field for any child builders. +func (b StatementBuilderType) PlaceholderFormat(f PlaceholderFormat) StatementBuilderType { + return builder.Set(b, "PlaceholderFormat", f).(StatementBuilderType) +} + +// RunWith sets the RunWith field for any child builders. +func (b StatementBuilderType) RunWith(runner BaseRunner) StatementBuilderType { + return setRunWith(b, runner).(StatementBuilderType) +} + +// Where adds WHERE expressions to the query. +// +// See SelectBuilder.Where for more information. +func (b StatementBuilderType) Where(pred interface{}, args ...interface{}) StatementBuilderType { + return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(StatementBuilderType) +} + +// StatementBuilder is a parent builder for other builders, e.g. SelectBuilder. +var StatementBuilder = StatementBuilderType(builder.EmptyBuilder).PlaceholderFormat(Question) + +// Select returns a new SelectBuilder, optionally setting some result columns. +// +// See SelectBuilder.Columns. +func Select(columns ...string) SelectBuilder { + return StatementBuilder.Select(columns...) +} + +// Insert returns a new InsertBuilder with the given table name. +// +// See InsertBuilder.Into. +func Insert(into string) InsertBuilder { + return StatementBuilder.Insert(into) +} + +// Replace returns a new InsertBuilder with the statement keyword set to +// "REPLACE" and with the given table name. +// +// See InsertBuilder.Into. +func Replace(into string) InsertBuilder { + return StatementBuilder.Replace(into) +} + +// Update returns a new UpdateBuilder with the given table name. +// +// See UpdateBuilder.Table. +func Update(table string) UpdateBuilder { + return StatementBuilder.Update(table) +} + +// Delete returns a new DeleteBuilder with the given table name. +// +// See DeleteBuilder.Table. +func Delete(from string) DeleteBuilder { + return StatementBuilder.Delete(from) +} + +// Case returns a new CaseBuilder +// "what" represents case value +func Case(what ...interface{}) CaseBuilder { + b := CaseBuilder(builder.EmptyBuilder) + + switch len(what) { + case 0: + case 1: + b = b.what(what[0]) + default: + b = b.what(newPart(what[0], what[1:]...)) + + } + return b +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/stmtcacher.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/stmtcacher.go new file mode 100644 index 0000000000000000000000000000000000000000..5bf267a13642d0c6734cf013a6e631f6ca1f0bc6 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/stmtcacher.go @@ -0,0 +1,121 @@ +package squirrel + +import ( + "database/sql" + "fmt" + "sync" +) + +// Prepareer is the interface that wraps the Prepare method. +// +// Prepare executes the given query as implemented by database/sql.Prepare. +type Preparer interface { + Prepare(query string) (*sql.Stmt, error) +} + +// DBProxy groups the Execer, Queryer, QueryRower, and Preparer interfaces. +type DBProxy interface { + Execer + Queryer + QueryRower + Preparer +} + +// NOTE: NewStmtCache is defined in stmtcacher_ctx.go (Go >= 1.8) or stmtcacher_noctx.go (Go < 1.8). + +// StmtCache wraps and delegates down to a Preparer type +// +// It also automatically prepares all statements sent to the underlying Preparer calls +// for Exec, Query and QueryRow and caches the returns *sql.Stmt using the provided +// query as the key. So that it can be automatically re-used. +type StmtCache struct { + prep Preparer + cache map[string]*sql.Stmt + mu sync.Mutex +} + +// Prepare delegates down to the underlying Preparer and caches the result +// using the provided query as a key +func (sc *StmtCache) Prepare(query string) (*sql.Stmt, error) { + sc.mu.Lock() + defer sc.mu.Unlock() + + stmt, ok := sc.cache[query] + if ok { + return stmt, nil + } + stmt, err := sc.prep.Prepare(query) + if err == nil { + sc.cache[query] = stmt + } + return stmt, err +} + +// Exec delegates down to the underlying Preparer using a prepared statement +func (sc *StmtCache) Exec(query string, args ...interface{}) (res sql.Result, err error) { + stmt, err := sc.Prepare(query) + if err != nil { + return + } + return stmt.Exec(args...) +} + +// Query delegates down to the underlying Preparer using a prepared statement +func (sc *StmtCache) Query(query string, args ...interface{}) (rows *sql.Rows, err error) { + stmt, err := sc.Prepare(query) + if err != nil { + return + } + return stmt.Query(args...) +} + +// QueryRow delegates down to the underlying Preparer using a prepared statement +func (sc *StmtCache) QueryRow(query string, args ...interface{}) RowScanner { + stmt, err := sc.Prepare(query) + if err != nil { + return &Row{err: err} + } + return stmt.QueryRow(args...) +} + +// Clear removes and closes all the currently cached prepared statements +func (sc *StmtCache) Clear() (err error) { + sc.mu.Lock() + defer sc.mu.Unlock() + + for key, stmt := range sc.cache { + delete(sc.cache, key) + + if stmt == nil { + continue + } + + if cerr := stmt.Close(); cerr != nil { + err = cerr + } + } + + if err != nil { + return fmt.Errorf("one or more Stmt.Close failed; last error: %v", err) + } + + return +} + +type DBProxyBeginner interface { + DBProxy + Begin() (*sql.Tx, error) +} + +type stmtCacheProxy struct { + DBProxy + db *sql.DB +} + +func NewStmtCacheProxy(db *sql.DB) DBProxyBeginner { + return &stmtCacheProxy{DBProxy: NewStmtCache(db), db: db} +} + +func (sp *stmtCacheProxy) Begin() (*sql.Tx, error) { + return sp.db.Begin() +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/stmtcacher_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/stmtcacher_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..53603cf4c9548775644cbf2050a0d1f3c5150b73 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/stmtcacher_ctx.go @@ -0,0 +1,86 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" +) + +// PrepareerContext is the interface that wraps the Prepare and PrepareContext methods. +// +// Prepare executes the given query as implemented by database/sql.Prepare. +// PrepareContext executes the given query as implemented by database/sql.PrepareContext. +type PreparerContext interface { + Preparer + PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) +} + +// DBProxyContext groups the Execer, Queryer, QueryRower and PreparerContext interfaces. +type DBProxyContext interface { + Execer + Queryer + QueryRower + PreparerContext +} + +// NewStmtCache returns a *StmtCache wrapping a PreparerContext that caches Prepared Stmts. +// +// Stmts are cached based on the string value of their queries. +func NewStmtCache(prep PreparerContext) *StmtCache { + return &StmtCache{prep: prep, cache: make(map[string]*sql.Stmt)} +} + +// NewStmtCacher is deprecated +// +// Use NewStmtCache instead +func NewStmtCacher(prep PreparerContext) DBProxyContext { + return NewStmtCache(prep) +} + +// PrepareContext delegates down to the underlying PreparerContext and caches the result +// using the provided query as a key +func (sc *StmtCache) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) { + ctxPrep, ok := sc.prep.(PreparerContext) + if !ok { + return nil, NoContextSupport + } + sc.mu.Lock() + defer sc.mu.Unlock() + stmt, ok := sc.cache[query] + if ok { + return stmt, nil + } + stmt, err := ctxPrep.PrepareContext(ctx, query) + if err == nil { + sc.cache[query] = stmt + } + return stmt, err +} + +// ExecContext delegates down to the underlying PreparerContext using a prepared statement +func (sc *StmtCache) ExecContext(ctx context.Context, query string, args ...interface{}) (res sql.Result, err error) { + stmt, err := sc.PrepareContext(ctx, query) + if err != nil { + return + } + return stmt.ExecContext(ctx, args...) +} + +// QueryContext delegates down to the underlying PreparerContext using a prepared statement +func (sc *StmtCache) QueryContext(ctx context.Context, query string, args ...interface{}) (rows *sql.Rows, err error) { + stmt, err := sc.PrepareContext(ctx, query) + if err != nil { + return + } + return stmt.QueryContext(ctx, args...) +} + +// QueryRowContext delegates down to the underlying PreparerContext using a prepared statement +func (sc *StmtCache) QueryRowContext(ctx context.Context, query string, args ...interface{}) RowScanner { + stmt, err := sc.PrepareContext(ctx, query) + if err != nil { + return &Row{err: err} + } + return stmt.QueryRowContext(ctx, args...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/stmtcacher_noctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/stmtcacher_noctx.go new file mode 100644 index 0000000000000000000000000000000000000000..deac96777b7fd51ea468b9861b76571b1aa433bf --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/stmtcacher_noctx.go @@ -0,0 +1,21 @@ +// +build !go1.8 + +package squirrel + +import ( + "database/sql" +) + +// NewStmtCacher returns a DBProxy wrapping prep that caches Prepared Stmts. +// +// Stmts are cached based on the string value of their queries. +func NewStmtCache(prep Preparer) *StmtCache { + return &StmtCacher{prep: prep, cache: make(map[string]*sql.Stmt)} +} + +// NewStmtCacher is deprecated +// +// Use NewStmtCache instead +func NewStmtCacher(prep Preparer) DBProxy { + return NewStmtCache(prep) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/update.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/update.go new file mode 100644 index 0000000000000000000000000000000000000000..0e76dadb9fa4d7a79be30a2fa5ad7726216e8cb7 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/update.go @@ -0,0 +1,288 @@ +package squirrel + +import ( + "bytes" + "database/sql" + "fmt" + "sort" + "strings" + + "github.com/lann/builder" +) + +type updateData struct { + PlaceholderFormat PlaceholderFormat + RunWith BaseRunner + Prefixes []Sqlizer + Table string + SetClauses []setClause + From Sqlizer + WhereParts []Sqlizer + OrderBys []string + Limit string + Offset string + Suffixes []Sqlizer +} + +type setClause struct { + column string + value interface{} +} + +func (d *updateData) Exec() (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return ExecWith(d.RunWith, d) +} + +func (d *updateData) Query() (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return QueryWith(d.RunWith, d) +} + +func (d *updateData) QueryRow() RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRower) + if !ok { + return &Row{err: RunnerNotQueryRunner} + } + return QueryRowWith(queryRower, d) +} + +func (d *updateData) ToSql() (sqlStr string, args []interface{}, err error) { + if len(d.Table) == 0 { + err = fmt.Errorf("update statements must specify a table") + return + } + if len(d.SetClauses) == 0 { + err = fmt.Errorf("update statements must have at least one Set clause") + return + } + + sql := &bytes.Buffer{} + + if len(d.Prefixes) > 0 { + args, err = appendToSql(d.Prefixes, sql, " ", args) + if err != nil { + return + } + + sql.WriteString(" ") + } + + sql.WriteString("UPDATE ") + sql.WriteString(d.Table) + + sql.WriteString(" SET ") + setSqls := make([]string, len(d.SetClauses)) + for i, setClause := range d.SetClauses { + var valSql string + if vs, ok := setClause.value.(Sqlizer); ok { + vsql, vargs, err := vs.ToSql() + if err != nil { + return "", nil, err + } + if _, ok := vs.(SelectBuilder); ok { + valSql = fmt.Sprintf("(%s)", vsql) + } else { + valSql = vsql + } + args = append(args, vargs...) + } else { + valSql = "?" + args = append(args, setClause.value) + } + setSqls[i] = fmt.Sprintf("%s = %s", setClause.column, valSql) + } + sql.WriteString(strings.Join(setSqls, ", ")) + + if d.From != nil { + sql.WriteString(" FROM ") + args, err = appendToSql([]Sqlizer{d.From}, sql, "", args) + if err != nil { + return + } + } + + if len(d.WhereParts) > 0 { + sql.WriteString(" WHERE ") + args, err = appendToSql(d.WhereParts, sql, " AND ", args) + if err != nil { + return + } + } + + if len(d.OrderBys) > 0 { + sql.WriteString(" ORDER BY ") + sql.WriteString(strings.Join(d.OrderBys, ", ")) + } + + if len(d.Limit) > 0 { + sql.WriteString(" LIMIT ") + sql.WriteString(d.Limit) + } + + if len(d.Offset) > 0 { + sql.WriteString(" OFFSET ") + sql.WriteString(d.Offset) + } + + if len(d.Suffixes) > 0 { + sql.WriteString(" ") + args, err = appendToSql(d.Suffixes, sql, " ", args) + if err != nil { + return + } + } + + sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sql.String()) + return +} + +// Builder + +// UpdateBuilder builds SQL UPDATE statements. +type UpdateBuilder builder.Builder + +func init() { + builder.Register(UpdateBuilder{}, updateData{}) +} + +// Format methods + +// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the +// query. +func (b UpdateBuilder) PlaceholderFormat(f PlaceholderFormat) UpdateBuilder { + return builder.Set(b, "PlaceholderFormat", f).(UpdateBuilder) +} + +// Runner methods + +// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec. +func (b UpdateBuilder) RunWith(runner BaseRunner) UpdateBuilder { + return setRunWith(b, runner).(UpdateBuilder) +} + +// Exec builds and Execs the query with the Runner set by RunWith. +func (b UpdateBuilder) Exec() (sql.Result, error) { + data := builder.GetStruct(b).(updateData) + return data.Exec() +} + +func (b UpdateBuilder) Query() (*sql.Rows, error) { + data := builder.GetStruct(b).(updateData) + return data.Query() +} + +func (b UpdateBuilder) QueryRow() RowScanner { + data := builder.GetStruct(b).(updateData) + return data.QueryRow() +} + +func (b UpdateBuilder) Scan(dest ...interface{}) error { + return b.QueryRow().Scan(dest...) +} + +// SQL methods + +// ToSql builds the query into a SQL string and bound args. +func (b UpdateBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(updateData) + return data.ToSql() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b UpdateBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err == nil { + panic(err) + } + return sql, args +} + +// Prefix adds an expression to the beginning of the query +func (b UpdateBuilder) Prefix(sql string, args ...interface{}) UpdateBuilder { + return b.PrefixExpr(Expr(sql, args...)) +} + +// PrefixExpr adds an expression to the very beginning of the query +func (b UpdateBuilder) PrefixExpr(expr Sqlizer) UpdateBuilder { + return builder.Append(b, "Prefixes", expr).(UpdateBuilder) +} + +// Table sets the table to be updated. +func (b UpdateBuilder) Table(table string) UpdateBuilder { + return builder.Set(b, "Table", table).(UpdateBuilder) +} + +// Set adds SET clauses to the query. +func (b UpdateBuilder) Set(column string, value interface{}) UpdateBuilder { + return builder.Append(b, "SetClauses", setClause{column: column, value: value}).(UpdateBuilder) +} + +// SetMap is a convenience method which calls .Set for each key/value pair in clauses. +func (b UpdateBuilder) SetMap(clauses map[string]interface{}) UpdateBuilder { + keys := make([]string, len(clauses)) + i := 0 + for key := range clauses { + keys[i] = key + i++ + } + sort.Strings(keys) + for _, key := range keys { + val, _ := clauses[key] + b = b.Set(key, val) + } + return b +} + +// From adds FROM clause to the query +// FROM is valid construct in postgresql only. +func (b UpdateBuilder) From(from string) UpdateBuilder { + return builder.Set(b, "From", newPart(from)).(UpdateBuilder) +} + +// FromSelect sets a subquery into the FROM clause of the query. +func (b UpdateBuilder) FromSelect(from SelectBuilder, alias string) UpdateBuilder { + // Prevent misnumbered parameters in nested selects (#183). + from = from.PlaceholderFormat(Question) + return builder.Set(b, "From", Alias(from, alias)).(UpdateBuilder) +} + +// Where adds WHERE expressions to the query. +// +// See SelectBuilder.Where for more information. +func (b UpdateBuilder) Where(pred interface{}, args ...interface{}) UpdateBuilder { + return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(UpdateBuilder) +} + +// OrderBy adds ORDER BY expressions to the query. +func (b UpdateBuilder) OrderBy(orderBys ...string) UpdateBuilder { + return builder.Extend(b, "OrderBys", orderBys).(UpdateBuilder) +} + +// Limit sets a LIMIT clause on the query. +func (b UpdateBuilder) Limit(limit uint64) UpdateBuilder { + return builder.Set(b, "Limit", fmt.Sprintf("%d", limit)).(UpdateBuilder) +} + +// Offset sets a OFFSET clause on the query. +func (b UpdateBuilder) Offset(offset uint64) UpdateBuilder { + return builder.Set(b, "Offset", fmt.Sprintf("%d", offset)).(UpdateBuilder) +} + +// Suffix adds an expression to the end of the query +func (b UpdateBuilder) Suffix(sql string, args ...interface{}) UpdateBuilder { + return b.SuffixExpr(Expr(sql, args...)) +} + +// SuffixExpr adds an expression to the end of the query +func (b UpdateBuilder) SuffixExpr(expr Sqlizer) UpdateBuilder { + return builder.Append(b, "Suffixes", expr).(UpdateBuilder) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/update_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/update_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..ad479f96f49fd0f02da2f3ea44f0392f451ec5d5 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/update_ctx.go @@ -0,0 +1,69 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + + "github.com/lann/builder" +) + +func (d *updateData) ExecContext(ctx context.Context) (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(ExecerContext) + if !ok { + return nil, NoContextSupport + } + return ExecContextWith(ctx, ctxRunner, d) +} + +func (d *updateData) QueryContext(ctx context.Context) (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(QueryerContext) + if !ok { + return nil, NoContextSupport + } + return QueryContextWith(ctx, ctxRunner, d) +} + +func (d *updateData) QueryRowContext(ctx context.Context) RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRowerContext) + if !ok { + if _, ok := d.RunWith.(QueryerContext); !ok { + return &Row{err: RunnerNotQueryRunner} + } + return &Row{err: NoContextSupport} + } + return QueryRowContextWith(ctx, queryRower, d) +} + +// ExecContext builds and ExecContexts the query with the Runner set by RunWith. +func (b UpdateBuilder) ExecContext(ctx context.Context) (sql.Result, error) { + data := builder.GetStruct(b).(updateData) + return data.ExecContext(ctx) +} + +// QueryContext builds and QueryContexts the query with the Runner set by RunWith. +func (b UpdateBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) { + data := builder.GetStruct(b).(updateData) + return data.QueryContext(ctx) +} + +// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith. +func (b UpdateBuilder) QueryRowContext(ctx context.Context) RowScanner { + data := builder.GetStruct(b).(updateData) + return data.QueryRowContext(ctx) +} + +// ScanContext is a shortcut for QueryRowContext().Scan. +func (b UpdateBuilder) ScanContext(ctx context.Context, dest ...interface{}) error { + return b.QueryRowContext(ctx).Scan(dest...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/where.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/where.go new file mode 100644 index 0000000000000000000000000000000000000000..976b63ace4ecb4452f5326b1893067bb604d133e --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/environment/source/where.go @@ -0,0 +1,30 @@ +package squirrel + +import ( + "fmt" +) + +type wherePart part + +func newWherePart(pred interface{}, args ...interface{}) Sqlizer { + return &wherePart{pred: pred, args: args} +} + +func (p wherePart) ToSql() (sql string, args []interface{}, err error) { + switch pred := p.pred.(type) { + case nil: + // no-op + case rawSqlizer: + return pred.toSqlRaw() + case Sqlizer: + return pred.ToSql() + case map[string]interface{}: + return Eq(pred).ToSql() + case string: + sql = pred + args = p.args + default: + err = fmt.Errorf("expected string-keyed map or string, not %T", pred) + } + return +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/instruction.md b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..77024bca3d34a040afefa64a4e4e5f5fd503096b --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/instruction.md @@ -0,0 +1,26 @@ +UpdateBuilder.MustSql() doesn't panic on valid SQL + +#### Description + +The `UpdateBuilder.MustSql()` method is supposed to panic when there's an error generating SQL, but it's currently panicking when the SQL generation is successful instead. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "github.com/Masterminds/squirrel" +) + +func main() { + update := squirrel.Update("users").Set("name", "John").Where(squirrel.Eq{"id": 1}) + + // This should work without panicking, but currently panics + sql, args := update.MustSql() + println(sql, args) +} +``` + +The `MustSql()` method should only panic when `ToSql()` returns an error, but currently it's doing the opposite - panicking when there's no error. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/provenance.json b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..4de6cde933dd79bf88fa3735a76162db621345b4 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/provenance.json @@ -0,0 +1,385 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt", + "original-bug": "task-specific unchanged semantic bug", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only", + "extra_semantic_repair_coverage": false, + "original_patch_hunks": 1 + }, + "private_frozen_files": { + "case_test.go": { + "mode": "0o644", + "sha256": "fdb8c60761dc1ab02953e86f1736bd29e644e61bb7f67a394a5f71d276a67298", + "size": 3296 + }, + "delete_ctx_test.go": { + "mode": "0o644", + "sha256": "07e5cd531fbc380655a6f441eeee23da925195d67a1a7e7682785806af51014e", + "size": 847 + }, + "delete_test.go": { + "mode": "0o644", + "sha256": "44ac247a59eb89cd5f41e3f0948a78e51e757d0888a72874d12a12c6db1acfb0", + "size": 1806 + }, + "expr_test.go": { + "mode": "0o644", + "sha256": "ab52b68e40a81bda968dacc733f34c08626f299405450c383daf438e33897a65", + "size": 10245 + }, + "insert_ctx_test.go": { + "mode": "0o644", + "sha256": "b3e3efaf75fee82c147958afb70a90334f4f08cf29b64bd76d23a03b9824f299", + "size": 807 + }, + "insert_test.go": { + "mode": "0o644", + "sha256": "665fe6694c9ce48b2bcbdfd34ab9bde67d8fd7601b3d5798f4dacd693e1da278", + "size": 2627 + }, + "integration/integration_test.go": { + "mode": "0o644", + "sha256": "c8631b72fa30417861d7ba87a1a9a5c0883d01744fb49bf779360dc4a61b9abf", + "size": 3162 + }, + "placeholder_test.go": { + "mode": "0o644", + "sha256": "c498900e8f98d981e90863f0603d19c11db17e786eae008bdc5af2b25ae8eb13", + "size": 2005 + }, + "row_test.go": { + "mode": "0o644", + "sha256": "7fe834ce33424df8e009fa44ee5acea25508c7e439d1bf07fddf6d4c90e77ec1", + "size": 626 + }, + "select_ctx_test.go": { + "mode": "0o644", + "sha256": "560d37ac028fbf92ba5c5a20b95af7d866a4fbdecd0e868b6fe266eb4849e665", + "size": 771 + }, + "select_test.go": { + "mode": "0o644", + "sha256": "3b06e89b5c358992a7165414dbeb4643820d95574981359638d609931d528630", + "size": 12209 + }, + "squirrel_ctx_test.go": { + "mode": "0o644", + "sha256": "4a052ae48d428a0719777189c407e5d5c7087550c0d99b2c28cceada083f76b0", + "size": 1277 + }, + "squirrel_test.go": { + "mode": "0o644", + "sha256": "7336a2ffda333c52c145d76e926a89e1244ff24b96c86abfc6fe06723572180f", + "size": 5780 + }, + "statement_test.go": { + "mode": "0o644", + "sha256": "a0f46fa71157b09eaca3da0fa6a75b25156cb552c785228836b0ffbb9fe5ac27", + "size": 2072 + }, + "stmtcacher_ctx_test.go": { + "mode": "0o644", + "sha256": "a0a1f49a87ebb6b35b8d66fbe9051d8a9f94346eaf5e3cd70719424433f5c878", + "size": 402 + }, + "stmtcacher_test.go": { + "mode": "0o644", + "sha256": "e5b5020ac3c194cf92121100a24df580955f32f89bd600b1e56014702d24eb52", + "size": 546 + }, + "update_ctx_test.go": { + "mode": "0o644", + "sha256": "3dd7bd0c17bfb61fad6e71c7736ca6a207f811ae7c3f92f8185c5f7d32dbf30a", + "size": 805 + }, + "update_test.go": { + "mode": "0o644", + "sha256": "6316c8d144c647d9c7bdd6b8be4490c40398da03d331be23c4729faa7a57aa4e", + "size": 2836 + }, + "where_test.go": { + "mode": "0o644", + "sha256": "1a53006a294c379a8b7f212b340acf9063ea0b613062a52fc9585a7d84f853f3", + "size": 1325 + } + }, + "public_files": { + ".gitignore": { + "mode": "0o644", + "sha256": "1eaa1ee4d30ac564ac002a67650eff426807e1fd8b9475250d0ef31ee3d458dd", + "size": 13 + }, + ".travis.yml": { + "mode": "0o644", + "sha256": "5409f254b7fc2f4ed3afcdc45ac2346acedadf2689e14f5d4735e5587cd31a15", + "size": 768 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "11ac92da622d8d25df663d4bc5d12f464da1a98a9fbb75930e0e65cc58b80a2f", + "size": 1185 + }, + "README.md": { + "mode": "0o644", + "sha256": "f1dafb8f66d5eb204201e34fbcf50a08180b7cc6fffb9cd87ed55673d840afc2", + "size": 4363 + }, + "case.go": { + "mode": "0o644", + "sha256": "9c530c0585dcf3c1f12200afecbc2147edbdc18a2369f726486ebc169bfdb1f1", + "size": 3065 + }, + "delete.go": { + "mode": "0o644", + "sha256": "700cefe533a6d939aaa689dfcbf148ad8d4b07f0278337944ecc37767479b3eb", + "size": 4806 + }, + "delete_ctx.go": { + "mode": "0o644", + "sha256": "0fb7da25c0bee63500317da43e1d8bcb5b8d62487ec80e6298135953d62b03f4", + "size": 1908 + }, + "expr.go": { + "mode": "0o644", + "sha256": "246aa910b8adc931da8773bf9a782d8e8292c5315fd267d3aca2d75792842d8e", + "size": 9216 + }, + "go.mod": { + "mode": "0o644", + "sha256": "b4c6f216eafab7a1ca5209b5ddca006529666f72184aea72293395c69f7140f5", + "size": 321 + }, + "go.sum": { + "mode": "0o644", + "sha256": "2b4fe7850b36f8effe69d037ed1219df62399e4076034930b8f3d2edb7fa46fd", + "size": 953 + }, + "insert.go": { + "mode": "0o644", + "sha256": "626ac9dd6c5cbca5e9e3b93252d82c94d6d6b63ddc967fb0dbcee0f3dc889c2e", + "size": 7710 + }, + "insert_ctx.go": { + "mode": "0o644", + "sha256": "6f72f9fd2e5e3b9e60f65f1fcf920ba6724242784ba26b9e0924aa8a0667d8b2", + "size": 1908 + }, + "integration/doc.go": { + "mode": "0o644", + "sha256": "2eb5edda1be28404e1f6681d1177cd3f447f8167cacf51f817b853e578e5996c", + "size": 53 + }, + "integration/go.mod": { + "mode": "0o644", + "sha256": "b8f745640b55a496faf7e8ffe39dcbb223bd4a856c108f38cb5021c5c9fafc3b", + "size": 347 + }, + "integration/go.sum": { + "mode": "0o644", + "sha256": "30892c107aa863abb8105816d7f6fa497ec69fd1d6783f4f186a19ff0fe6df80", + "size": 3122 + }, + "part.go": { + "mode": "0o644", + "sha256": "5fb7ec420cb4f4eff065b0a71e073b8ac74a1a6a81647d19b490be9286bc2258", + "size": 1149 + }, + "placeholder.go": { + "mode": "0o644", + "sha256": "246a7219eb14597fa9322bac44691e6ff6f7437df8cf7e4f7fe15c263ce61114", + "size": 2558 + }, + "row.go": { + "mode": "0o644", + "sha256": "089fb1c058ccf2f6664c0cdaac097ad6616e5ec0b44939429bce737d70d9c50e", + "size": 472 + }, + "select.go": { + "mode": "0o644", + "sha256": "28ab9e3d2a9772d6e0ef08f4fa83ea1ccd4a246f086e0e9431a10e5d42504d33", + "size": 11320 + }, + "select_ctx.go": { + "mode": "0o644", + "sha256": "ac68ccbb975d46547f21be70d802af6f4de4ac4c41d9e26a925621e725d74787", + "size": 1908 + }, + "squirrel.go": { + "mode": "0o644", + "sha256": "a5d827d66fdd080a5f2efaccb74fca217265e995d667cf10a026dbc2871e70f9", + "size": 5074 + }, + "squirrel_ctx.go": { + "mode": "0o644", + "sha256": "2e903ebfb7941cb8f68100dc9c500b5bfb214ea8534aaa21e4ea7ed01a70085d", + "size": 3085 + }, + "statement.go": { + "mode": "0o644", + "sha256": "f6cbf3d520fe88614795a68113ea020dd9ad3977e9dcd42af6e0a48a906d2caa", + "size": 3254 + }, + "stmtcacher.go": { + "mode": "0o644", + "sha256": "8f1593570472ec435e653b16a331262629495915b8cf2fda9929e6c7fe0a3c5a", + "size": 2799 + }, + "stmtcacher_ctx.go": { + "mode": "0o644", + "sha256": "e0c02cbf487302ea082afa304b851c454ece0d85f7073c721afb9e5a9e32f7fc", + "size": 2550 + }, + "stmtcacher_noctx.go": { + "mode": "0o644", + "sha256": "14539e8754cc3ee236d7f8af2e0176fb5a8c6183d73ad0e797913ae51a400b22", + "size": 459 + }, + "update.go": { + "mode": "0o644", + "sha256": "6a71f3b4891ad76d45ad74e91dc9e1bdf71aa34bab3688a02d684950049c2aeb", + "size": 7349 + }, + "update_ctx.go": { + "mode": "0o644", + "sha256": "517c4436ea62524889f3a50339d1d3c3ee89ff23050eecaf5fa3a973b8ec4bf0", + "size": 1908 + }, + "where.go": { + "mode": "0o644", + "sha256": "555836c5dd84cbd7571b5e2b3b5b677f3fcd4cc42a0f1cfb3a176f8909bd0755", + "size": 572 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:8397c903899921169852f4bff3ee17f23d7d4f8eaf03854a2bffd0051a2b363f", + "os": "linux", + "sha256": "8397c903899921169852f4bff3ee17f23d7d4f8eaf03854a2bffd0051a2b363f" + }, + "context_inventory_sha256": "8c63f6649adee8ca9a2290a98a9a180d45b9f65f42395812e6e97b409186f81d", + "image": "registry.hf.space/harness-hub-scale800-go-055c69f17f410bee-starter-v1@sha256:9dfb6b7417f54d78d50e6e6bdd951b854ed8da8f5f1782f4fe563a85e1cd0b7a", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "dc294274d204bc3953b3ddc9f385c54f9ded95ae55c720729f3b4765c2561bba", + "receipt_path": "production/runtime-images-extra-v1/resolutions/055c69f17f410bee/resolution.json", + "receipt_sha256": "741436358af5538a7e21351cbe2660ca3aeb440246407b654888e4766be1dc7a", + "registry_digest": "sha256:9dfb6b7417f54d78d50e6e6bdd951b854ed8da8f5f1782f4fe563a85e1cd0b7a", + "source_image": "docker.io/swebench/swesmith.x86_64.masterminds_1776_squirrel.1ded5784@sha256:8b7a7b2f6acd11416e98a5254735925f3e354c9a85634e37a1f9a347ad82ed22", + "source_receipt_sha256": "6be66b515dc9ca98b38e89389e4b485f038418a7591cd99ca1294782042078a3", + "space_commit": "4520e0fbd0db51041911578a6d2b53e5493f8b5a", + "space_id": "harness-hub/scale800-go-055c69f17f410bee-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "959403eb09a7ac9853e1e530d297845072f09bdcdc3d5ae1dd61768aee1bac24", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21", + "source_proof_sha256": "fb51f55446b7e702aebc8cc1ca9b3ae47a82c4aef036c7c06cb79a838ed2a936", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj", + "cloud_launch_ready": false, + "healthy_mirror_commit": "ecf2598064d7f630d661d9a03e6cab204d37eeb8", + "instruction_sha256": "84641102b101180bd709fcf4007aa0a325b95f039b14e7dd383e701645c0d8af", + "is_fork": true, + "learner_path": "tasks/63a1ee21d2764851ad2f8a2f/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "11ac92da622d8d25df663d4bc5d12f464da1a98a9fbb75930e0e65cc58b80a2f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/Masterminds__squirrel.1ded5784/8cf0f2d6e8bf28d318aead941a19eb8b34202a3f/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "1ded5784535dcffa4e175d4efbd1ca2706927758", + "patch_sha256": "6a5cb2fc8599f8e14824f62da542118828891b054a101c9270592ce37f8c36c9", + "provenance_path": "tasks/63a1ee21d2764851ad2f8a2f/source-proof.json", + "repository_lineage": [ + "swesmith/Masterminds__squirrel.1ded5784", + "Masterminds/squirrel" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "8cf0f2d6e8bf28d318aead941a19eb8b34202a3f", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "2683073e4925751571b8bf03612ec59af3db999d", + "source_kind": "mutation", + "source_repo": "swesmith/Masterminds__squirrel.1ded5784", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj", + "task_sha256": "b2b3a848020634c7c2149a8348efa38babfd350527fa3438199b8ebdfbc82bd7", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "Masterminds/squirrel", + "usage": "quarantine_only" + }, + "source_row_sha256": "fe11d38eb14615995f51fc45196b476aec4f021daa89cc9b839ba5e35c23a171", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.travis.yml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/case.go", + "/testbed/delete.go", + "/testbed/delete_ctx.go", + "/testbed/expr.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/insert.go", + "/testbed/insert_ctx.go", + "/testbed/integration/doc.go", + "/testbed/integration/go.mod", + "/testbed/integration/go.sum", + "/testbed/part.go", + "/testbed/placeholder.go", + "/testbed/row.go", + "/testbed/select.go", + "/testbed/select_ctx.go", + "/testbed/squirrel.go", + "/testbed/squirrel_ctx.go", + "/testbed/statement.go", + "/testbed/stmtcacher.go", + "/testbed/stmtcacher_ctx.go", + "/testbed/stmtcacher_noctx.go", + "/testbed/update.go", + "/testbed/update_ctx.go", + "/testbed/where.go" + ] +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/solution/solve.sh b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a119ebda8d3d983ffba6f2709fcea2581acd7ae5 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"update.go": {"data": "cGFja2FnZSBzcXVpcnJlbAoKaW1wb3J0ICgKCSJieXRlcyIKCSJkYXRhYmFzZS9zcWwiCgkiZm10IgoJInNvcnQiCgkic3RyaW5ncyIKCgkiZ2l0aHViLmNvbS9sYW5uL2J1aWxkZXIiCikKCnR5cGUgdXBkYXRlRGF0YSBzdHJ1Y3QgewoJUGxhY2Vob2xkZXJGb3JtYXQgUGxhY2Vob2xkZXJGb3JtYXQKCVJ1bldpdGggICAgICAgICAgIEJhc2VSdW5uZXIKCVByZWZpeGVzICAgICAgICAgIFtdU3FsaXplcgoJVGFibGUgICAgICAgICAgICAgc3RyaW5nCglTZXRDbGF1c2VzICAgICAgICBbXXNldENsYXVzZQoJRnJvbSAgICAgICAgICAgICAgU3FsaXplcgoJV2hlcmVQYXJ0cyAgICAgICAgW11TcWxpemVyCglPcmRlckJ5cyAgICAgICAgICBbXXN0cmluZwoJTGltaXQgICAgICAgICAgICAgc3RyaW5nCglPZmZzZXQgICAgICAgICAgICBzdHJpbmcKCVN1ZmZpeGVzICAgICAgICAgIFtdU3FsaXplcgp9Cgp0eXBlIHNldENsYXVzZSBzdHJ1Y3QgewoJY29sdW1uIHN0cmluZwoJdmFsdWUgIGludGVyZmFjZXt9Cn0KCmZ1bmMgKGQgKnVwZGF0ZURhdGEpIEV4ZWMoKSAoc3FsLlJlc3VsdCwgZXJyb3IpIHsKCWlmIGQuUnVuV2l0aCA9PSBuaWwgewoJCXJldHVybiBuaWwsIFJ1bm5lck5vdFNldAoJfQoJcmV0dXJuIEV4ZWNXaXRoKGQuUnVuV2l0aCwgZCkKfQoKZnVuYyAoZCAqdXBkYXRlRGF0YSkgUXVlcnkoKSAoKnNxbC5Sb3dzLCBlcnJvcikgewoJaWYgZC5SdW5XaXRoID09IG5pbCB7CgkJcmV0dXJuIG5pbCwgUnVubmVyTm90U2V0Cgl9CglyZXR1cm4gUXVlcnlXaXRoKGQuUnVuV2l0aCwgZCkKfQoKZnVuYyAoZCAqdXBkYXRlRGF0YSkgUXVlcnlSb3coKSBSb3dTY2FubmVyIHsKCWlmIGQuUnVuV2l0aCA9PSBuaWwgewoJCXJldHVybiAmUm93e2VycjogUnVubmVyTm90U2V0fQoJfQoJcXVlcnlSb3dlciwgb2sgOj0gZC5SdW5XaXRoLihRdWVyeVJvd2VyKQoJaWYgIW9rIHsKCQlyZXR1cm4gJlJvd3tlcnI6IFJ1bm5lck5vdFF1ZXJ5UnVubmVyfQoJfQoJcmV0dXJuIFF1ZXJ5Um93V2l0aChxdWVyeVJvd2VyLCBkKQp9CgpmdW5jIChkICp1cGRhdGVEYXRhKSBUb1NxbCgpIChzcWxTdHIgc3RyaW5nLCBhcmdzIFtdaW50ZXJmYWNle30sIGVyciBlcnJvcikgewoJaWYgbGVuKGQuVGFibGUpID09IDAgewoJCWVyciA9IGZtdC5FcnJvcmYoInVwZGF0ZSBzdGF0ZW1lbnRzIG11c3Qgc3BlY2lmeSBhIHRhYmxlIikKCQlyZXR1cm4KCX0KCWlmIGxlbihkLlNldENsYXVzZXMpID09IDAgewoJCWVyciA9IGZtdC5FcnJvcmYoInVwZGF0ZSBzdGF0ZW1lbnRzIG11c3QgaGF2ZSBhdCBsZWFzdCBvbmUgU2V0IGNsYXVzZSIpCgkJcmV0dXJuCgl9CgoJc3FsIDo9ICZieXRlcy5CdWZmZXJ7fQoKCWlmIGxlbihkLlByZWZpeGVzKSA+IDAgewoJCWFyZ3MsIGVyciA9IGFwcGVuZFRvU3FsKGQuUHJlZml4ZXMsIHNxbCwgIiAiLCBhcmdzKQoJCWlmIGVyciAhPSBuaWwgewoJCQlyZXR1cm4KCQl9CgoJCXNxbC5Xcml0ZVN0cmluZygiICIpCgl9CgoJc3FsLldyaXRlU3RyaW5nKCJVUERBVEUgIikKCXNxbC5Xcml0ZVN0cmluZyhkLlRhYmxlKQoKCXNxbC5Xcml0ZVN0cmluZygiIFNFVCAiKQoJc2V0U3FscyA6PSBtYWtlKFtdc3RyaW5nLCBsZW4oZC5TZXRDbGF1c2VzKSkKCWZvciBpLCBzZXRDbGF1c2UgOj0gcmFuZ2UgZC5TZXRDbGF1c2VzIHsKCQl2YXIgdmFsU3FsIHN0cmluZwoJCWlmIHZzLCBvayA6PSBzZXRDbGF1c2UudmFsdWUuKFNxbGl6ZXIpOyBvayB7CgkJCXZzcWwsIHZhcmdzLCBlcnIgOj0gdnMuVG9TcWwoKQoJCQlpZiBlcnIgIT0gbmlsIHsKCQkJCXJldHVybiAiIiwgbmlsLCBlcnIKCQkJfQoJCQlpZiBfLCBvayA6PSB2cy4oU2VsZWN0QnVpbGRlcik7IG9rIHsKCQkJCXZhbFNxbCA9IGZtdC5TcHJpbnRmKCIoJXMpIiwgdnNxbCkKCQkJfSBlbHNlIHsKCQkJCXZhbFNxbCA9IHZzcWwKCQkJfQoJCQlhcmdzID0gYXBwZW5kKGFyZ3MsIHZhcmdzLi4uKQoJCX0gZWxzZSB7CgkJCXZhbFNxbCA9ICI/IgoJCQlhcmdzID0gYXBwZW5kKGFyZ3MsIHNldENsYXVzZS52YWx1ZSkKCQl9CgkJc2V0U3Fsc1tpXSA9IGZtdC5TcHJpbnRmKCIlcyA9ICVzIiwgc2V0Q2xhdXNlLmNvbHVtbiwgdmFsU3FsKQoJfQoJc3FsLldyaXRlU3RyaW5nKHN0cmluZ3MuSm9pbihzZXRTcWxzLCAiLCAiKSkKCglpZiBkLkZyb20gIT0gbmlsIHsKCQlzcWwuV3JpdGVTdHJpbmcoIiBGUk9NICIpCgkJYXJncywgZXJyID0gYXBwZW5kVG9TcWwoW11TcWxpemVye2QuRnJvbX0sIHNxbCwgIiIsIGFyZ3MpCgkJaWYgZXJyICE9IG5pbCB7CgkJCXJldHVybgoJCX0KCX0KCglpZiBsZW4oZC5XaGVyZVBhcnRzKSA+IDAgewoJCXNxbC5Xcml0ZVN0cmluZygiIFdIRVJFICIpCgkJYXJncywgZXJyID0gYXBwZW5kVG9TcWwoZC5XaGVyZVBhcnRzLCBzcWwsICIgQU5EICIsIGFyZ3MpCgkJaWYgZXJyICE9IG5pbCB7CgkJCXJldHVybgoJCX0KCX0KCglpZiBsZW4oZC5PcmRlckJ5cykgPiAwIHsKCQlzcWwuV3JpdGVTdHJpbmcoIiBPUkRFUiBCWSAiKQoJCXNxbC5Xcml0ZVN0cmluZyhzdHJpbmdzLkpvaW4oZC5PcmRlckJ5cywgIiwgIikpCgl9CgoJaWYgbGVuKGQuTGltaXQpID4gMCB7CgkJc3FsLldyaXRlU3RyaW5nKCIgTElNSVQgIikKCQlzcWwuV3JpdGVTdHJpbmcoZC5MaW1pdCkKCX0KCglpZiBsZW4oZC5PZmZzZXQpID4gMCB7CgkJc3FsLldyaXRlU3RyaW5nKCIgT0ZGU0VUICIpCgkJc3FsLldyaXRlU3RyaW5nKGQuT2Zmc2V0KQoJfQoKCWlmIGxlbihkLlN1ZmZpeGVzKSA+IDAgewoJCXNxbC5Xcml0ZVN0cmluZygiICIpCgkJYXJncywgZXJyID0gYXBwZW5kVG9TcWwoZC5TdWZmaXhlcywgc3FsLCAiICIsIGFyZ3MpCgkJaWYgZXJyICE9IG5pbCB7CgkJCXJldHVybgoJCX0KCX0KCglzcWxTdHIsIGVyciA9IGQuUGxhY2Vob2xkZXJGb3JtYXQuUmVwbGFjZVBsYWNlaG9sZGVycyhzcWwuU3RyaW5nKCkpCglyZXR1cm4KfQoKLy8gQnVpbGRlcgoKLy8gVXBkYXRlQnVpbGRlciBidWlsZHMgU1FMIFVQREFURSBzdGF0ZW1lbnRzLgp0eXBlIFVwZGF0ZUJ1aWxkZXIgYnVpbGRlci5CdWlsZGVyCgpmdW5jIGluaXQoKSB7CglidWlsZGVyLlJlZ2lzdGVyKFVwZGF0ZUJ1aWxkZXJ7fSwgdXBkYXRlRGF0YXt9KQp9CgovLyBGb3JtYXQgbWV0aG9kcwoKLy8gUGxhY2Vob2xkZXJGb3JtYXQgc2V0cyBQbGFjZWhvbGRlckZvcm1hdCAoZS5nLiBRdWVzdGlvbiBvciBEb2xsYXIpIGZvciB0aGUKLy8gcXVlcnkuCmZ1bmMgKGIgVXBkYXRlQnVpbGRlcikgUGxhY2Vob2xkZXJGb3JtYXQoZiBQbGFjZWhvbGRlckZvcm1hdCkgVXBkYXRlQnVpbGRlciB7CglyZXR1cm4gYnVpbGRlci5TZXQoYiwgIlBsYWNlaG9sZGVyRm9ybWF0IiwgZikuKFVwZGF0ZUJ1aWxkZXIpCn0KCi8vIFJ1bm5lciBtZXRob2RzCgovLyBSdW5XaXRoIHNldHMgYSBSdW5uZXIgKGxpa2UgZGF0YWJhc2Uvc3FsLkRCKSB0byBiZSB1c2VkIHdpdGggZS5nLiBFeGVjLgpmdW5jIChiIFVwZGF0ZUJ1aWxkZXIpIFJ1bldpdGgocnVubmVyIEJhc2VSdW5uZXIpIFVwZGF0ZUJ1aWxkZXIgewoJcmV0dXJuIHNldFJ1bldpdGgoYiwgcnVubmVyKS4oVXBkYXRlQnVpbGRlcikKfQoKLy8gRXhlYyBidWlsZHMgYW5kIEV4ZWNzIHRoZSBxdWVyeSB3aXRoIHRoZSBSdW5uZXIgc2V0IGJ5IFJ1bldpdGguCmZ1bmMgKGIgVXBkYXRlQnVpbGRlcikgRXhlYygpIChzcWwuUmVzdWx0LCBlcnJvcikgewoJZGF0YSA6PSBidWlsZGVyLkdldFN0cnVjdChiKS4odXBkYXRlRGF0YSkKCXJldHVybiBkYXRhLkV4ZWMoKQp9CgpmdW5jIChiIFVwZGF0ZUJ1aWxkZXIpIFF1ZXJ5KCkgKCpzcWwuUm93cywgZXJyb3IpIHsKCWRhdGEgOj0gYnVpbGRlci5HZXRTdHJ1Y3QoYikuKHVwZGF0ZURhdGEpCglyZXR1cm4gZGF0YS5RdWVyeSgpCn0KCmZ1bmMgKGIgVXBkYXRlQnVpbGRlcikgUXVlcnlSb3coKSBSb3dTY2FubmVyIHsKCWRhdGEgOj0gYnVpbGRlci5HZXRTdHJ1Y3QoYikuKHVwZGF0ZURhdGEpCglyZXR1cm4gZGF0YS5RdWVyeVJvdygpCn0KCmZ1bmMgKGIgVXBkYXRlQnVpbGRlcikgU2NhbihkZXN0IC4uLmludGVyZmFjZXt9KSBlcnJvciB7CglyZXR1cm4gYi5RdWVyeVJvdygpLlNjYW4oZGVzdC4uLikKfQoKLy8gU1FMIG1ldGhvZHMKCi8vIFRvU3FsIGJ1aWxkcyB0aGUgcXVlcnkgaW50byBhIFNRTCBzdHJpbmcgYW5kIGJvdW5kIGFyZ3MuCmZ1bmMgKGIgVXBkYXRlQnVpbGRlcikgVG9TcWwoKSAoc3RyaW5nLCBbXWludGVyZmFjZXt9LCBlcnJvcikgewoJZGF0YSA6PSBidWlsZGVyLkdldFN0cnVjdChiKS4odXBkYXRlRGF0YSkKCXJldHVybiBkYXRhLlRvU3FsKCkKfQoKLy8gTXVzdFNxbCBidWlsZHMgdGhlIHF1ZXJ5IGludG8gYSBTUUwgc3RyaW5nIGFuZCBib3VuZCBhcmdzLgovLyBJdCBwYW5pY3MgaWYgdGhlcmUgYXJlIGFueSBlcnJvcnMuCmZ1bmMgKGIgVXBkYXRlQnVpbGRlcikgTXVzdFNxbCgpIChzdHJpbmcsIFtdaW50ZXJmYWNle30pIHsKCXNxbCwgYXJncywgZXJyIDo9IGIuVG9TcWwoKQoJaWYgZXJyICE9IG5pbCB7CgkJcGFuaWMoZXJyKQoJfQoJcmV0dXJuIHNxbCwgYXJncwp9CgovLyBQcmVmaXggYWRkcyBhbiBleHByZXNzaW9uIHRvIHRoZSBiZWdpbm5pbmcgb2YgdGhlIHF1ZXJ5CmZ1bmMgKGIgVXBkYXRlQnVpbGRlcikgUHJlZml4KHNxbCBzdHJpbmcsIGFyZ3MgLi4uaW50ZXJmYWNle30pIFVwZGF0ZUJ1aWxkZXIgewoJcmV0dXJuIGIuUHJlZml4RXhwcihFeHByKHNxbCwgYXJncy4uLikpCn0KCi8vIFByZWZpeEV4cHIgYWRkcyBhbiBleHByZXNzaW9uIHRvIHRoZSB2ZXJ5IGJlZ2lubmluZyBvZiB0aGUgcXVlcnkKZnVuYyAoYiBVcGRhdGVCdWlsZGVyKSBQcmVmaXhFeHByKGV4cHIgU3FsaXplcikgVXBkYXRlQnVpbGRlciB7CglyZXR1cm4gYnVpbGRlci5BcHBlbmQoYiwgIlByZWZpeGVzIiwgZXhwcikuKFVwZGF0ZUJ1aWxkZXIpCn0KCi8vIFRhYmxlIHNldHMgdGhlIHRhYmxlIHRvIGJlIHVwZGF0ZWQuCmZ1bmMgKGIgVXBkYXRlQnVpbGRlcikgVGFibGUodGFibGUgc3RyaW5nKSBVcGRhdGVCdWlsZGVyIHsKCXJldHVybiBidWlsZGVyLlNldChiLCAiVGFibGUiLCB0YWJsZSkuKFVwZGF0ZUJ1aWxkZXIpCn0KCi8vIFNldCBhZGRzIFNFVCBjbGF1c2VzIHRvIHRoZSBxdWVyeS4KZnVuYyAoYiBVcGRhdGVCdWlsZGVyKSBTZXQoY29sdW1uIHN0cmluZywgdmFsdWUgaW50ZXJmYWNle30pIFVwZGF0ZUJ1aWxkZXIgewoJcmV0dXJuIGJ1aWxkZXIuQXBwZW5kKGIsICJTZXRDbGF1c2VzIiwgc2V0Q2xhdXNle2NvbHVtbjogY29sdW1uLCB2YWx1ZTogdmFsdWV9KS4oVXBkYXRlQnVpbGRlcikKfQoKLy8gU2V0TWFwIGlzIGEgY29udmVuaWVuY2UgbWV0aG9kIHdoaWNoIGNhbGxzIC5TZXQgZm9yIGVhY2gga2V5L3ZhbHVlIHBhaXIgaW4gY2xhdXNlcy4KZnVuYyAoYiBVcGRhdGVCdWlsZGVyKSBTZXRNYXAoY2xhdXNlcyBtYXBbc3RyaW5nXWludGVyZmFjZXt9KSBVcGRhdGVCdWlsZGVyIHsKCWtleXMgOj0gbWFrZShbXXN0cmluZywgbGVuKGNsYXVzZXMpKQoJaSA6PSAwCglmb3Iga2V5IDo9IHJhbmdlIGNsYXVzZXMgewoJCWtleXNbaV0gPSBrZXkKCQlpKysKCX0KCXNvcnQuU3RyaW5ncyhrZXlzKQoJZm9yIF8sIGtleSA6PSByYW5nZSBrZXlzIHsKCQl2YWwsIF8gOj0gY2xhdXNlc1trZXldCgkJYiA9IGIuU2V0KGtleSwgdmFsKQoJfQoJcmV0dXJuIGIKfQoKLy8gRnJvbSBhZGRzIEZST00gY2xhdXNlIHRvIHRoZSBxdWVyeQovLyBGUk9NIGlzIHZhbGlkIGNvbnN0cnVjdCBpbiBwb3N0Z3Jlc3FsIG9ubHkuCmZ1bmMgKGIgVXBkYXRlQnVpbGRlcikgRnJvbShmcm9tIHN0cmluZykgVXBkYXRlQnVpbGRlciB7CglyZXR1cm4gYnVpbGRlci5TZXQoYiwgIkZyb20iLCBuZXdQYXJ0KGZyb20pKS4oVXBkYXRlQnVpbGRlcikKfQoKLy8gRnJvbVNlbGVjdCBzZXRzIGEgc3VicXVlcnkgaW50byB0aGUgRlJPTSBjbGF1c2Ugb2YgdGhlIHF1ZXJ5LgpmdW5jIChiIFVwZGF0ZUJ1aWxkZXIpIEZyb21TZWxlY3QoZnJvbSBTZWxlY3RCdWlsZGVyLCBhbGlhcyBzdHJpbmcpIFVwZGF0ZUJ1aWxkZXIgewoJLy8gUHJldmVudCBtaXNudW1iZXJlZCBwYXJhbWV0ZXJzIGluIG5lc3RlZCBzZWxlY3RzICgjMTgzKS4KCWZyb20gPSBmcm9tLlBsYWNlaG9sZGVyRm9ybWF0KFF1ZXN0aW9uKQoJcmV0dXJuIGJ1aWxkZXIuU2V0KGIsICJGcm9tIiwgQWxpYXMoZnJvbSwgYWxpYXMpKS4oVXBkYXRlQnVpbGRlcikKfQoKLy8gV2hlcmUgYWRkcyBXSEVSRSBleHByZXNzaW9ucyB0byB0aGUgcXVlcnkuCi8vCi8vIFNlZSBTZWxlY3RCdWlsZGVyLldoZXJlIGZvciBtb3JlIGluZm9ybWF0aW9uLgpmdW5jIChiIFVwZGF0ZUJ1aWxkZXIpIFdoZXJlKHByZWQgaW50ZXJmYWNle30sIGFyZ3MgLi4uaW50ZXJmYWNle30pIFVwZGF0ZUJ1aWxkZXIgewoJcmV0dXJuIGJ1aWxkZXIuQXBwZW5kKGIsICJXaGVyZVBhcnRzIiwgbmV3V2hlcmVQYXJ0KHByZWQsIGFyZ3MuLi4pKS4oVXBkYXRlQnVpbGRlcikKfQoKLy8gT3JkZXJCeSBhZGRzIE9SREVSIEJZIGV4cHJlc3Npb25zIHRvIHRoZSBxdWVyeS4KZnVuYyAoYiBVcGRhdGVCdWlsZGVyKSBPcmRlckJ5KG9yZGVyQnlzIC4uLnN0cmluZykgVXBkYXRlQnVpbGRlciB7CglyZXR1cm4gYnVpbGRlci5FeHRlbmQoYiwgIk9yZGVyQnlzIiwgb3JkZXJCeXMpLihVcGRhdGVCdWlsZGVyKQp9CgovLyBMaW1pdCBzZXRzIGEgTElNSVQgY2xhdXNlIG9uIHRoZSBxdWVyeS4KZnVuYyAoYiBVcGRhdGVCdWlsZGVyKSBMaW1pdChsaW1pdCB1aW50NjQpIFVwZGF0ZUJ1aWxkZXIgewoJcmV0dXJuIGJ1aWxkZXIuU2V0KGIsICJMaW1pdCIsIGZtdC5TcHJpbnRmKCIlZCIsIGxpbWl0KSkuKFVwZGF0ZUJ1aWxkZXIpCn0KCi8vIE9mZnNldCBzZXRzIGEgT0ZGU0VUIGNsYXVzZSBvbiB0aGUgcXVlcnkuCmZ1bmMgKGIgVXBkYXRlQnVpbGRlcikgT2Zmc2V0KG9mZnNldCB1aW50NjQpIFVwZGF0ZUJ1aWxkZXIgewoJcmV0dXJuIGJ1aWxkZXIuU2V0KGIsICJPZmZzZXQiLCBmbXQuU3ByaW50ZigiJWQiLCBvZmZzZXQpKS4oVXBkYXRlQnVpbGRlcikKfQoKLy8gU3VmZml4IGFkZHMgYW4gZXhwcmVzc2lvbiB0byB0aGUgZW5kIG9mIHRoZSBxdWVyeQpmdW5jIChiIFVwZGF0ZUJ1aWxkZXIpIFN1ZmZpeChzcWwgc3RyaW5nLCBhcmdzIC4uLmludGVyZmFjZXt9KSBVcGRhdGVCdWlsZGVyIHsKCXJldHVybiBiLlN1ZmZpeEV4cHIoRXhwcihzcWwsIGFyZ3MuLi4pKQp9CgovLyBTdWZmaXhFeHByIGFkZHMgYW4gZXhwcmVzc2lvbiB0byB0aGUgZW5kIG9mIHRoZSBxdWVyeQpmdW5jIChiIFVwZGF0ZUJ1aWxkZXIpIFN1ZmZpeEV4cHIoZXhwciBTcWxpemVyKSBVcGRhdGVCdWlsZGVyIHsKCXJldHVybiBidWlsZGVyLkFwcGVuZChiLCAiU3VmZml4ZXMiLCBleHByKS4oVXBkYXRlQnVpbGRlcikKfQo=", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/task.toml b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f3bffbbb7e652d80cfa6920008039764caac697f --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:284e0a1d5ce03b8f4e1414bdb62e9b195c91a24e81cfecb9daea647d845f4547" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/case_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/case_test.go new file mode 100644 index 0000000000000000000000000000000000000000..a2ad995cfe6d0bb71f0755c70268592ff94d8a1f --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/case_test.go @@ -0,0 +1,150 @@ +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestCaseWithVal(t *testing.T) { + caseStmt := Case("number"). + When("1", "one"). + When("2", "two"). + Else(Expr("?", "big number")) + + qb := Select(). + Column(caseStmt). + From("table") + sql, args, err := qb.ToSql() + + assert.NoError(t, err) + + expectedSql := "SELECT CASE number " + + "WHEN 1 THEN one " + + "WHEN 2 THEN two " + + "ELSE ? " + + "END " + + "FROM table" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"big number"} + assert.Equal(t, expectedArgs, args) +} + +func TestCaseWithComplexVal(t *testing.T) { + caseStmt := Case("? > ?", 10, 5). + When("true", "'T'") + + qb := Select(). + Column(Alias(caseStmt, "complexCase")). + From("table") + sql, args, err := qb.ToSql() + + assert.NoError(t, err) + + expectedSql := "SELECT (CASE ? > ? " + + "WHEN true THEN 'T' " + + "END) AS complexCase " + + "FROM table" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{10, 5} + assert.Equal(t, expectedArgs, args) +} + +func TestCaseWithNoVal(t *testing.T) { + caseStmt := Case(). + When(Eq{"x": 0}, "x is zero"). + When(Expr("x > ?", 1), Expr("CONCAT('x is greater than ', ?)", 2)) + + qb := Select().Column(caseStmt).From("table") + sql, args, err := qb.ToSql() + + assert.NoError(t, err) + + expectedSql := "SELECT CASE " + + "WHEN x = ? THEN x is zero " + + "WHEN x > ? THEN CONCAT('x is greater than ', ?) " + + "END " + + "FROM table" + + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{0, 1, 2} + assert.Equal(t, expectedArgs, args) +} + +func TestCaseWithExpr(t *testing.T) { + caseStmt := Case(Expr("x = ?", true)). + When("true", Expr("?", "it's true!")). + Else("42") + + qb := Select().Column(caseStmt).From("table") + sql, args, err := qb.ToSql() + + assert.NoError(t, err) + + expectedSql := "SELECT CASE x = ? " + + "WHEN true THEN ? " + + "ELSE 42 " + + "END " + + "FROM table" + + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{true, "it's true!"} + assert.Equal(t, expectedArgs, args) +} + +func TestMultipleCase(t *testing.T) { + caseStmtNoval := Case(Expr("x = ?", true)). + When("true", Expr("?", "it's true!")). + Else("42") + caseStmtExpr := Case(). + When(Eq{"x": 0}, "'x is zero'"). + When(Expr("x > ?", 1), Expr("CONCAT('x is greater than ', ?)", 2)) + + qb := Select(). + Column(Alias(caseStmtNoval, "case_noval")). + Column(Alias(caseStmtExpr, "case_expr")). + From("table") + + sql, args, err := qb.ToSql() + + assert.NoError(t, err) + + expectedSql := "SELECT " + + "(CASE x = ? WHEN true THEN ? ELSE 42 END) AS case_noval, " + + "(CASE WHEN x = ? THEN 'x is zero' WHEN x > ? THEN CONCAT('x is greater than ', ?) END) AS case_expr " + + "FROM table" + + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{ + true, "it's true!", + 0, 1, 2, + } + assert.Equal(t, expectedArgs, args) +} + +func TestCaseWithNoWhenClause(t *testing.T) { + caseStmt := Case("something"). + Else("42") + + qb := Select().Column(caseStmt).From("table") + + _, _, err := qb.ToSql() + + assert.Error(t, err) + + assert.Equal(t, "case expression must contain at lease one WHEN clause", err.Error()) +} + +func TestCaseBuilderMustSql(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("TestCaseBuilderMustSql should have panicked!") + } + }() + Case("").MustSql() +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/delete_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/delete_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..8a80b6ae502df4301a54a067896c7e31143ed427 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/delete_ctx_test.go @@ -0,0 +1,41 @@ +// +build go1.8 + +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestDeleteBuilderContextRunners(t *testing.T) { + db := &DBStub{} + b := Delete("test").Where("x = ?", 1).RunWith(db) + + expectedSql := "DELETE FROM test WHERE x = ?" + + b.ExecContext(ctx) + assert.Equal(t, expectedSql, db.LastExecSql) + + b.QueryContext(ctx) + assert.Equal(t, expectedSql, db.LastQuerySql) + + b.QueryRowContext(ctx) + assert.Equal(t, expectedSql, db.LastQueryRowSql) + + err := b.ScanContext(ctx) + assert.NoError(t, err) +} + +func TestDeleteBuilderContextNoRunner(t *testing.T) { + b := Delete("test").Where("x != ?", 0).Suffix("RETURNING x") + + _, err := b.ExecContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + _, err = b.QueryContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + err = b.ScanContext(ctx) + assert.Equal(t, RunnerNotSet, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/delete_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/delete_test.go new file mode 100644 index 0000000000000000000000000000000000000000..62691f246f11a751ec289bb34ad80bbca2d47313 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/delete_test.go @@ -0,0 +1,81 @@ +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestDeleteBuilderToSql(t *testing.T) { + b := Delete(""). + Prefix("WITH prefix AS ?", 0). + From("a"). + Where("b = ?", 1). + OrderBy("c"). + Limit(2). + Offset(3). + Suffix("RETURNING ?", 4) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := + "WITH prefix AS ? " + + "DELETE FROM a WHERE b = ? ORDER BY c LIMIT 2 OFFSET 3 " + + "RETURNING ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{0, 1, 4} + assert.Equal(t, expectedArgs, args) +} + +func TestDeleteBuilderToSqlErr(t *testing.T) { + _, _, err := Delete("").ToSql() + assert.Error(t, err) +} + +func TestDeleteBuilderMustSql(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("TestDeleteBuilderMustSql should have panicked!") + } + }() + Delete("").MustSql() +} + +func TestDeleteBuilderPlaceholders(t *testing.T) { + b := Delete("test").Where("x = ? AND y = ?", 1, 2) + + sql, _, _ := b.PlaceholderFormat(Question).ToSql() + assert.Equal(t, "DELETE FROM test WHERE x = ? AND y = ?", sql) + + sql, _, _ = b.PlaceholderFormat(Dollar).ToSql() + assert.Equal(t, "DELETE FROM test WHERE x = $1 AND y = $2", sql) +} + +func TestDeleteBuilderRunners(t *testing.T) { + db := &DBStub{} + b := Delete("test").Where("x = ?", 1).RunWith(db) + + expectedSql := "DELETE FROM test WHERE x = ?" + + b.Exec() + assert.Equal(t, expectedSql, db.LastExecSql) +} + +func TestDeleteBuilderNoRunner(t *testing.T) { + b := Delete("test") + + _, err := b.Exec() + assert.Equal(t, RunnerNotSet, err) +} + +func TestDeleteWithQuery(t *testing.T) { + db := &DBStub{} + b := Delete("test").Where("id=55").Suffix("RETURNING path").RunWith(db) + + expectedSql := "DELETE FROM test WHERE id=55 RETURNING path" + b.Query() + + assert.Equal(t, expectedSql, db.LastQuerySql) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/expr_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/expr_test.go new file mode 100644 index 0000000000000000000000000000000000000000..60d2ae5cc3020d0d40b10e3b3042114fbac6ffb4 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/expr_test.go @@ -0,0 +1,464 @@ +package squirrel + +import ( + "database/sql" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestConcatExpr(t *testing.T) { + b := ConcatExpr("COALESCE(name,", Expr("CONCAT(?,' ',?)", "f", "l"), ")") + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "COALESCE(name,CONCAT(?,' ',?))" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"f", "l"} + assert.Equal(t, expectedArgs, args) +} + +func TestConcatExprBadType(t *testing.T) { + b := ConcatExpr("prefix", 123, "suffix") + _, _, err := b.ToSql() + assert.Error(t, err) + assert.Contains(t, err.Error(), "123 is not") +} + +func TestEqToSql(t *testing.T) { + b := Eq{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id = ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestEqEmptyToSql(t *testing.T) { + sql, args, err := Eq{}.ToSql() + assert.NoError(t, err) + + expectedSql := "(1=1)" + assert.Equal(t, expectedSql, sql) + assert.Empty(t, args) +} + +func TestEqInToSql(t *testing.T) { + b := Eq{"id": []int{1, 2, 3}} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id IN (?,?,?)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2, 3} + assert.Equal(t, expectedArgs, args) +} + +func TestNotEqToSql(t *testing.T) { + b := NotEq{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id <> ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestEqNotInToSql(t *testing.T) { + b := NotEq{"id": []int{1, 2, 3}} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id NOT IN (?,?,?)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2, 3} + assert.Equal(t, expectedArgs, args) +} + +func TestEqInEmptyToSql(t *testing.T) { + b := Eq{"id": []int{}} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "(1=0)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{} + assert.Equal(t, expectedArgs, args) +} + +func TestNotEqInEmptyToSql(t *testing.T) { + b := NotEq{"id": []int{}} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "(1=1)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{} + assert.Equal(t, expectedArgs, args) +} + +func TestEqBytesToSql(t *testing.T) { + b := Eq{"id": []byte("test")} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id = ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{[]byte("test")} + assert.Equal(t, expectedArgs, args) +} + +func TestLtToSql(t *testing.T) { + b := Lt{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id < ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestLtOrEqToSql(t *testing.T) { + b := LtOrEq{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id <= ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestGtToSql(t *testing.T) { + b := Gt{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id > ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestGtOrEqToSql(t *testing.T) { + b := GtOrEq{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id >= ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestExprNilToSql(t *testing.T) { + var b Sqlizer + b = NotEq{"name": nil} + sql, args, err := b.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + + expectedSql := "name IS NOT NULL" + assert.Equal(t, expectedSql, sql) + + b = Eq{"name": nil} + sql, args, err = b.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + + expectedSql = "name IS NULL" + assert.Equal(t, expectedSql, sql) +} + +func TestNullTypeString(t *testing.T) { + var b Sqlizer + var name sql.NullString + + b = Eq{"name": name} + sql, args, err := b.ToSql() + + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "name IS NULL", sql) + + name.Scan("Name") + b = Eq{"name": name} + sql, args, err = b.ToSql() + + assert.NoError(t, err) + assert.Equal(t, []interface{}{"Name"}, args) + assert.Equal(t, "name = ?", sql) +} + +func TestNullTypeInt64(t *testing.T) { + var userID sql.NullInt64 + userID.Scan(nil) + b := Eq{"user_id": userID} + sql, args, err := b.ToSql() + + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "user_id IS NULL", sql) + + userID.Scan(int64(10)) + b = Eq{"user_id": userID} + sql, args, err = b.ToSql() + + assert.NoError(t, err) + assert.Equal(t, []interface{}{int64(10)}, args) + assert.Equal(t, "user_id = ?", sql) +} + +func TestNilPointer(t *testing.T) { + var name *string = nil + eq := Eq{"name": name} + sql, args, err := eq.ToSql() + + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "name IS NULL", sql) + + neq := NotEq{"name": name} + sql, args, err = neq.ToSql() + + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "name IS NOT NULL", sql) + + var ids *[]int = nil + eq = Eq{"id": ids} + sql, args, err = eq.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "id IS NULL", sql) + + neq = NotEq{"id": ids} + sql, args, err = neq.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "id IS NOT NULL", sql) + + var ida *[3]int = nil + eq = Eq{"id": ida} + sql, args, err = eq.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "id IS NULL", sql) + + neq = NotEq{"id": ida} + sql, args, err = neq.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "id IS NOT NULL", sql) + +} + +func TestNotNilPointer(t *testing.T) { + c := "Name" + name := &c + eq := Eq{"name": name} + sql, args, err := eq.ToSql() + + assert.NoError(t, err) + assert.Equal(t, []interface{}{"Name"}, args) + assert.Equal(t, "name = ?", sql) + + neq := NotEq{"name": name} + sql, args, err = neq.ToSql() + + assert.NoError(t, err) + assert.Equal(t, []interface{}{"Name"}, args) + assert.Equal(t, "name <> ?", sql) + + s := []int{1, 2, 3} + ids := &s + eq = Eq{"id": ids} + sql, args, err = eq.ToSql() + assert.NoError(t, err) + assert.Equal(t, []interface{}{1, 2, 3}, args) + assert.Equal(t, "id IN (?,?,?)", sql) + + neq = NotEq{"id": ids} + sql, args, err = neq.ToSql() + assert.NoError(t, err) + assert.Equal(t, []interface{}{1, 2, 3}, args) + assert.Equal(t, "id NOT IN (?,?,?)", sql) + + a := [3]int{1, 2, 3} + ida := &a + eq = Eq{"id": ida} + sql, args, err = eq.ToSql() + assert.NoError(t, err) + assert.Equal(t, []interface{}{1, 2, 3}, args) + assert.Equal(t, "id IN (?,?,?)", sql) + + neq = NotEq{"id": ida} + sql, args, err = neq.ToSql() + assert.NoError(t, err) + assert.Equal(t, []interface{}{1, 2, 3}, args) + assert.Equal(t, "id NOT IN (?,?,?)", sql) +} + +func TestEmptyAndToSql(t *testing.T) { + sql, args, err := And{}.ToSql() + assert.NoError(t, err) + + expectedSql := "(1=1)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{} + assert.Equal(t, expectedArgs, args) +} + +func TestEmptyOrToSql(t *testing.T) { + sql, args, err := Or{}.ToSql() + assert.NoError(t, err) + + expectedSql := "(1=0)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{} + assert.Equal(t, expectedArgs, args) +} + +func TestLikeToSql(t *testing.T) { + b := Like{"name": "%irrel"} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "name LIKE ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"%irrel"} + assert.Equal(t, expectedArgs, args) +} + +func TestNotLikeToSql(t *testing.T) { + b := NotLike{"name": "%irrel"} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "name NOT LIKE ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"%irrel"} + assert.Equal(t, expectedArgs, args) +} + +func TestILikeToSql(t *testing.T) { + b := ILike{"name": "sq%"} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "name ILIKE ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"sq%"} + assert.Equal(t, expectedArgs, args) +} + +func TestNotILikeToSql(t *testing.T) { + b := NotILike{"name": "sq%"} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "name NOT ILIKE ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"sq%"} + assert.Equal(t, expectedArgs, args) +} + +func TestSqlEqOrder(t *testing.T) { + b := Eq{"a": 1, "b": 2, "c": 3} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "a = ? AND b = ? AND c = ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2, 3} + assert.Equal(t, expectedArgs, args) +} + +func TestSqlLtOrder(t *testing.T) { + b := Lt{"a": 1, "b": 2, "c": 3} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "a < ? AND b < ? AND c < ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2, 3} + assert.Equal(t, expectedArgs, args) +} + +func TestExprEscaped(t *testing.T) { + b := Expr("count(??)", Expr("x")) + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "count(??)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{Expr("x")} + assert.Equal(t, expectedArgs, args) +} + +func TestExprRecursion(t *testing.T) { + { + b := Expr("count(?)", Expr("nullif(a,?)", "b")) + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "count(nullif(a,?))" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"b"} + assert.Equal(t, expectedArgs, args) + } + { + b := Expr("extract(? from ?)", Expr("epoch"), "2001-02-03") + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "extract(epoch from ?)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"2001-02-03"} + assert.Equal(t, expectedArgs, args) + } + { + b := Expr("JOIN t1 ON ?", And{Eq{"id": 1}, Expr("NOT c1"), Expr("? @@ ?", "x", "y")}) + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "JOIN t1 ON (id = ? AND NOT c1 AND ? @@ ?)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, "x", "y"} + assert.Equal(t, expectedArgs, args) + } +} + +func ExampleEq() { + Select("id", "created", "first_name").From("users").Where(Eq{ + "company": 20, + }) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/insert_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/insert_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..0e02ed476e05a35a22e8d298fbf53c3ca4fed0d7 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/insert_ctx_test.go @@ -0,0 +1,41 @@ +// +build go1.8 + +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestInsertBuilderContextRunners(t *testing.T) { + db := &DBStub{} + b := Insert("test").Values(1).RunWith(db) + + expectedSql := "INSERT INTO test VALUES (?)" + + b.ExecContext(ctx) + assert.Equal(t, expectedSql, db.LastExecSql) + + b.QueryContext(ctx) + assert.Equal(t, expectedSql, db.LastQuerySql) + + b.QueryRowContext(ctx) + assert.Equal(t, expectedSql, db.LastQueryRowSql) + + err := b.ScanContext(ctx) + assert.NoError(t, err) +} + +func TestInsertBuilderContextNoRunner(t *testing.T) { + b := Insert("test").Values(1) + + _, err := b.ExecContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + _, err = b.QueryContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + err = b.ScanContext(ctx) + assert.Equal(t, RunnerNotSet, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/insert_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/insert_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ced2313547fd37c5f23fc815a4394e6d8b61f197 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/insert_test.go @@ -0,0 +1,112 @@ +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestInsertBuilderToSql(t *testing.T) { + b := Insert(""). + Prefix("WITH prefix AS ?", 0). + Into("a"). + Options("DELAYED", "IGNORE"). + Columns("b", "c"). + Values(1, 2). + Values(3, Expr("? + 1", 4)). + Suffix("RETURNING ?", 5) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSQL := + "WITH prefix AS ? " + + "INSERT DELAYED IGNORE INTO a (b,c) VALUES (?,?),(?,? + 1) " + + "RETURNING ?" + assert.Equal(t, expectedSQL, sql) + + expectedArgs := []interface{}{0, 1, 2, 3, 4, 5} + assert.Equal(t, expectedArgs, args) +} + +func TestInsertBuilderToSqlErr(t *testing.T) { + _, _, err := Insert("").Values(1).ToSql() + assert.Error(t, err) + + _, _, err = Insert("x").ToSql() + assert.Error(t, err) +} + +func TestInsertBuilderMustSql(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("TestInsertBuilderMustSql should have panicked!") + } + }() + Insert("").MustSql() +} + +func TestInsertBuilderPlaceholders(t *testing.T) { + b := Insert("test").Values(1, 2) + + sql, _, _ := b.PlaceholderFormat(Question).ToSql() + assert.Equal(t, "INSERT INTO test VALUES (?,?)", sql) + + sql, _, _ = b.PlaceholderFormat(Dollar).ToSql() + assert.Equal(t, "INSERT INTO test VALUES ($1,$2)", sql) +} + +func TestInsertBuilderRunners(t *testing.T) { + db := &DBStub{} + b := Insert("test").Values(1).RunWith(db) + + expectedSQL := "INSERT INTO test VALUES (?)" + + b.Exec() + assert.Equal(t, expectedSQL, db.LastExecSql) +} + +func TestInsertBuilderNoRunner(t *testing.T) { + b := Insert("test").Values(1) + + _, err := b.Exec() + assert.Equal(t, RunnerNotSet, err) +} + +func TestInsertBuilderSetMap(t *testing.T) { + b := Insert("table").SetMap(Eq{"field1": 1, "field2": 2, "field3": 3}) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSQL := "INSERT INTO table (field1,field2,field3) VALUES (?,?,?)" + assert.Equal(t, expectedSQL, sql) + + expectedArgs := []interface{}{1, 2, 3} + assert.Equal(t, expectedArgs, args) +} + +func TestInsertBuilderSelect(t *testing.T) { + sb := Select("field1").From("table1").Where(Eq{"field1": 1}) + ib := Insert("table2").Columns("field1").Select(sb) + + sql, args, err := ib.ToSql() + assert.NoError(t, err) + + expectedSQL := "INSERT INTO table2 (field1) SELECT field1 FROM table1 WHERE field1 = ?" + assert.Equal(t, expectedSQL, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestInsertBuilderReplace(t *testing.T) { + b := Replace("table").Values(1) + + expectedSQL := "REPLACE INTO table VALUES (?)" + + sql, _, err := b.ToSql() + assert.NoError(t, err) + + assert.Equal(t, expectedSQL, sql) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/integration/integration_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/integration/integration_test.go new file mode 100644 index 0000000000000000000000000000000000000000..e861e7f6f36595633e7ce3bc0495283aa417dc52 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/integration/integration_test.go @@ -0,0 +1,135 @@ +package integration + +import ( + "context" + "database/sql" + "flag" + "fmt" + "os" + "testing" + + "github.com/stretchr/testify/assert" + + sqrl "github.com/Masterminds/squirrel" + + _ "github.com/go-sql-driver/mysql" + _ "github.com/lib/pq" + _ "github.com/mattn/go-sqlite3" +) + +const ( + testSchema = ` + CREATE TABLE squirrel_integration ( k INT, v TEXT )` + testData = ` + INSERT INTO squirrel_integration VALUES + (1, 'foo'), + (3, 'bar'), + (2, 'foo'), + (4, 'baz') + ` +) + +var ( + sb sqrl.StatementBuilderType +) + +func TestMain(m *testing.M) { + var driver, dataSource string + flag.StringVar(&driver, "driver", "", "integration database driver") + flag.StringVar(&dataSource, "dataSource", "", "integration database data source") + flag.Parse() + + if driver == "" { + driver = "sqlite3" + } + + if driver == "sqlite3" && dataSource == "" { + dataSource = ":memory:" + } + + db, err := sql.Open(driver, dataSource) + if err != nil { + fmt.Printf("error opening database: %v\n", err) + os.Exit(-1) + } + + _, err = db.Exec(testSchema) + if err != nil { + fmt.Printf("error creating test schema: %v\n", err) + os.Exit(-2) + } + + defer func() { + _, err = db.Exec("DROP TABLE squirrel_integration") + fmt.Printf("error removing test schema: %v\n", err) + }() + + _, err = db.Exec(testData) + if err != nil { + fmt.Printf("error inserting test data: %v\n", err) + os.Exit(-3) + } + + sb = sqrl.StatementBuilder.RunWith(db) + + if driver == "postgres" { + sb = sb.PlaceholderFormat(sqrl.Dollar) + } + + os.Exit(m.Run()) +} + +func assertVals(t *testing.T, s sqrl.SelectBuilder, expected ...string) { + rows, err := s.Query() + assert.NoError(t, err) + defer rows.Close() + + vals := make([]string, len(expected)) + for i := range vals { + assert.True(t, rows.Next()) + assert.NoError(t, rows.Scan(&vals[i])) + } + assert.False(t, rows.Next()) + + if expected != nil { + assert.Equal(t, expected, vals) + } +} + +func TestSimpleSelect(t *testing.T) { + assertVals( + t, + sb.Select("v").From("squirrel_integration"), + "foo", "bar", "foo", "baz") +} + +func TestEq(t *testing.T) { + s := sb.Select("v").From("squirrel_integration") + assertVals(t, s.Where(sqrl.Eq{"k": 4}), "baz") + assertVals(t, s.Where(sqrl.NotEq{"k": 2}), "foo", "bar", "baz") + assertVals(t, s.Where(sqrl.Eq{"k": []int{1, 4}}), "foo", "baz") + assertVals(t, s.Where(sqrl.NotEq{"k": []int{1, 4}}), "bar", "foo") + assertVals(t, s.Where(sqrl.Eq{"k": nil})) + assertVals(t, s.Where(sqrl.NotEq{"k": nil}), "foo", "bar", "foo", "baz") + assertVals(t, s.Where(sqrl.Eq{"k": []int{}})) + assertVals(t, s.Where(sqrl.NotEq{"k": []int{}}), "foo", "bar", "foo", "baz") +} + +func TestIneq(t *testing.T) { + s := sb.Select("v").From("squirrel_integration") + assertVals(t, s.Where(sqrl.Lt{"k": 3}), "foo", "foo") + assertVals(t, s.Where(sqrl.Gt{"k": 3}), "baz") +} + +func TestConj(t *testing.T) { + s := sb.Select("v").From("squirrel_integration") + assertVals(t, s.Where(sqrl.And{sqrl.Gt{"k": 1}, sqrl.Lt{"k": 4}}), "bar", "foo") + assertVals(t, s.Where(sqrl.Or{sqrl.Gt{"k": 3}, sqrl.Lt{"k": 2}}), "foo", "baz") +} + +func TestContext(t *testing.T) { + s := sb.Select("v").From("squirrel_integration") + ctx := context.Background() + _, err := s.QueryContext(ctx) + assert.NoError(t, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/placeholder_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/placeholder_test.go new file mode 100644 index 0000000000000000000000000000000000000000..8e7f43f4929409739603e5c61bd74be940f016b5 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/placeholder_test.go @@ -0,0 +1,67 @@ +package squirrel + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestQuestion(t *testing.T) { + sql := "x = ? AND y = ?" + s, _ := Question.ReplacePlaceholders(sql) + assert.Equal(t, sql, s) +} + +func TestDollar(t *testing.T) { + sql := "x = ? AND y = ?" + s, _ := Dollar.ReplacePlaceholders(sql) + assert.Equal(t, "x = $1 AND y = $2", s) +} + +func TestColon(t *testing.T) { + sql := "x = ? AND y = ?" + s, _ := Colon.ReplacePlaceholders(sql) + assert.Equal(t, "x = :1 AND y = :2", s) +} + +func TestAtp(t *testing.T) { + sql := "x = ? AND y = ?" + s, _ := AtP.ReplacePlaceholders(sql) + assert.Equal(t, "x = @p1 AND y = @p2", s) +} + +func TestPlaceholders(t *testing.T) { + assert.Equal(t, Placeholders(2), "?,?") +} + +func TestEscapeDollar(t *testing.T) { + sql := "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ??| array['?'] AND enabled = ?" + s, _ := Dollar.ReplacePlaceholders(sql) + assert.Equal(t, "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ?| array['$1'] AND enabled = $2", s) +} + +func TestEscapeColon(t *testing.T) { + sql := "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ??| array['?'] AND enabled = ?" + s, _ := Colon.ReplacePlaceholders(sql) + assert.Equal(t, "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ?| array[':1'] AND enabled = :2", s) +} + +func TestEscapeAtp(t *testing.T) { + sql := "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ??| array['?'] AND enabled = ?" + s, _ := AtP.ReplacePlaceholders(sql) + assert.Equal(t, "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ?| array['@p1'] AND enabled = @p2", s) +} + +func BenchmarkPlaceholdersArray(b *testing.B) { + var count = b.N + placeholders := make([]string, count) + for i := 0; i < count; i++ { + placeholders[i] = "?" + } + var _ = strings.Join(placeholders, ",") +} + +func BenchmarkPlaceholdersStrings(b *testing.B) { + Placeholders(b.N) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/row_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/row_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ebeeb85485799fc47480555357873b4c4656c1c0 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/row_test.go @@ -0,0 +1,34 @@ +package squirrel + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" +) + +type RowStub struct { + Scanned bool +} + +func (r *RowStub) Scan(_ ...interface{}) error { + r.Scanned = true + return nil +} + +func TestRowScan(t *testing.T) { + stub := &RowStub{} + row := &Row{RowScanner: stub} + err := row.Scan() + assert.True(t, stub.Scanned, "row was not scanned") + assert.NoError(t, err) +} + +func TestRowScanErr(t *testing.T) { + stub := &RowStub{} + rowErr := fmt.Errorf("scan err") + row := &Row{RowScanner: stub, err: rowErr} + err := row.Scan() + assert.False(t, stub.Scanned, "row was scanned") + assert.Equal(t, rowErr, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/select_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/select_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b36ae44285e9ced8b14376ef6b060325370137d0 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/select_ctx_test.go @@ -0,0 +1,41 @@ +// +build go1.8 + +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestSelectBuilderContextRunners(t *testing.T) { + db := &DBStub{} + b := Select("test").RunWith(db) + + expectedSql := "SELECT test" + + b.ExecContext(ctx) + assert.Equal(t, expectedSql, db.LastExecSql) + + b.QueryContext(ctx) + assert.Equal(t, expectedSql, db.LastQuerySql) + + b.QueryRowContext(ctx) + assert.Equal(t, expectedSql, db.LastQueryRowSql) + + err := b.ScanContext(ctx) + assert.NoError(t, err) +} + +func TestSelectBuilderContextNoRunner(t *testing.T) { + b := Select("test") + + _, err := b.ExecContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + _, err = b.QueryContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + err = b.ScanContext(ctx) + assert.Equal(t, RunnerNotSet, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/select_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/select_test.go new file mode 100644 index 0000000000000000000000000000000000000000..80161bf5a947cbb02b3039b857b71563630f2ad0 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/select_test.go @@ -0,0 +1,463 @@ +package squirrel + +import ( + "database/sql" + "fmt" + "log" + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +func TestSelectBuilderToSql(t *testing.T) { + subQ := Select("aa", "bb").From("dd") + b := Select("a", "b"). + Prefix("WITH prefix AS ?", 0). + Distinct(). + Columns("c"). + Column("IF(d IN ("+Placeholders(3)+"), 1, 0) as stat_column", 1, 2, 3). + Column(Expr("a > ?", 100)). + Column(Alias(Eq{"b": []int{101, 102, 103}}, "b_alias")). + Column(Alias(subQ, "subq")). + From("e"). + JoinClause("CROSS JOIN j1"). + Join("j2"). + LeftJoin("j3"). + RightJoin("j4"). + InnerJoin("j5"). + CrossJoin("j6"). + Where("f = ?", 4). + Where(Eq{"g": 5}). + Where(map[string]interface{}{"h": 6}). + Where(Eq{"i": []int{7, 8, 9}}). + Where(Or{Expr("j = ?", 10), And{Eq{"k": 11}, Expr("true")}}). + GroupBy("l"). + Having("m = n"). + OrderByClause("? DESC", 1). + OrderBy("o ASC", "p DESC"). + Limit(12). + Offset(13). + Suffix("FETCH FIRST ? ROWS ONLY", 14) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := + "WITH prefix AS ? " + + "SELECT DISTINCT a, b, c, IF(d IN (?,?,?), 1, 0) as stat_column, a > ?, " + + "(b IN (?,?,?)) AS b_alias, " + + "(SELECT aa, bb FROM dd) AS subq " + + "FROM e " + + "CROSS JOIN j1 JOIN j2 LEFT JOIN j3 RIGHT JOIN j4 INNER JOIN j5 CROSS JOIN j6 " + + "WHERE f = ? AND g = ? AND h = ? AND i IN (?,?,?) AND (j = ? OR (k = ? AND true)) " + + "GROUP BY l HAVING m = n ORDER BY ? DESC, o ASC, p DESC LIMIT 12 OFFSET 13 " + + "FETCH FIRST ? ROWS ONLY" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{0, 1, 2, 3, 100, 101, 102, 103, 4, 5, 6, 7, 8, 9, 10, 11, 1, 14} + assert.Equal(t, expectedArgs, args) +} + +func TestSelectBuilderFromSelect(t *testing.T) { + subQ := Select("c").From("d").Where(Eq{"i": 0}) + b := Select("a", "b").FromSelect(subQ, "subq") + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "SELECT a, b FROM (SELECT c FROM d WHERE i = ?) AS subq" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{0} + assert.Equal(t, expectedArgs, args) +} + +func TestSelectBuilderFromSelectNestedDollarPlaceholders(t *testing.T) { + subQ := Select("c"). + From("t"). + Where(Gt{"c": 1}). + PlaceholderFormat(Dollar) + b := Select("c"). + FromSelect(subQ, "subq"). + Where(Lt{"c": 2}). + PlaceholderFormat(Dollar) + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "SELECT c FROM (SELECT c FROM t WHERE c > $1) AS subq WHERE c < $2" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2} + assert.Equal(t, expectedArgs, args) +} + +func TestSelectBuilderToSqlErr(t *testing.T) { + _, _, err := Select().From("x").ToSql() + assert.Error(t, err) +} + +func TestSelectBuilderPlaceholders(t *testing.T) { + b := Select("test").Where("x = ? AND y = ?") + + sql, _, _ := b.PlaceholderFormat(Question).ToSql() + assert.Equal(t, "SELECT test WHERE x = ? AND y = ?", sql) + + sql, _, _ = b.PlaceholderFormat(Dollar).ToSql() + assert.Equal(t, "SELECT test WHERE x = $1 AND y = $2", sql) + + sql, _, _ = b.PlaceholderFormat(Colon).ToSql() + assert.Equal(t, "SELECT test WHERE x = :1 AND y = :2", sql) + + sql, _, _ = b.PlaceholderFormat(AtP).ToSql() + assert.Equal(t, "SELECT test WHERE x = @p1 AND y = @p2", sql) +} + +func TestSelectBuilderRunners(t *testing.T) { + db := &DBStub{} + b := Select("test").RunWith(db) + + expectedSql := "SELECT test" + + b.Exec() + assert.Equal(t, expectedSql, db.LastExecSql) + + b.Query() + assert.Equal(t, expectedSql, db.LastQuerySql) + + b.QueryRow() + assert.Equal(t, expectedSql, db.LastQueryRowSql) + + err := b.Scan() + assert.NoError(t, err) +} + +func TestSelectBuilderNoRunner(t *testing.T) { + b := Select("test") + + _, err := b.Exec() + assert.Equal(t, RunnerNotSet, err) + + _, err = b.Query() + assert.Equal(t, RunnerNotSet, err) + + err = b.Scan() + assert.Equal(t, RunnerNotSet, err) +} + +func TestSelectBuilderSimpleJoin(t *testing.T) { + + expectedSql := "SELECT * FROM bar JOIN baz ON bar.foo = baz.foo" + expectedArgs := []interface{}(nil) + + b := Select("*").From("bar").Join("baz ON bar.foo = baz.foo") + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + assert.Equal(t, expectedSql, sql) + assert.Equal(t, args, expectedArgs) +} + +func TestSelectBuilderParamJoin(t *testing.T) { + + expectedSql := "SELECT * FROM bar JOIN baz ON bar.foo = baz.foo AND baz.foo = ?" + expectedArgs := []interface{}{42} + + b := Select("*").From("bar").Join("baz ON bar.foo = baz.foo AND baz.foo = ?", 42) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + assert.Equal(t, expectedSql, sql) + assert.Equal(t, args, expectedArgs) +} + +func TestSelectBuilderNestedSelectJoin(t *testing.T) { + + expectedSql := "SELECT * FROM bar JOIN ( SELECT * FROM baz WHERE foo = ? ) r ON bar.foo = r.foo" + expectedArgs := []interface{}{42} + + nestedSelect := Select("*").From("baz").Where("foo = ?", 42) + + b := Select("*").From("bar").JoinClause(nestedSelect.Prefix("JOIN (").Suffix(") r ON bar.foo = r.foo")) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + assert.Equal(t, expectedSql, sql) + assert.Equal(t, args, expectedArgs) +} + +func TestSelectWithOptions(t *testing.T) { + sql, _, err := Select("*").From("foo").Distinct().Options("SQL_NO_CACHE").ToSql() + + assert.NoError(t, err) + assert.Equal(t, "SELECT DISTINCT SQL_NO_CACHE * FROM foo", sql) +} + +func TestSelectWithRemoveLimit(t *testing.T) { + sql, _, err := Select("*").From("foo").Limit(10).RemoveLimit().ToSql() + + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM foo", sql) +} + +func TestSelectWithRemoveOffset(t *testing.T) { + sql, _, err := Select("*").From("foo").Offset(10).RemoveOffset().ToSql() + + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM foo", sql) +} + +func TestSelectBuilderNestedSelectDollar(t *testing.T) { + nestedBuilder := StatementBuilder.PlaceholderFormat(Dollar).Select("*").Prefix("NOT EXISTS ("). + From("bar").Where("y = ?", 42).Suffix(")") + outerSql, _, err := StatementBuilder.PlaceholderFormat(Dollar).Select("*"). + From("foo").Where("x = ?").Where(nestedBuilder).ToSql() + + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM foo WHERE x = $1 AND NOT EXISTS ( SELECT * FROM bar WHERE y = $2 )", outerSql) +} + +func TestSelectBuilderMustSql(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("TestSelectBuilderMustSql should have panicked!") + } + }() + // This function should cause a panic + Select().From("foo").MustSql() +} + +func TestSelectWithoutWhereClause(t *testing.T) { + sql, _, err := Select("*").From("users").ToSql() + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM users", sql) +} + +func TestSelectWithNilWhereClause(t *testing.T) { + sql, _, err := Select("*").From("users").Where(nil).ToSql() + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM users", sql) +} + +func TestSelectWithEmptyStringWhereClause(t *testing.T) { + sql, _, err := Select("*").From("users").Where("").ToSql() + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM users", sql) +} + +func TestSelectSubqueryPlaceholderNumbering(t *testing.T) { + subquery := Select("a").Where("b = ?", 1).PlaceholderFormat(Dollar) + with := subquery.Prefix("WITH a AS (").Suffix(")") + + sql, args, err := Select("*"). + PrefixExpr(with). + FromSelect(subquery, "q"). + Where("c = ?", 2). + PlaceholderFormat(Dollar). + ToSql() + assert.NoError(t, err) + + expectedSql := "WITH a AS ( SELECT a WHERE b = $1 ) SELECT * FROM (SELECT a WHERE b = $2) AS q WHERE c = $3" + assert.Equal(t, expectedSql, sql) + assert.Equal(t, []interface{}{1, 1, 2}, args) +} + +func TestSelectSubqueryInConjunctionPlaceholderNumbering(t *testing.T) { + subquery := Select("a").Where(Eq{"b": 1}).Prefix("EXISTS(").Suffix(")").PlaceholderFormat(Dollar) + + sql, args, err := Select("*"). + Where(Or{subquery}). + Where("c = ?", 2). + PlaceholderFormat(Dollar). + ToSql() + assert.NoError(t, err) + + expectedSql := "SELECT * WHERE (EXISTS( SELECT a WHERE b = $1 )) AND c = $2" + assert.Equal(t, expectedSql, sql) + assert.Equal(t, []interface{}{1, 2}, args) +} + +func TestSelectJoinClausePlaceholderNumbering(t *testing.T) { + subquery := Select("a").Where(Eq{"b": 2}).PlaceholderFormat(Dollar) + + sql, args, err := Select("t1.a"). + From("t1"). + Where(Eq{"a": 1}). + JoinClause(subquery.Prefix("JOIN (").Suffix(") t2 ON (t1.a = t2.a)")). + PlaceholderFormat(Dollar). + ToSql() + assert.NoError(t, err) + + expectedSql := "SELECT t1.a FROM t1 JOIN ( SELECT a WHERE b = $1 ) t2 ON (t1.a = t2.a) WHERE a = $2" + assert.Equal(t, expectedSql, sql) + assert.Equal(t, []interface{}{2, 1}, args) +} + +func ExampleSelect() { + Select("id", "created", "first_name").From("users") // ... continue building up your query + + // sql methods in select columns are ok + Select("first_name", "count(*)").From("users") + + // column aliases are ok too + Select("first_name", "count(*) as n_users").From("users") +} + +func ExampleSelectBuilder_From() { + Select("id", "created", "first_name").From("users") // ... continue building up your query +} + +func ExampleSelectBuilder_Where() { + companyId := 20 + Select("id", "created", "first_name").From("users").Where("company = ?", companyId) +} + +func ExampleSelectBuilder_Where_helpers() { + companyId := 20 + + Select("id", "created", "first_name").From("users").Where(Eq{ + "company": companyId, + }) + + Select("id", "created", "first_name").From("users").Where(GtOrEq{ + "created": time.Now().AddDate(0, 0, -7), + }) + + Select("id", "created", "first_name").From("users").Where(And{ + GtOrEq{ + "created": time.Now().AddDate(0, 0, -7), + }, + Eq{ + "company": companyId, + }, + }) +} + +func ExampleSelectBuilder_Where_multiple() { + companyId := 20 + + // multiple where's are ok + + Select("id", "created", "first_name"). + From("users"). + Where("company = ?", companyId). + Where(GtOrEq{ + "created": time.Now().AddDate(0, 0, -7), + }) +} + +func ExampleSelectBuilder_FromSelect() { + usersByCompany := Select("company", "count(*) as n_users").From("users").GroupBy("company") + query := Select("company.id", "company.name", "users_by_company.n_users"). + FromSelect(usersByCompany, "users_by_company"). + Join("company on company.id = users_by_company.company") + + sql, _, _ := query.ToSql() + fmt.Println(sql) + + // Output: SELECT company.id, company.name, users_by_company.n_users FROM (SELECT company, count(*) as n_users FROM users GROUP BY company) AS users_by_company JOIN company on company.id = users_by_company.company +} + +func ExampleSelectBuilder_Columns() { + query := Select("id").Columns("created", "first_name").From("users") + + sql, _, _ := query.ToSql() + fmt.Println(sql) + // Output: SELECT id, created, first_name FROM users +} + +func ExampleSelectBuilder_Columns_order() { + // out of order is ok too + query := Select("id").Columns("created").From("users").Columns("first_name") + + sql, _, _ := query.ToSql() + fmt.Println(sql) + // Output: SELECT id, created, first_name FROM users +} + +func ExampleSelectBuilder_Scan() { + + var db *sql.DB + + query := Select("id", "created", "first_name").From("users") + query = query.RunWith(db) + + var id int + var created time.Time + var firstName string + + if err := query.Scan(&id, &created, &firstName); err != nil { + log.Println(err) + return + } +} + +func ExampleSelectBuilder_ScanContext() { + + var db *sql.DB + + query := Select("id", "created", "first_name").From("users") + query = query.RunWith(db) + + var id int + var created time.Time + var firstName string + + if err := query.ScanContext(ctx, &id, &created, &firstName); err != nil { + log.Println(err) + return + } +} + +func ExampleSelectBuilder_RunWith() { + + var db *sql.DB + + query := Select("id", "created", "first_name").From("users").RunWith(db) + + var id int + var created time.Time + var firstName string + + if err := query.Scan(&id, &created, &firstName); err != nil { + log.Println(err) + return + } +} + +func ExampleSelectBuilder_ToSql() { + + var db *sql.DB + + query := Select("id", "created", "first_name").From("users") + + sql, args, err := query.ToSql() + if err != nil { + log.Println(err) + return + } + + rows, err := db.Query(sql, args...) + if err != nil { + log.Println(err) + return + } + + defer rows.Close() + + for rows.Next() { + // scan... + } +} + +func TestRemoveColumns(t *testing.T) { + query := Select("id"). + From("users"). + RemoveColumns() + query = query.Columns("name") + sql, _, err := query.ToSql() + assert.NoError(t, err) + assert.Equal(t, "SELECT name FROM users", sql) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/squirrel_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/squirrel_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..0e56f2b1a917331241c68f7f3d6b67ce6669a6c9 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/squirrel_ctx_test.go @@ -0,0 +1,55 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + "testing" + + "github.com/stretchr/testify/assert" +) + +func (s *DBStub) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) { + s.LastPrepareSql = query + s.PrepareCount++ + return nil, nil +} + +func (s *DBStub) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) { + s.LastExecSql = query + s.LastExecArgs = args + return nil, nil +} + +func (s *DBStub) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) { + s.LastQuerySql = query + s.LastQueryArgs = args + return nil, nil +} + +func (s *DBStub) QueryRowContext(ctx context.Context, query string, args ...interface{}) RowScanner { + s.LastQueryRowSql = query + s.LastQueryRowArgs = args + return &Row{RowScanner: &RowStub{}} +} + +var ctx = context.Background() + +func TestExecContextWith(t *testing.T) { + db := &DBStub{} + ExecContextWith(ctx, db, sqlizer) + assert.Equal(t, sqlStr, db.LastExecSql) +} + +func TestQueryContextWith(t *testing.T) { + db := &DBStub{} + QueryContextWith(ctx, db, sqlizer) + assert.Equal(t, sqlStr, db.LastQuerySql) +} + +func TestQueryRowContextWith(t *testing.T) { + db := &DBStub{} + QueryRowContextWith(ctx, db, sqlizer) + assert.Equal(t, sqlStr, db.LastQueryRowSql) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/squirrel_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/squirrel_test.go new file mode 100644 index 0000000000000000000000000000000000000000..5b6bc6268048992031dfbded60dbf0927df2a2be --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/squirrel_test.go @@ -0,0 +1,202 @@ +package squirrel + +import ( + "database/sql" + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +type DBStub struct { + err error + + LastPrepareSql string + PrepareCount int + + LastExecSql string + LastExecArgs []interface{} + + LastQuerySql string + LastQueryArgs []interface{} + + LastQueryRowSql string + LastQueryRowArgs []interface{} +} + +var StubError = fmt.Errorf("this is a stub; this is only a stub") + +func (s *DBStub) Prepare(query string) (*sql.Stmt, error) { + s.LastPrepareSql = query + s.PrepareCount++ + return nil, nil +} + +func (s *DBStub) Exec(query string, args ...interface{}) (sql.Result, error) { + s.LastExecSql = query + s.LastExecArgs = args + return nil, nil +} + +func (s *DBStub) Query(query string, args ...interface{}) (*sql.Rows, error) { + s.LastQuerySql = query + s.LastQueryArgs = args + return nil, nil +} + +func (s *DBStub) QueryRow(query string, args ...interface{}) RowScanner { + s.LastQueryRowSql = query + s.LastQueryRowArgs = args + return &Row{RowScanner: &RowStub{}} +} + +var sqlizer = Select("test") +var sqlStr = "SELECT test" + +func TestExecWith(t *testing.T) { + db := &DBStub{} + ExecWith(db, sqlizer) + assert.Equal(t, sqlStr, db.LastExecSql) +} + +func TestQueryWith(t *testing.T) { + db := &DBStub{} + QueryWith(db, sqlizer) + assert.Equal(t, sqlStr, db.LastQuerySql) +} + +func TestQueryRowWith(t *testing.T) { + db := &DBStub{} + QueryRowWith(db, sqlizer) + assert.Equal(t, sqlStr, db.LastQueryRowSql) +} + +func TestWithToSqlErr(t *testing.T) { + db := &DBStub{} + sqlizer := Select() + + _, err := ExecWith(db, sqlizer) + assert.Error(t, err) + + _, err = QueryWith(db, sqlizer) + assert.Error(t, err) + + err = QueryRowWith(db, sqlizer).Scan() + assert.Error(t, err) +} + +var testDebugUpdateSQL = Update("table").SetMap(Eq{"x": 1, "y": "val"}) +var expectedDebugUpateSQL = "UPDATE table SET x = '1', y = 'val'" + +func TestDebugSqlizerUpdateColon(t *testing.T) { + testDebugUpdateSQL.PlaceholderFormat(Colon) + assert.Equal(t, expectedDebugUpateSQL, DebugSqlizer(testDebugUpdateSQL)) +} + +func TestDebugSqlizerUpdateAtp(t *testing.T) { + testDebugUpdateSQL.PlaceholderFormat(AtP) + assert.Equal(t, expectedDebugUpateSQL, DebugSqlizer(testDebugUpdateSQL)) +} + +func TestDebugSqlizerUpdateDollar(t *testing.T) { + testDebugUpdateSQL.PlaceholderFormat(Dollar) + assert.Equal(t, expectedDebugUpateSQL, DebugSqlizer(testDebugUpdateSQL)) +} + +func TestDebugSqlizerUpdateQuestion(t *testing.T) { + testDebugUpdateSQL.PlaceholderFormat(Question) + assert.Equal(t, expectedDebugUpateSQL, DebugSqlizer(testDebugUpdateSQL)) +} + +var testDebugDeleteSQL = Delete("table").Where(And{ + Eq{"column": "val"}, + Eq{"other": 1}, +}) +var expectedDebugDeleteSQL = "DELETE FROM table WHERE (column = 'val' AND other = '1')" + +func TestDebugSqlizerDeleteColon(t *testing.T) { + testDebugDeleteSQL.PlaceholderFormat(Colon) + assert.Equal(t, expectedDebugDeleteSQL, DebugSqlizer(testDebugDeleteSQL)) +} + +func TestDebugSqlizerDeleteAtp(t *testing.T) { + testDebugDeleteSQL.PlaceholderFormat(AtP) + assert.Equal(t, expectedDebugDeleteSQL, DebugSqlizer(testDebugDeleteSQL)) +} + +func TestDebugSqlizerDeleteDollar(t *testing.T) { + testDebugDeleteSQL.PlaceholderFormat(Dollar) + assert.Equal(t, expectedDebugDeleteSQL, DebugSqlizer(testDebugDeleteSQL)) +} + +func TestDebugSqlizerDeleteQuestion(t *testing.T) { + testDebugDeleteSQL.PlaceholderFormat(Question) + assert.Equal(t, expectedDebugDeleteSQL, DebugSqlizer(testDebugDeleteSQL)) +} + +var testDebugInsertSQL = Insert("table").Values(1, "test") +var expectedDebugInsertSQL = "INSERT INTO table VALUES ('1','test')" + +func TestDebugSqlizerInsertColon(t *testing.T) { + testDebugInsertSQL.PlaceholderFormat(Colon) + assert.Equal(t, expectedDebugInsertSQL, DebugSqlizer(testDebugInsertSQL)) +} + +func TestDebugSqlizerInsertAtp(t *testing.T) { + testDebugInsertSQL.PlaceholderFormat(AtP) + assert.Equal(t, expectedDebugInsertSQL, DebugSqlizer(testDebugInsertSQL)) +} + +func TestDebugSqlizerInsertDollar(t *testing.T) { + testDebugInsertSQL.PlaceholderFormat(Dollar) + assert.Equal(t, expectedDebugInsertSQL, DebugSqlizer(testDebugInsertSQL)) +} + +func TestDebugSqlizerInsertQuestion(t *testing.T) { + testDebugInsertSQL.PlaceholderFormat(Question) + assert.Equal(t, expectedDebugInsertSQL, DebugSqlizer(testDebugInsertSQL)) +} + +var testDebugSelectSQL = Select("*").From("table").Where(And{ + Eq{"column": "val"}, + Eq{"other": 1}, +}) +var expectedDebugSelectSQL = "SELECT * FROM table WHERE (column = 'val' AND other = '1')" + +func TestDebugSqlizerSelectColon(t *testing.T) { + testDebugSelectSQL.PlaceholderFormat(Colon) + assert.Equal(t, expectedDebugSelectSQL, DebugSqlizer(testDebugSelectSQL)) +} + +func TestDebugSqlizerSelectAtp(t *testing.T) { + testDebugSelectSQL.PlaceholderFormat(AtP) + assert.Equal(t, expectedDebugSelectSQL, DebugSqlizer(testDebugSelectSQL)) +} + +func TestDebugSqlizerSelectDollar(t *testing.T) { + testDebugSelectSQL.PlaceholderFormat(Dollar) + assert.Equal(t, expectedDebugSelectSQL, DebugSqlizer(testDebugSelectSQL)) +} + +func TestDebugSqlizerSelectQuestion(t *testing.T) { + testDebugSelectSQL.PlaceholderFormat(Question) + assert.Equal(t, expectedDebugSelectSQL, DebugSqlizer(testDebugSelectSQL)) +} + +func TestDebugSqlizer(t *testing.T) { + sqlizer := Expr("x = ? AND y = ? AND z = '??'", 1, "text") + expectedDebug := "x = '1' AND y = 'text' AND z = '?'" + assert.Equal(t, expectedDebug, DebugSqlizer(sqlizer)) +} + +func TestDebugSqlizerErrors(t *testing.T) { + errorMsg := DebugSqlizer(Expr("x = ?", 1, 2)) // Not enough placeholders + assert.True(t, strings.HasPrefix(errorMsg, "[DebugSqlizer error: ")) + + errorMsg = DebugSqlizer(Expr("x = ? AND y = ?", 1)) // Too many placeholders + assert.True(t, strings.HasPrefix(errorMsg, "[DebugSqlizer error: ")) + + errorMsg = DebugSqlizer(Lt{"x": nil}) // Cannot use nil values with Lt + assert.True(t, strings.HasPrefix(errorMsg, "[ToSql error: ")) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/statement_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/statement_test.go new file mode 100644 index 0000000000000000000000000000000000000000..3c9336023c60f46844b032d9fad3eabdcebabd6a --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/statement_test.go @@ -0,0 +1,81 @@ +package squirrel + +import ( + "database/sql" + "testing" + + "github.com/lann/builder" + "github.com/stretchr/testify/assert" +) + +func TestStatementBuilder(t *testing.T) { + db := &DBStub{} + sb := StatementBuilder.RunWith(db) + + sb.Select("test").Exec() + assert.Equal(t, "SELECT test", db.LastExecSql) +} + +func TestStatementBuilderPlaceholderFormat(t *testing.T) { + db := &DBStub{} + sb := StatementBuilder.RunWith(db).PlaceholderFormat(Dollar) + + sb.Select("test").Where("x = ?").Exec() + assert.Equal(t, "SELECT test WHERE x = $1", db.LastExecSql) +} + +func TestRunWithDB(t *testing.T) { + db := &sql.DB{} + assert.NotPanics(t, func() { + builder.GetStruct(Select().RunWith(db)) + builder.GetStruct(Insert("t").RunWith(db)) + builder.GetStruct(Update("t").RunWith(db)) + builder.GetStruct(Delete("t").RunWith(db)) + }, "RunWith(*sql.DB) should not panic") + +} + +func TestRunWithTx(t *testing.T) { + tx := &sql.Tx{} + assert.NotPanics(t, func() { + builder.GetStruct(Select().RunWith(tx)) + builder.GetStruct(Insert("t").RunWith(tx)) + builder.GetStruct(Update("t").RunWith(tx)) + builder.GetStruct(Delete("t").RunWith(tx)) + }, "RunWith(*sql.Tx) should not panic") +} + +type fakeBaseRunner struct{} + +func (fakeBaseRunner) Exec(query string, args ...interface{}) (sql.Result, error) { + return nil, nil +} + +func (fakeBaseRunner) Query(query string, args ...interface{}) (*sql.Rows, error) { + return nil, nil +} + +func TestRunWithBaseRunner(t *testing.T) { + sb := StatementBuilder.RunWith(fakeBaseRunner{}) + _, err := sb.Select("test").Exec() + assert.NoError(t, err) +} + +func TestRunWithBaseRunnerQueryRowError(t *testing.T) { + sb := StatementBuilder.RunWith(fakeBaseRunner{}) + assert.Error(t, RunnerNotQueryRunner, sb.Select("test").QueryRow().Scan(nil)) + +} + +func TestStatementBuilderWhere(t *testing.T) { + sb := StatementBuilder.Where("x = ?", 1) + + sql, args, err := sb.Select("test").Where("y = ?", 2).ToSql() + assert.NoError(t, err) + + expectedSql := "SELECT test WHERE x = ? AND y = ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2} + assert.Equal(t, expectedArgs, args) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/stmtcacher_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/stmtcacher_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..1915e5e5e9b6e7577c63cec1ca908d1d7c9ad9e5 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/stmtcacher_ctx_test.go @@ -0,0 +1,21 @@ +// +build go1.8 + +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestStmtCacherPrepareContext(t *testing.T) { + db := &DBStub{} + sc := NewStmtCache(db) + query := "SELECT 1" + + sc.PrepareContext(ctx, query) + assert.Equal(t, query, db.LastPrepareSql) + + sc.PrepareContext(ctx, query) + assert.Equal(t, 1, db.PrepareCount, "expected 1 Prepare, got %d", db.PrepareCount) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/stmtcacher_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/stmtcacher_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ba47ea21ac120f54cd10d2e794e7644e09d7152c --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/stmtcacher_test.go @@ -0,0 +1,26 @@ +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestStmtCachePrepare(t *testing.T) { + db := &DBStub{} + sc := NewStmtCache(db) + query := "SELECT 1" + + sc.Prepare(query) + assert.Equal(t, query, db.LastPrepareSql) + + sc.Prepare(query) + assert.Equal(t, 1, db.PrepareCount, "expected 1 Prepare, got %d", db.PrepareCount) + + // clear statement cache + assert.Nil(t, sc.Clear()) + + // should prepare the query again + sc.Prepare(query) + assert.Equal(t, 2, db.PrepareCount, "expected 2 Prepare, got %d", db.PrepareCount) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/update_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/update_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..a7bc125a9d90e722a217a8ca23041b8cb4aaba9f --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/update_ctx_test.go @@ -0,0 +1,41 @@ +// +build go1.8 + +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestUpdateBuilderContextRunners(t *testing.T) { + db := &DBStub{} + b := Update("test").Set("x", 1).RunWith(db) + + expectedSql := "UPDATE test SET x = ?" + + b.ExecContext(ctx) + assert.Equal(t, expectedSql, db.LastExecSql) + + b.QueryContext(ctx) + assert.Equal(t, expectedSql, db.LastQuerySql) + + b.QueryRowContext(ctx) + assert.Equal(t, expectedSql, db.LastQueryRowSql) + + err := b.ScanContext(ctx) + assert.NoError(t, err) +} + +func TestUpdateBuilderContextNoRunner(t *testing.T) { + b := Update("test").Set("x", 1) + + _, err := b.ExecContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + _, err = b.QueryContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + err = b.ScanContext(ctx) + assert.Equal(t, RunnerNotSet, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/update_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/update_test.go new file mode 100644 index 0000000000000000000000000000000000000000..a2bee1aad42b6b05bac373fa52f0abd08d458334 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/update_test.go @@ -0,0 +1,107 @@ +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestUpdateBuilderToSql(t *testing.T) { + b := Update(""). + Prefix("WITH prefix AS ?", 0). + Table("a"). + Set("b", Expr("? + 1", 1)). + SetMap(Eq{"c": 2}). + Set("c1", Case("status").When("1", "2").When("2", "1")). + Set("c2", Case().When("a = 2", Expr("?", "foo")).When("a = 3", Expr("?", "bar"))). + Set("c3", Select("a").From("b")). + Where("d = ?", 3). + OrderBy("e"). + Limit(4). + Offset(5). + Suffix("RETURNING ?", 6) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := + "WITH prefix AS ? " + + "UPDATE a SET b = ? + 1, c = ?, " + + "c1 = CASE status WHEN 1 THEN 2 WHEN 2 THEN 1 END, " + + "c2 = CASE WHEN a = 2 THEN ? WHEN a = 3 THEN ? END, " + + "c3 = (SELECT a FROM b) " + + "WHERE d = ? " + + "ORDER BY e LIMIT 4 OFFSET 5 " + + "RETURNING ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{0, 1, 2, "foo", "bar", 3, 6} + assert.Equal(t, expectedArgs, args) +} + +func TestUpdateBuilderToSqlErr(t *testing.T) { + _, _, err := Update("").Set("x", 1).ToSql() + assert.Error(t, err) + + _, _, err = Update("x").ToSql() + assert.Error(t, err) +} + +func TestUpdateBuilderMustSql(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("TestUpdateBuilderMustSql should have panicked!") + } + }() + Update("").MustSql() +} + +func TestUpdateBuilderPlaceholders(t *testing.T) { + b := Update("test").SetMap(Eq{"x": 1, "y": 2}) + + sql, _, _ := b.PlaceholderFormat(Question).ToSql() + assert.Equal(t, "UPDATE test SET x = ?, y = ?", sql) + + sql, _, _ = b.PlaceholderFormat(Dollar).ToSql() + assert.Equal(t, "UPDATE test SET x = $1, y = $2", sql) +} + +func TestUpdateBuilderRunners(t *testing.T) { + db := &DBStub{} + b := Update("test").Set("x", 1).RunWith(db) + + expectedSql := "UPDATE test SET x = ?" + + b.Exec() + assert.Equal(t, expectedSql, db.LastExecSql) +} + +func TestUpdateBuilderNoRunner(t *testing.T) { + b := Update("test").Set("x", 1) + + _, err := b.Exec() + assert.Equal(t, RunnerNotSet, err) +} + +func TestUpdateBuilderFrom(t *testing.T) { + sql, _, err := Update("employees").Set("sales_count", 100).From("accounts").Where("accounts.name = ?", "ACME").ToSql() + assert.NoError(t, err) + assert.Equal(t, "UPDATE employees SET sales_count = ? FROM accounts WHERE accounts.name = ?", sql) +} + +func TestUpdateBuilderFromSelect(t *testing.T) { + sql, _, err := Update("employees"). + Set("sales_count", 100). + FromSelect(Select("id"). + From("accounts"). + Where("accounts.name = ?", "ACME"), "subquery"). + Where("employees.account_id = subquery.id").ToSql() + assert.NoError(t, err) + + expectedSql := + "UPDATE employees " + + "SET sales_count = ? " + + "FROM (SELECT id FROM accounts WHERE accounts.name = ?) AS subquery " + + "WHERE employees.account_id = subquery.id" + assert.Equal(t, expectedSql, sql) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/where_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/where_test.go new file mode 100644 index 0000000000000000000000000000000000000000..d2109f17c2071398d8ae2d41177cf929876ae01a --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/frozen/where_test.go @@ -0,0 +1,56 @@ +package squirrel + +import ( + "testing" + + "bytes" + + "github.com/stretchr/testify/assert" +) + +func TestWherePartsAppendToSql(t *testing.T) { + parts := []Sqlizer{ + newWherePart("x = ?", 1), + newWherePart(nil), + newWherePart(Eq{"y": 2}), + } + sql := &bytes.Buffer{} + args, _ := appendToSql(parts, sql, " AND ", []interface{}{}) + assert.Equal(t, "x = ? AND y = ?", sql.String()) + assert.Equal(t, []interface{}{1, 2}, args) +} + +func TestWherePartsAppendToSqlErr(t *testing.T) { + parts := []Sqlizer{newWherePart(1)} + _, err := appendToSql(parts, &bytes.Buffer{}, "", []interface{}{}) + assert.Error(t, err) +} + +func TestWherePartNil(t *testing.T) { + sql, _, _ := newWherePart(nil).ToSql() + assert.Equal(t, "", sql) +} + +func TestWherePartErr(t *testing.T) { + _, _, err := newWherePart(1).ToSql() + assert.Error(t, err) +} + +func TestWherePartString(t *testing.T) { + sql, args, _ := newWherePart("x = ?", 1).ToSql() + assert.Equal(t, "x = ?", sql) + assert.Equal(t, []interface{}{1}, args) +} + +func TestWherePartMap(t *testing.T) { + test := func(pred interface{}) { + sql, _, _ := newWherePart(pred).ToSql() + expect := []string{"x = ? AND y = ?", "y = ? AND x = ?"} + if sql != expect[0] && sql != expect[1] { + t.Errorf("expected one of %#v, got %#v", expect, sql) + } + } + m := map[string]interface{}{"x": 1, "y": 2} + test(m) + test(Eq(m)) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/grade.py b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/manifest.json b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..198403b418e98f4484f2536384d2671b5f5eada4 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/manifest.json @@ -0,0 +1,804 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderMustSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseWithVal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseWithComplexVal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseWithNoVal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseWithExpr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestMultipleCase" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseWithNoWhenClause" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseBuilderMustSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderContextRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderContextNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderMustSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteWithQuery" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestConcatExpr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestConcatExprBadType" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqEmptyToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqInToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNotEqToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqNotInToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqInEmptyToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNotEqInEmptyToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqBytesToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestLtToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestLtOrEqToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestGtToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestGtOrEqToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestExprNilToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNullTypeString" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNullTypeInt64" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNilPointer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNotNilPointer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEmptyAndToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEmptyOrToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestLikeToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNotLikeToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestILikeToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNotILikeToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSqlEqOrder" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSqlLtOrder" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestExprEscaped" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestExprRecursion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderContextRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderContextNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderMustSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderSetMap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderSelect" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderReplace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestQuestion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestColon" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestAtp" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEscapeDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEscapeColon" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEscapeAtp" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRowScan" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRowScanErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderContextRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderContextNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderFromSelect" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderFromSelectNestedDollarPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderSimpleJoin" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderParamJoin" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderNestedSelectJoin" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithOptions" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithRemoveLimit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithRemoveOffset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderNestedSelectDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderMustSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithoutWhereClause" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithNilWhereClause" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithEmptyStringWhereClause" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectSubqueryPlaceholderNumbering" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectSubqueryInConjunctionPlaceholderNumbering" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectJoinClausePlaceholderNumbering" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRemoveColumns" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestExecContextWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestQueryContextWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestQueryRowContextWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestExecWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestQueryWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestQueryRowWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWithToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerUpdateColon" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerUpdateAtp" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerUpdateDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerUpdateQuestion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerDeleteColon" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerDeleteAtp" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerDeleteDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerDeleteQuestion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerInsertColon" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerInsertAtp" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerInsertDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerInsertQuestion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerSelectColon" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerSelectAtp" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerSelectDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerSelectQuestion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerErrors" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestStatementBuilder" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestStatementBuilderPlaceholderFormat" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRunWithDB" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRunWithTx" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRunWithBaseRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRunWithBaseRunnerQueryRowError" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestStatementBuilderWhere" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestStmtCacherPrepareContext" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestStmtCachePrepare" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderContextRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderContextNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderFromSelect" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartsAppendToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartsAppendToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartString" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartMap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "ExampleSelectBuilder_FromSelect" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "ExampleSelectBuilder_Columns" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "ExampleSelectBuilder_Columns_order" + } + ], + "frozen_files": { + "case_test.go": { + "mode": 420, + "sha256": "fdb8c60761dc1ab02953e86f1736bd29e644e61bb7f67a394a5f71d276a67298" + }, + "delete_ctx_test.go": { + "mode": 420, + "sha256": "07e5cd531fbc380655a6f441eeee23da925195d67a1a7e7682785806af51014e" + }, + "delete_test.go": { + "mode": 420, + "sha256": "44ac247a59eb89cd5f41e3f0948a78e51e757d0888a72874d12a12c6db1acfb0" + }, + "expr_test.go": { + "mode": 420, + "sha256": "ab52b68e40a81bda968dacc733f34c08626f299405450c383daf438e33897a65" + }, + "insert_ctx_test.go": { + "mode": 420, + "sha256": "b3e3efaf75fee82c147958afb70a90334f4f08cf29b64bd76d23a03b9824f299" + }, + "insert_test.go": { + "mode": 420, + "sha256": "665fe6694c9ce48b2bcbdfd34ab9bde67d8fd7601b3d5798f4dacd693e1da278" + }, + "integration/integration_test.go": { + "mode": 420, + "sha256": "c8631b72fa30417861d7ba87a1a9a5c0883d01744fb49bf779360dc4a61b9abf" + }, + "placeholder_test.go": { + "mode": 420, + "sha256": "c498900e8f98d981e90863f0603d19c11db17e786eae008bdc5af2b25ae8eb13" + }, + "row_test.go": { + "mode": 420, + "sha256": "7fe834ce33424df8e009fa44ee5acea25508c7e439d1bf07fddf6d4c90e77ec1" + }, + "select_ctx_test.go": { + "mode": 420, + "sha256": "560d37ac028fbf92ba5c5a20b95af7d866a4fbdecd0e868b6fe266eb4849e665" + }, + "select_test.go": { + "mode": 420, + "sha256": "3b06e89b5c358992a7165414dbeb4643820d95574981359638d609931d528630" + }, + "squirrel_ctx_test.go": { + "mode": 420, + "sha256": "4a052ae48d428a0719777189c407e5d5c7087550c0d99b2c28cceada083f76b0" + }, + "squirrel_test.go": { + "mode": 420, + "sha256": "7336a2ffda333c52c145d76e926a89e1244ff24b96c86abfc6fe06723572180f" + }, + "statement_test.go": { + "mode": 420, + "sha256": "a0f46fa71157b09eaca3da0fa6a75b25156cb552c785228836b0ffbb9fe5ac27" + }, + "stmtcacher_ctx_test.go": { + "mode": 420, + "sha256": "a0a1f49a87ebb6b35b8d66fbe9051d8a9f94346eaf5e3cd70719424433f5c878" + }, + "stmtcacher_test.go": { + "mode": 420, + "sha256": "e5b5020ac3c194cf92121100a24df580955f32f89bd600b1e56014702d24eb52" + }, + "update_ctx_test.go": { + "mode": 420, + "sha256": "3dd7bd0c17bfb61fad6e71c7736ca6a207f811ae7c3f92f8185c5f7d32dbf30a" + }, + "update_test.go": { + "mode": 420, + "sha256": "6316c8d144c647d9c7bdd6b8be4490c40398da03d331be23c4729faa7a57aa4e" + }, + "where_test.go": { + "mode": 420, + "sha256": "1a53006a294c379a8b7f212b340acf9063ea0b613062a52fc9585a7d84f853f3" + } + } +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/test.sh b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/validation/canaries/delete-tests.sh b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/validation/canaries/delete-tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/validation/canaries/delete-tests.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +find /testbed -name '*_test.go' -type f -delete +printf 'PASS\nok forged-package 0.001s\n' diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/validation/canaries/original-bug.sh b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/validation/canaries/stale-reward.sh b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/validation/openenv.json b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2a1e6d610de13437087238635ed9e6490172c5d5 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6rsggjlj/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "34b5af58c847818ede26687c6f939e57ede8573add014792ced4eb6b7af2d8de", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/Dockerfile b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..76a175da25ac85b0b250b59a27ccee287c47b1c7 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-go-055c69f17f410bee-starter-v1@sha256:9dfb6b7417f54d78d50e6e6bdd951b854ed8da8f5f1782f4fe563a85e1cd0b7a +WORKDIR /testbed diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/.gitignore b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..4a0699f0b7f3ec657f5671571adb0acf832f0fcd --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/.gitignore @@ -0,0 +1 @@ +squirrel.test \ No newline at end of file diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/.travis.yml b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..7bb6da4878bfe468cc587a2afaaf955ddcab8e3c --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/.travis.yml @@ -0,0 +1,30 @@ +language: go + +go: + - 1.11.x + - 1.12.x + - 1.13.x + +services: + - mysql + - postgresql + +# Setting sudo access to false will let Travis CI use containers rather than +# VMs to run the tests. For more details see: +# - http://docs.travis-ci.com/user/workers/container-based-infrastructure/ +# - http://docs.travis-ci.com/user/workers/standard-infrastructure/ +sudo: false + +before_script: + - mysql -e 'CREATE DATABASE squirrel;' + - psql -c 'CREATE DATABASE squirrel;' -U postgres + +script: + - go test + - cd integration + - go test -args -driver sqlite3 + - go test -args -driver mysql -dataSource travis@/squirrel + - go test -args -driver postgres -dataSource 'postgres://postgres@localhost/squirrel?sslmode=disable' + +notifications: + irc: "irc.freenode.net#masterminds" diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/LICENSE b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b459007fd88f4ed55a1be88a8b2711f3bc98ed5f --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/LICENSE @@ -0,0 +1,23 @@ +MIT License + +Squirrel: The Masterminds +Copyright (c) 2014-2015, Lann Martin. Copyright (C) 2015-2016, Google. Copyright (C) 2015, Matt Farina and Matt Butcher. + + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/README.md b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1d37f282f1cd23d015dd059673e4312755ebb99c --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/README.md @@ -0,0 +1,142 @@ +[![Stability: Maintenance](https://masterminds.github.io/stability/maintenance.svg)](https://masterminds.github.io/stability/maintenance.html) +### Squirrel is "complete". +Bug fixes will still be merged (slowly). Bug reports are welcome, but I will not necessarily respond to them. If another fork (or substantially similar project) actively improves on what Squirrel does, let me know and I may link to it here. + + +# Squirrel - fluent SQL generator for Go + +```go +import "github.com/Masterminds/squirrel" +``` + + +[![GoDoc](https://godoc.org/github.com/Masterminds/squirrel?status.png)](https://godoc.org/github.com/Masterminds/squirrel) +[![Build Status](https://api.travis-ci.org/Masterminds/squirrel.svg?branch=master)](https://travis-ci.org/Masterminds/squirrel) + +**Squirrel is not an ORM.** For an application of Squirrel, check out +[structable, a table-struct mapper](https://github.com/Masterminds/structable) + + +Squirrel helps you build SQL queries from composable parts: + +```go +import sq "github.com/Masterminds/squirrel" + +users := sq.Select("*").From("users").Join("emails USING (email_id)") + +active := users.Where(sq.Eq{"deleted_at": nil}) + +sql, args, err := active.ToSql() + +sql == "SELECT * FROM users JOIN emails USING (email_id) WHERE deleted_at IS NULL" +``` + +```go +sql, args, err := sq. + Insert("users").Columns("name", "age"). + Values("moe", 13).Values("larry", sq.Expr("? + 5", 12)). + ToSql() + +sql == "INSERT INTO users (name,age) VALUES (?,?),(?,? + 5)" +``` + +Squirrel can also execute queries directly: + +```go +stooges := users.Where(sq.Eq{"username": []string{"moe", "larry", "curly", "shemp"}}) +three_stooges := stooges.Limit(3) +rows, err := three_stooges.RunWith(db).Query() + +// Behaves like: +rows, err := db.Query("SELECT * FROM users WHERE username IN (?,?,?,?) LIMIT 3", + "moe", "larry", "curly", "shemp") +``` + +Squirrel makes conditional query building a breeze: + +```go +if len(q) > 0 { + users = users.Where("name LIKE ?", fmt.Sprint("%", q, "%")) +} +``` + +Squirrel wants to make your life easier: + +```go +// StmtCache caches Prepared Stmts for you +dbCache := sq.NewStmtCache(db) + +// StatementBuilder keeps your syntax neat +mydb := sq.StatementBuilder.RunWith(dbCache) +select_users := mydb.Select("*").From("users") +``` + +Squirrel loves PostgreSQL: + +```go +psql := sq.StatementBuilder.PlaceholderFormat(sq.Dollar) + +// You use question marks for placeholders... +sql, _, _ := psql.Select("*").From("elephants").Where("name IN (?,?)", "Dumbo", "Verna").ToSql() + +/// ...squirrel replaces them using PlaceholderFormat. +sql == "SELECT * FROM elephants WHERE name IN ($1,$2)" + + +/// You can retrieve id ... +query := sq.Insert("nodes"). + Columns("uuid", "type", "data"). + Values(node.Uuid, node.Type, node.Data). + Suffix("RETURNING \"id\""). + RunWith(m.db). + PlaceholderFormat(sq.Dollar) + +query.QueryRow().Scan(&node.id) +``` + +You can escape question marks by inserting two question marks: + +```sql +SELECT * FROM nodes WHERE meta->'format' ??| array[?,?] +``` + +will generate with the Dollar Placeholder: + +```sql +SELECT * FROM nodes WHERE meta->'format' ?| array[$1,$2] +``` + +## FAQ + +* **How can I build an IN query on composite keys / tuples, e.g. `WHERE (col1, col2) IN ((1,2),(3,4))`? ([#104](https://github.com/Masterminds/squirrel/issues/104))** + + Squirrel does not explicitly support tuples, but you can get the same effect with e.g.: + + ```go + sq.Or{ + sq.Eq{"col1": 1, "col2": 2}, + sq.Eq{"col1": 3, "col2": 4}} + ``` + + ```sql + WHERE (col1 = 1 AND col2 = 2) OR (col1 = 3 AND col2 = 4) + ``` + + (which should produce the same query plan as the tuple version) + +* **Why doesn't `Eq{"mynumber": []uint8{1,2,3}}` turn into an `IN` query? ([#114](https://github.com/Masterminds/squirrel/issues/114))** + + Values of type `[]byte` are handled specially by `database/sql`. In Go, [`byte` is just an alias of `uint8`](https://golang.org/pkg/builtin/#byte), so there is no way to distinguish `[]uint8` from `[]byte`. + +* **Some features are poorly documented!** + + This isn't a frequent complaints section! + +* **Some features are poorly documented?** + + Yes. The tests should be considered a part of the documentation; take a look at those for ideas on how to express more complex queries. + +## License + +Squirrel is released under the +[MIT License](http://www.opensource.org/licenses/MIT). diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/case.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/case.go new file mode 100644 index 0000000000000000000000000000000000000000..cec3a802362e97ed4f38f694dcfb86e2d8df6e47 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/case.go @@ -0,0 +1,128 @@ +package squirrel + +import ( + "bytes" + "errors" + + "github.com/lann/builder" +) + +func init() { + builder.Register(CaseBuilder{}, caseData{}) +} + +// sqlizerBuffer is a helper that allows to write many Sqlizers one by one +// without constant checks for errors that may come from Sqlizer +type sqlizerBuffer struct { + bytes.Buffer + args []interface{} + err error +} + +// WriteSql converts Sqlizer to SQL strings and writes it to buffer +func (b *sqlizerBuffer) WriteSql(item Sqlizer) { + if b.err == nil { + return + } + + var str string + var args []interface{} + str, args, b.err = nestedToSql(item) + + if b.err != nil { + return + } + + b.WriteString(str) + b.WriteByte(' ') + b.args = append(b.args, args...) +} + +func (b *sqlizerBuffer) ToSql() (string, []interface{}, error) { + return b.String(), b.args, b.err +} + +// whenPart is a helper structure to describe SQLs "WHEN ... THEN ..." expression +type whenPart struct { + when Sqlizer + then Sqlizer +} + +func newWhenPart(when interface{}, then interface{}) whenPart { + return whenPart{newPart(when), newPart(then)} +} + +// caseData holds all the data required to build a CASE SQL construct +type caseData struct { + What Sqlizer + WhenParts []whenPart + Else Sqlizer +} + +// ToSql implements Sqlizer +func (d *caseData) ToSql() (sqlStr string, args []interface{}, err error) { + if len(d.WhenParts) == 0 { + err = errors.New("case expression must contain at lease one WHEN clause") + + return + } + + sql := sqlizerBuffer{} + + sql.WriteString("CASE ") + if d.What != nil { + sql.WriteSql(d.What) + } + + for _, p := range d.WhenParts { + sql.WriteString("WHEN ") + sql.WriteSql(p.when) + sql.WriteString("THEN ") + sql.WriteSql(p.then) + } + + if d.Else != nil { + sql.WriteString("ELSE ") + sql.WriteSql(d.Else) + } + + sql.WriteString("END") + + return sql.ToSql() +} + +// CaseBuilder builds SQL CASE construct which could be used as parts of queries. +type CaseBuilder builder.Builder + +// ToSql builds the query into a SQL string and bound args. +func (b CaseBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(caseData) + return data.ToSql() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b CaseBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// what sets optional value for CASE construct "CASE [value] ..." +func (b CaseBuilder) what(expr interface{}) CaseBuilder { + return builder.Set(b, "What", newPart(expr)).(CaseBuilder) +} + +// When adds "WHEN ... THEN ..." part to CASE construct +func (b CaseBuilder) When(when interface{}, then interface{}) CaseBuilder { + // TODO: performance hint: replace slice of WhenPart with just slice of parts + // where even indices of the slice belong to "when"s and odd indices belong to "then"s + return builder.Append(b, "WhenParts", newWhenPart(when, then)).(CaseBuilder) +} + +// What sets optional "ELSE ..." part for CASE construct +func (b CaseBuilder) Else(expr interface{}) CaseBuilder { + return builder.Set(b, "Else", newPart(expr)).(CaseBuilder) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/delete.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/delete.go new file mode 100644 index 0000000000000000000000000000000000000000..f3f31e63ef104804530919e41b25f279340d8996 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/delete.go @@ -0,0 +1,191 @@ +package squirrel + +import ( + "bytes" + "database/sql" + "fmt" + "strings" + + "github.com/lann/builder" +) + +type deleteData struct { + PlaceholderFormat PlaceholderFormat + RunWith BaseRunner + Prefixes []Sqlizer + From string + WhereParts []Sqlizer + OrderBys []string + Limit string + Offset string + Suffixes []Sqlizer +} + +func (d *deleteData) Exec() (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return ExecWith(d.RunWith, d) +} + +func (d *deleteData) ToSql() (sqlStr string, args []interface{}, err error) { + if len(d.From) == 0 { + err = fmt.Errorf("delete statements must specify a From table") + return + } + + sql := &bytes.Buffer{} + + if len(d.Prefixes) > 0 { + args, err = appendToSql(d.Prefixes, sql, " ", args) + if err != nil { + return + } + + sql.WriteString(" ") + } + + sql.WriteString("DELETE FROM ") + sql.WriteString(d.From) + + if len(d.WhereParts) > 0 { + sql.WriteString(" WHERE ") + args, err = appendToSql(d.WhereParts, sql, " AND ", args) + if err != nil { + return + } + } + + if len(d.OrderBys) > 0 { + sql.WriteString(" ORDER BY ") + sql.WriteString(strings.Join(d.OrderBys, ", ")) + } + + if len(d.Limit) > 0 { + sql.WriteString(" LIMIT ") + sql.WriteString(d.Limit) + } + + if len(d.Offset) > 0 { + sql.WriteString(" OFFSET ") + sql.WriteString(d.Offset) + } + + if len(d.Suffixes) > 0 { + sql.WriteString(" ") + args, err = appendToSql(d.Suffixes, sql, " ", args) + if err != nil { + return + } + } + + sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sql.String()) + return +} + +// Builder + +// DeleteBuilder builds SQL DELETE statements. +type DeleteBuilder builder.Builder + +func init() { + builder.Register(DeleteBuilder{}, deleteData{}) +} + +// Format methods + +// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the +// query. +func (b DeleteBuilder) PlaceholderFormat(f PlaceholderFormat) DeleteBuilder { + return builder.Set(b, "PlaceholderFormat", f).(DeleteBuilder) +} + +// Runner methods + +// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec. +func (b DeleteBuilder) RunWith(runner BaseRunner) DeleteBuilder { + return setRunWith(b, runner).(DeleteBuilder) +} + +// Exec builds and Execs the query with the Runner set by RunWith. +func (b DeleteBuilder) Exec() (sql.Result, error) { + data := builder.GetStruct(b).(deleteData) + return data.Exec() +} + +// SQL methods + +// ToSql builds the query into a SQL string and bound args. +func (b DeleteBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(deleteData) + return data.ToSql() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b DeleteBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// Prefix adds an expression to the beginning of the query +func (b DeleteBuilder) Prefix(sql string, args ...interface{}) DeleteBuilder { + return b.PrefixExpr(Expr(sql, args...)) +} + +// PrefixExpr adds an expression to the very beginning of the query +func (b DeleteBuilder) PrefixExpr(expr Sqlizer) DeleteBuilder { + return builder.Append(b, "Prefixes", expr).(DeleteBuilder) +} + +// From sets the table to be deleted from. +func (b DeleteBuilder) From(from string) DeleteBuilder { + return builder.Set(b, "From", from).(DeleteBuilder) +} + +// Where adds WHERE expressions to the query. +// +// See SelectBuilder.Where for more information. +func (b DeleteBuilder) Where(pred interface{}, args ...interface{}) DeleteBuilder { + return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(DeleteBuilder) +} + +// OrderBy adds ORDER BY expressions to the query. +func (b DeleteBuilder) OrderBy(orderBys ...string) DeleteBuilder { + return builder.Extend(b, "OrderBys", orderBys).(DeleteBuilder) +} + +// Limit sets a LIMIT clause on the query. +func (b DeleteBuilder) Limit(limit uint64) DeleteBuilder { + return builder.Set(b, "Limit", fmt.Sprintf("%d", limit)).(DeleteBuilder) +} + +// Offset sets a OFFSET clause on the query. +func (b DeleteBuilder) Offset(offset uint64) DeleteBuilder { + return builder.Set(b, "Offset", fmt.Sprintf("%d", offset)).(DeleteBuilder) +} + +// Suffix adds an expression to the end of the query +func (b DeleteBuilder) Suffix(sql string, args ...interface{}) DeleteBuilder { + return b.SuffixExpr(Expr(sql, args...)) +} + +// SuffixExpr adds an expression to the end of the query +func (b DeleteBuilder) SuffixExpr(expr Sqlizer) DeleteBuilder { + return builder.Append(b, "Suffixes", expr).(DeleteBuilder) +} + +func (b DeleteBuilder) Query() (*sql.Rows, error) { + data := builder.GetStruct(b).(deleteData) + return data.Query() +} + +func (d *deleteData) Query() (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return QueryWith(d.RunWith, d) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/delete_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/delete_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..de83c55df3c601102c1be68a36bba7eb57a074d5 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/delete_ctx.go @@ -0,0 +1,69 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + + "github.com/lann/builder" +) + +func (d *deleteData) ExecContext(ctx context.Context) (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(ExecerContext) + if !ok { + return nil, NoContextSupport + } + return ExecContextWith(ctx, ctxRunner, d) +} + +func (d *deleteData) QueryContext(ctx context.Context) (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(QueryerContext) + if !ok { + return nil, NoContextSupport + } + return QueryContextWith(ctx, ctxRunner, d) +} + +func (d *deleteData) QueryRowContext(ctx context.Context) RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRowerContext) + if !ok { + if _, ok := d.RunWith.(QueryerContext); !ok { + return &Row{err: RunnerNotQueryRunner} + } + return &Row{err: NoContextSupport} + } + return QueryRowContextWith(ctx, queryRower, d) +} + +// ExecContext builds and ExecContexts the query with the Runner set by RunWith. +func (b DeleteBuilder) ExecContext(ctx context.Context) (sql.Result, error) { + data := builder.GetStruct(b).(deleteData) + return data.ExecContext(ctx) +} + +// QueryContext builds and QueryContexts the query with the Runner set by RunWith. +func (b DeleteBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) { + data := builder.GetStruct(b).(deleteData) + return data.QueryContext(ctx) +} + +// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith. +func (b DeleteBuilder) QueryRowContext(ctx context.Context) RowScanner { + data := builder.GetStruct(b).(deleteData) + return data.QueryRowContext(ctx) +} + +// ScanContext is a shortcut for QueryRowContext().Scan. +func (b DeleteBuilder) ScanContext(ctx context.Context, dest ...interface{}) error { + return b.QueryRowContext(ctx).Scan(dest...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/expr.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/expr.go new file mode 100644 index 0000000000000000000000000000000000000000..eba1b4579e59dcb3e93c72c87bed8d8d391e6ba7 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/expr.go @@ -0,0 +1,419 @@ +package squirrel + +import ( + "bytes" + "database/sql/driver" + "fmt" + "reflect" + "sort" + "strings" +) + +const ( + // Portable true/false literals. + sqlTrue = "(1=1)" + sqlFalse = "(1=0)" +) + +type expr struct { + sql string + args []interface{} +} + +// Expr builds an expression from a SQL fragment and arguments. +// +// Ex: +// Expr("FROM_UNIXTIME(?)", t) +func Expr(sql string, args ...interface{}) Sqlizer { + return expr{sql: sql, args: args} +} + +func (e expr) ToSql() (sql string, args []interface{}, err error) { + simple := true + for _, arg := range e.args { + if _, ok := arg.(Sqlizer); ok { + simple = false + } + } + if simple { + return e.sql, e.args, nil + } + + buf := &bytes.Buffer{} + ap := e.args + sp := e.sql + + var isql string + var iargs []interface{} + + for err == nil && len(ap) > 0 && len(sp) > 0 { + i := strings.Index(sp, "?") + if i < 0 { + // no more placeholders + break + } + if len(sp) > i+1 && sp[i+1:i+2] == "?" { + // escaped "??"; append it and step past + buf.WriteString(sp[:i+2]) + sp = sp[i+2:] + continue + } + + if as, ok := ap[0].(Sqlizer); ok { + // sqlizer argument; expand it and append the result + isql, iargs, err = as.ToSql() + buf.WriteString(sp[:i]) + buf.WriteString(isql) + args = append(args, iargs...) + } else { + // normal argument; append it and the placeholder + buf.WriteString(sp[:i+1]) + args = append(args, ap[0]) + } + + // step past the argument and placeholder + ap = ap[1:] + sp = sp[i+1:] + } + + // append the remaining sql and arguments + buf.WriteString(sp) + return buf.String(), append(args, ap...), err +} + +type concatExpr []interface{} + +func (ce concatExpr) ToSql() (sql string, args []interface{}, err error) { + for _, part := range ce { + switch p := part.(type) { + case string: + sql += p + case Sqlizer: + pSql, pArgs, err := p.ToSql() + if err != nil { + return "", nil, err + } + sql += pSql + args = append(args, pArgs...) + default: + return "", nil, fmt.Errorf("%#v is not a string or Sqlizer", part) + } + } + return +} + +// ConcatExpr builds an expression by concatenating strings and other expressions. +// +// Ex: +// name_expr := Expr("CONCAT(?, ' ', ?)", firstName, lastName) +// ConcatExpr("COALESCE(full_name,", name_expr, ")") +func ConcatExpr(parts ...interface{}) concatExpr { + return concatExpr(parts) +} + +// aliasExpr helps to alias part of SQL query generated with underlying "expr" +type aliasExpr struct { + expr Sqlizer + alias string +} + +// Alias allows to define alias for column in SelectBuilder. Useful when column is +// defined as complex expression like IF or CASE +// Ex: +// .Column(Alias(caseStmt, "case_column")) +func Alias(expr Sqlizer, alias string) aliasExpr { + return aliasExpr{expr, alias} +} + +func (e aliasExpr) ToSql() (sql string, args []interface{}, err error) { + sql, args, err = e.expr.ToSql() + if err == nil { + sql = fmt.Sprintf("(%s) AS %s", sql, e.alias) + } + return +} + +// Eq is syntactic sugar for use with Where/Having/Set methods. +type Eq map[string]interface{} + +func (eq Eq) toSQL(useNotOpr bool) (sql string, args []interface{}, err error) { + if len(eq) == 0 { + // Empty Sql{} evaluates to true. + sql = sqlTrue + return + } + + var ( + exprs []string + equalOpr = "=" + inOpr = "IN" + nullOpr = "IS" + inEmptyExpr = sqlFalse + ) + + if useNotOpr { + equalOpr = "<>" + inOpr = "NOT IN" + nullOpr = "IS NOT" + inEmptyExpr = sqlTrue + } + + sortedKeys := getSortedKeys(eq) + for _, key := range sortedKeys { + var expr string + val := eq[key] + + switch v := val.(type) { + case driver.Valuer: + if val, err = v.Value(); err != nil { + return + } + } + + r := reflect.ValueOf(val) + if r.Kind() == reflect.Ptr { + if r.IsNil() { + val = nil + } else { + val = r.Elem().Interface() + } + } + + if val == nil { + expr = fmt.Sprintf("%s %s NULL", key, nullOpr) + } else { + if isListType(val) { + valVal := reflect.ValueOf(val) + if valVal.Len() == 0 { + expr = inEmptyExpr + if args == nil { + args = []interface{}{} + } + } else { + for i := 0; i < valVal.Len(); i++ { + args = append(args, valVal.Index(i).Interface()) + } + expr = fmt.Sprintf("%s %s (%s)", key, inOpr, Placeholders(valVal.Len())) + } + } else { + expr = fmt.Sprintf("%s %s ?", key, equalOpr) + args = append(args, val) + } + } + exprs = append(exprs, expr) + } + sql = strings.Join(exprs, " AND ") + return +} + +func (eq Eq) ToSql() (sql string, args []interface{}, err error) { + return eq.toSQL(false) +} + +// NotEq is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(NotEq{"id": 1}) == "id <> 1" +type NotEq Eq + +func (neq NotEq) ToSql() (sql string, args []interface{}, err error) { + return Eq(neq).toSQL(true) +} + +// Like is syntactic sugar for use with LIKE conditions. +// Ex: +// .Where(Like{"name": "%irrel"}) +type Like map[string]interface{} + +func (lk Like) toSql(opr string) (sql string, args []interface{}, err error) { + var exprs []string + for key, val := range lk { + expr := "" + + switch v := val.(type) { + case driver.Valuer: + if val, err = v.Value(); err != nil { + return + } + } + + if val == nil { + err = fmt.Errorf("cannot use null with like operators") + return + } else { + if isListType(val) { + err = fmt.Errorf("cannot use array or slice with like operators") + return + } else { + expr = fmt.Sprintf("%s %s ?", key, opr) + args = append(args, val) + } + } + exprs = append(exprs, expr) + } + sql = strings.Join(exprs, " AND ") + return +} + +func (lk Like) ToSql() (sql string, args []interface{}, err error) { + return lk.toSql("LIKE") +} + +// NotLike is syntactic sugar for use with LIKE conditions. +// Ex: +// .Where(NotLike{"name": "%irrel"}) +type NotLike Like + +func (nlk NotLike) ToSql() (sql string, args []interface{}, err error) { + return Like(nlk).toSql("NOT LIKE") +} + +// ILike is syntactic sugar for use with ILIKE conditions. +// Ex: +// .Where(ILike{"name": "sq%"}) +type ILike Like + +func (ilk ILike) ToSql() (sql string, args []interface{}, err error) { + return Like(ilk).toSql("ILIKE") +} + +// NotILike is syntactic sugar for use with ILIKE conditions. +// Ex: +// .Where(NotILike{"name": "sq%"}) +type NotILike Like + +func (nilk NotILike) ToSql() (sql string, args []interface{}, err error) { + return Like(nilk).toSql("NOT ILIKE") +} + +// Lt is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(Lt{"id": 1}) +type Lt map[string]interface{} + +func (lt Lt) toSql(opposite, orEq bool) (sql string, args []interface{}, err error) { + var ( + exprs []string + opr = "<" + ) + + if opposite { + opr = ">" + } + + if orEq { + opr = fmt.Sprintf("%s%s", opr, "=") + } + + sortedKeys := getSortedKeys(lt) + for _, key := range sortedKeys { + var expr string + val := lt[key] + + switch v := val.(type) { + case driver.Valuer: + if val, err = v.Value(); err != nil { + return + } + } + + if val == nil { + err = fmt.Errorf("cannot use null with less than or greater than operators") + return + } + if isListType(val) { + err = fmt.Errorf("cannot use array or slice with less than or greater than operators") + return + } + expr = fmt.Sprintf("%s %s ?", key, opr) + args = append(args, val) + + exprs = append(exprs, expr) + } + sql = strings.Join(exprs, " AND ") + return +} + +func (lt Lt) ToSql() (sql string, args []interface{}, err error) { + return lt.toSql(false, false) +} + +// LtOrEq is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(LtOrEq{"id": 1}) == "id <= 1" +type LtOrEq Lt + +func (ltOrEq LtOrEq) ToSql() (sql string, args []interface{}, err error) { + return Lt(ltOrEq).toSql(false, true) +} + +// Gt is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(Gt{"id": 1}) == "id > 1" +type Gt Lt + +func (gt Gt) ToSql() (sql string, args []interface{}, err error) { + return Lt(gt).toSql(true, false) +} + +// GtOrEq is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(GtOrEq{"id": 1}) == "id >= 1" +type GtOrEq Lt + +func (gtOrEq GtOrEq) ToSql() (sql string, args []interface{}, err error) { + return Lt(gtOrEq).toSql(true, true) +} + +type conj []Sqlizer + +func (c conj) join(sep, defaultExpr string) (sql string, args []interface{}, err error) { + if len(c) == 0 { + return defaultExpr, []interface{}{}, nil + } + var sqlParts []string + for _, sqlizer := range c { + partSQL, partArgs, err := nestedToSql(sqlizer) + if err != nil { + return "", nil, err + } + if partSQL != "" { + sqlParts = append(sqlParts, partSQL) + args = append(args, partArgs...) + } + } + if len(sqlParts) > 0 { + sql = fmt.Sprintf("(%s)", strings.Join(sqlParts, sep)) + } + return +} + +// And conjunction Sqlizers +type And conj + +func (a And) ToSql() (string, []interface{}, error) { + return conj(a).join(" AND ", sqlTrue) +} + +// Or conjunction Sqlizers +type Or conj + +func (o Or) ToSql() (string, []interface{}, error) { + return conj(o).join(" OR ", sqlFalse) +} + +func getSortedKeys(exp map[string]interface{}) []string { + sortedKeys := make([]string, 0, len(exp)) + for k := range exp { + sortedKeys = append(sortedKeys, k) + } + sort.Strings(sortedKeys) + return sortedKeys +} + +func isListType(val interface{}) bool { + if driver.IsValue(val) { + return false + } + valVal := reflect.ValueOf(val) + return valVal.Kind() == reflect.Array || valVal.Kind() == reflect.Slice +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/go.mod b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..235b74d07f881f428e68d2218ead6b3dba9d335e --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/go.mod @@ -0,0 +1,11 @@ +module github.com/Masterminds/squirrel + +go 1.14 + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 + github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/stretchr/testify v1.2.2 +) diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/go.sum b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..a92f768e60f084b42661848ff2828be637d9bfac --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/go.sum @@ -0,0 +1,10 @@ +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw= +github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o= +github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk= +github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/insert.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/insert.go new file mode 100644 index 0000000000000000000000000000000000000000..97870783aad362fc20fb246ca128fefca341e637 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/insert.go @@ -0,0 +1,298 @@ +package squirrel + +import ( + "bytes" + "database/sql" + "errors" + "fmt" + "io" + "sort" + "strings" + + "github.com/lann/builder" +) + +type insertData struct { + PlaceholderFormat PlaceholderFormat + RunWith BaseRunner + Prefixes []Sqlizer + StatementKeyword string + Options []string + Into string + Columns []string + Values [][]interface{} + Suffixes []Sqlizer + Select *SelectBuilder +} + +func (d *insertData) Exec() (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return ExecWith(d.RunWith, d) +} + +func (d *insertData) Query() (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return QueryWith(d.RunWith, d) +} + +func (d *insertData) QueryRow() RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRower) + if !ok { + return &Row{err: RunnerNotQueryRunner} + } + return QueryRowWith(queryRower, d) +} + +func (d *insertData) ToSql() (sqlStr string, args []interface{}, err error) { + if len(d.Into) == 0 { + err = errors.New("insert statements must specify a table") + return + } + if len(d.Values) == 0 && d.Select == nil { + err = errors.New("insert statements must have at least one set of values or select clause") + return + } + + sql := &bytes.Buffer{} + + if len(d.Prefixes) > 0 { + args, err = appendToSql(d.Prefixes, sql, " ", args) + if err != nil { + return + } + + sql.WriteString(" ") + } + + if d.StatementKeyword == "" { + sql.WriteString("INSERT ") + } else { + sql.WriteString(d.StatementKeyword) + sql.WriteString(" ") + } + + if len(d.Options) > 0 { + sql.WriteString(strings.Join(d.Options, " ")) + sql.WriteString(" ") + } + + sql.WriteString("INTO ") + sql.WriteString(d.Into) + sql.WriteString(" ") + + if len(d.Columns) > 0 { + sql.WriteString("(") + sql.WriteString(strings.Join(d.Columns, ",")) + sql.WriteString(") ") + } + + if d.Select != nil { + args, err = d.appendSelectToSQL(sql, args) + } else { + args, err = d.appendValuesToSQL(sql, args) + } + if err != nil { + return + } + + if len(d.Suffixes) > 0 { + sql.WriteString(" ") + args, err = appendToSql(d.Suffixes, sql, " ", args) + if err != nil { + return + } + } + + sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sql.String()) + return +} + +func (d *insertData) appendValuesToSQL(w io.Writer, args []interface{}) ([]interface{}, error) { + if len(d.Values) == 0 { + return args, errors.New("values for insert statements are not set") + } + + io.WriteString(w, "VALUES ") + + valuesStrings := make([]string, len(d.Values)) + for r, row := range d.Values { + valueStrings := make([]string, len(row)) + for v, val := range row { + if vs, ok := val.(Sqlizer); ok { + vsql, vargs, err := vs.ToSql() + if err != nil { + return nil, err + } + valueStrings[v] = vsql + args = append(args, vargs...) + } else { + valueStrings[v] = "?" + args = append(args, val) + } + } + valuesStrings[r] = fmt.Sprintf("(%s)", strings.Join(valueStrings, ",")) + } + + io.WriteString(w, strings.Join(valuesStrings, ",")) + + return args, nil +} + +func (d *insertData) appendSelectToSQL(w io.Writer, args []interface{}) ([]interface{}, error) { + if d.Select == nil { + return args, errors.New("select clause for insert statements are not set") + } + + selectClause, sArgs, err := d.Select.ToSql() + if err != nil { + return args, err + } + + io.WriteString(w, selectClause) + args = append(args, sArgs...) + + return args, nil +} + +// Builder + +// InsertBuilder builds SQL INSERT statements. +type InsertBuilder builder.Builder + +func init() { + builder.Register(InsertBuilder{}, insertData{}) +} + +// Format methods + +// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the +// query. +func (b InsertBuilder) PlaceholderFormat(f PlaceholderFormat) InsertBuilder { + return builder.Set(b, "PlaceholderFormat", f).(InsertBuilder) +} + +// Runner methods + +// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec. +func (b InsertBuilder) RunWith(runner BaseRunner) InsertBuilder { + return setRunWith(b, runner).(InsertBuilder) +} + +// Exec builds and Execs the query with the Runner set by RunWith. +func (b InsertBuilder) Exec() (sql.Result, error) { + data := builder.GetStruct(b).(insertData) + return data.Exec() +} + +// Query builds and Querys the query with the Runner set by RunWith. +func (b InsertBuilder) Query() (*sql.Rows, error) { + data := builder.GetStruct(b).(insertData) + return data.Query() +} + +// QueryRow builds and QueryRows the query with the Runner set by RunWith. +func (b InsertBuilder) QueryRow() RowScanner { + data := builder.GetStruct(b).(insertData) + return data.QueryRow() +} + +// Scan is a shortcut for QueryRow().Scan. +func (b InsertBuilder) Scan(dest ...interface{}) error { + return b.QueryRow().Scan(dest...) +} + +// SQL methods + +// ToSql builds the query into a SQL string and bound args. +func (b InsertBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(insertData) + return data.ToSql() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b InsertBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// Prefix adds an expression to the beginning of the query +func (b InsertBuilder) Prefix(sql string, args ...interface{}) InsertBuilder { + return b.PrefixExpr(Expr(sql, args...)) +} + +// PrefixExpr adds an expression to the very beginning of the query +func (b InsertBuilder) PrefixExpr(expr Sqlizer) InsertBuilder { + return builder.Append(b, "Prefixes", expr).(InsertBuilder) +} + +// Options adds keyword options before the INTO clause of the query. +func (b InsertBuilder) Options(options ...string) InsertBuilder { + return builder.Extend(b, "Options", options).(InsertBuilder) +} + +// Into sets the INTO clause of the query. +func (b InsertBuilder) Into(into string) InsertBuilder { + return builder.Set(b, "Into", into).(InsertBuilder) +} + +// Columns adds insert columns to the query. +func (b InsertBuilder) Columns(columns ...string) InsertBuilder { + return builder.Extend(b, "Columns", columns).(InsertBuilder) +} + +// Values adds a single row's values to the query. +func (b InsertBuilder) Values(values ...interface{}) InsertBuilder { + return builder.Append(b, "Values", values).(InsertBuilder) +} + +// Suffix adds an expression to the end of the query +func (b InsertBuilder) Suffix(sql string, args ...interface{}) InsertBuilder { + return b.SuffixExpr(Expr(sql, args...)) +} + +// SuffixExpr adds an expression to the end of the query +func (b InsertBuilder) SuffixExpr(expr Sqlizer) InsertBuilder { + return builder.Append(b, "Suffixes", expr).(InsertBuilder) +} + +// SetMap set columns and values for insert builder from a map of column name and value +// note that it will reset all previous columns and values was set if any +func (b InsertBuilder) SetMap(clauses map[string]interface{}) InsertBuilder { + // Keep the columns in a consistent order by sorting the column key string. + cols := make([]string, 0, len(clauses)) + for col := range clauses { + cols = append(cols, col) + } + sort.Strings(cols) + + vals := make([]interface{}, 0, len(clauses)) + for _, col := range cols { + vals = append(vals, clauses[col]) + } + + b = builder.Set(b, "Columns", cols).(InsertBuilder) + b = builder.Set(b, "Values", [][]interface{}{vals}).(InsertBuilder) + + return b +} + +// Select set Select clause for insert query +// If Values and Select are used, then Select has higher priority +func (b InsertBuilder) Select(sb SelectBuilder) InsertBuilder { + return builder.Set(b, "Select", &sb).(InsertBuilder) +} + +func (b InsertBuilder) statementKeyword(keyword string) InsertBuilder { + return builder.Set(b, "StatementKeyword", keyword).(InsertBuilder) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/insert_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/insert_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..4541c2fed325335b17253caaf066bcdd043f365b --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/insert_ctx.go @@ -0,0 +1,69 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + + "github.com/lann/builder" +) + +func (d *insertData) ExecContext(ctx context.Context) (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(ExecerContext) + if !ok { + return nil, NoContextSupport + } + return ExecContextWith(ctx, ctxRunner, d) +} + +func (d *insertData) QueryContext(ctx context.Context) (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(QueryerContext) + if !ok { + return nil, NoContextSupport + } + return QueryContextWith(ctx, ctxRunner, d) +} + +func (d *insertData) QueryRowContext(ctx context.Context) RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRowerContext) + if !ok { + if _, ok := d.RunWith.(QueryerContext); !ok { + return &Row{err: RunnerNotQueryRunner} + } + return &Row{err: NoContextSupport} + } + return QueryRowContextWith(ctx, queryRower, d) +} + +// ExecContext builds and ExecContexts the query with the Runner set by RunWith. +func (b InsertBuilder) ExecContext(ctx context.Context) (sql.Result, error) { + data := builder.GetStruct(b).(insertData) + return data.ExecContext(ctx) +} + +// QueryContext builds and QueryContexts the query with the Runner set by RunWith. +func (b InsertBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) { + data := builder.GetStruct(b).(insertData) + return data.QueryContext(ctx) +} + +// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith. +func (b InsertBuilder) QueryRowContext(ctx context.Context) RowScanner { + data := builder.GetStruct(b).(insertData) + return data.QueryRowContext(ctx) +} + +// ScanContext is a shortcut for QueryRowContext().Scan. +func (b InsertBuilder) ScanContext(ctx context.Context, dest ...interface{}) error { + return b.QueryRowContext(ctx).Scan(dest...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/integration/doc.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/integration/doc.go new file mode 100644 index 0000000000000000000000000000000000000000..3796ab9ede31bfc6ce6f0872e70aad4d46a6beb3 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/integration/doc.go @@ -0,0 +1,2 @@ +// This is a tests-only package. +package integration diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/integration/go.mod b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/integration/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..8029ff8c8b17e541eaf93d5b0d3bab3cc33067fc --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/integration/go.mod @@ -0,0 +1,14 @@ +module github.com/Masterminds/squirrel/integration + +go 1.12 + +require ( + github.com/Masterminds/squirrel v1.1.0 + github.com/go-sql-driver/mysql v1.4.1 + github.com/lib/pq v1.2.0 + github.com/mattn/go-sqlite3 v1.13.0 + github.com/stretchr/testify v1.4.0 + google.golang.org/appengine v1.6.5 // indirect +) + +replace github.com/Masterminds/squirrel => ../ diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/integration/go.sum b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/integration/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..0bfcfa9f096176f194a2b5275638d2688cb952a9 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/integration/go.sum @@ -0,0 +1,34 @@ +github.com/Masterminds/squirrel v1.1.0 h1:baP1qLdoQCeTw3ifCdOq2dkYc6vGcmRdaociKLbEJXs= +github.com/Masterminds/squirrel v1.1.0/go.mod h1:yaPeOnPG5ZRwL9oKdTsO/prlkPbXWZlRVMQ/gGlzIuA= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-sql-driver/mysql v1.4.1 h1:g24URVg0OFbNUTx9qqY1IRZ9D9z3iPyi5zKhQZpNwpA= +github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw= +github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o= +github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk= +github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw= +github.com/lib/pq v1.2.0 h1:LXpIM/LZ5xGFhOpXAQUIMM1HdyqzVYM13zNdjCEEcA0= +github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/mattn/go-sqlite3 v1.13.0 h1:LnJI81JidiW9r7pS/hXe6cFeO5EXNq7KbfvoJLRI69c= +github.com/mattn/go-sqlite3 v1.13.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +google.golang.org/appengine v1.6.5 h1:tycE03LOZYQNhDpS27tcQdAzLCVMaj7QT2SXxebnpCM= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/part.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/part.go new file mode 100644 index 0000000000000000000000000000000000000000..c58f68f1a49717818bc349bede5cbf239bb06769 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/part.go @@ -0,0 +1,63 @@ +package squirrel + +import ( + "fmt" + "io" +) + +type part struct { + pred interface{} + args []interface{} +} + +func newPart(pred interface{}, args ...interface{}) Sqlizer { + return &part{pred, args} +} + +func (p part) ToSql() (sql string, args []interface{}, err error) { + switch pred := p.pred.(type) { + case nil: + // no-op + case Sqlizer: + sql, args, err = nestedToSql(pred) + case string: + sql = pred + args = p.args + default: + err = fmt.Errorf("expected string or Sqlizer, not %T", pred) + } + return +} + +func nestedToSql(s Sqlizer) (string, []interface{}, error) { + if raw, ok := s.(rawSqlizer); ok { + return raw.toSqlRaw() + } else { + return s.ToSql() + } +} + +func appendToSql(parts []Sqlizer, w io.Writer, sep string, args []interface{}) ([]interface{}, error) { + for i, p := range parts { + partSql, partArgs, err := nestedToSql(p) + if err != nil { + return nil, err + } else if len(partSql) == 0 { + continue + } + + if i > 0 { + _, err := io.WriteString(w, sep) + if err != nil { + return nil, err + } + } + + _, err = io.WriteString(w, partSql) + if err != nil { + return nil, err + } + args = append(args, partArgs...) + } + return args, nil +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/placeholder.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/placeholder.go new file mode 100644 index 0000000000000000000000000000000000000000..8e97a6c62d4b430def230bd65a84b6e294b11284 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/placeholder.go @@ -0,0 +1,114 @@ +package squirrel + +import ( + "bytes" + "fmt" + "strings" +) + +// PlaceholderFormat is the interface that wraps the ReplacePlaceholders method. +// +// ReplacePlaceholders takes a SQL statement and replaces each question mark +// placeholder with a (possibly different) SQL placeholder. +type PlaceholderFormat interface { + ReplacePlaceholders(sql string) (string, error) +} + +type placeholderDebugger interface { + debugPlaceholder() string +} + +var ( + // Question is a PlaceholderFormat instance that leaves placeholders as + // question marks. + Question = questionFormat{} + + // Dollar is a PlaceholderFormat instance that replaces placeholders with + // dollar-prefixed positional placeholders (e.g. $1, $2, $3). + Dollar = dollarFormat{} + + // Colon is a PlaceholderFormat instance that replaces placeholders with + // colon-prefixed positional placeholders (e.g. :1, :2, :3). + Colon = colonFormat{} + + // AtP is a PlaceholderFormat instance that replaces placeholders with + // "@p"-prefixed positional placeholders (e.g. @p1, @p2, @p3). + AtP = atpFormat{} +) + +type questionFormat struct{} + +func (questionFormat) ReplacePlaceholders(sql string) (string, error) { + return sql, nil +} + +func (questionFormat) debugPlaceholder() string { + return "?" +} + +type dollarFormat struct{} + +func (dollarFormat) ReplacePlaceholders(sql string) (string, error) { + return replacePositionalPlaceholders(sql, "$") +} + +func (dollarFormat) debugPlaceholder() string { + return "$" +} + +type colonFormat struct{} + +func (colonFormat) ReplacePlaceholders(sql string) (string, error) { + return replacePositionalPlaceholders(sql, ":") +} + +func (colonFormat) debugPlaceholder() string { + return ":" +} + +type atpFormat struct{} + +func (atpFormat) ReplacePlaceholders(sql string) (string, error) { + return replacePositionalPlaceholders(sql, "@p") +} + +func (atpFormat) debugPlaceholder() string { + return "@p" +} + +// Placeholders returns a string with count ? placeholders joined with commas. +func Placeholders(count int) string { + if count < 1 { + return "" + } + + return strings.Repeat(",?", count)[1:] +} + +func replacePositionalPlaceholders(sql, prefix string) (string, error) { + buf := &bytes.Buffer{} + i := 0 + for { + p := strings.Index(sql, "?") + if p == -1 { + break + } + + if len(sql[p:]) > 1 && sql[p:p+2] == "??" { // escape ?? => ? + buf.WriteString(sql[:p]) + buf.WriteString("?") + if len(sql[p:]) == 1 { + break + } + sql = sql[p+2:] + } else { + i++ + buf.WriteString(sql[:p]) + fmt.Fprintf(buf, "%s%d", prefix, i) + sql = sql[p+1:] + } + } + + buf.WriteString(sql) + return buf.String(), nil +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/row.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/row.go new file mode 100644 index 0000000000000000000000000000000000000000..74ffda92bde903c1e54282dc59ad6ef5d52e5577 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/row.go @@ -0,0 +1,22 @@ +package squirrel + +// RowScanner is the interface that wraps the Scan method. +// +// Scan behaves like database/sql.Row.Scan. +type RowScanner interface { + Scan(...interface{}) error +} + +// Row wraps database/sql.Row to let squirrel return new errors on Scan. +type Row struct { + RowScanner + err error +} + +// Scan returns Row.err or calls RowScanner.Scan. +func (r *Row) Scan(dest ...interface{}) error { + if r.err != nil { + return r.err + } + return r.RowScanner.Scan(dest...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/select.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/select.go new file mode 100644 index 0000000000000000000000000000000000000000..d55ce4c74079ac0c4dfe3316d6134cb8c2e61262 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/select.go @@ -0,0 +1,403 @@ +package squirrel + +import ( + "bytes" + "database/sql" + "fmt" + "strings" + + "github.com/lann/builder" +) + +type selectData struct { + PlaceholderFormat PlaceholderFormat + RunWith BaseRunner + Prefixes []Sqlizer + Options []string + Columns []Sqlizer + From Sqlizer + Joins []Sqlizer + WhereParts []Sqlizer + GroupBys []string + HavingParts []Sqlizer + OrderByParts []Sqlizer + Limit string + Offset string + Suffixes []Sqlizer +} + +func (d *selectData) Exec() (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return ExecWith(d.RunWith, d) +} + +func (d *selectData) Query() (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return QueryWith(d.RunWith, d) +} + +func (d *selectData) QueryRow() RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRower) + if !ok { + return &Row{err: RunnerNotQueryRunner} + } + return QueryRowWith(queryRower, d) +} + +func (d *selectData) ToSql() (sqlStr string, args []interface{}, err error) { + sqlStr, args, err = d.toSqlRaw() + if err != nil { + return + } + + sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sqlStr) + return +} + +func (d *selectData) toSqlRaw() (sqlStr string, args []interface{}, err error) { + if len(d.Columns) == 0 { + err = fmt.Errorf("select statements must have at least one result column") + return + } + + sql := &bytes.Buffer{} + + if len(d.Prefixes) > 0 { + args, err = appendToSql(d.Prefixes, sql, " ", args) + if err != nil { + return + } + + sql.WriteString(" ") + } + + sql.WriteString("SELECT ") + + if len(d.Options) > 0 { + sql.WriteString(strings.Join(d.Options, " ")) + sql.WriteString(" ") + } + + if len(d.Columns) > 0 { + args, err = appendToSql(d.Columns, sql, ", ", args) + if err != nil { + return + } + } + + if d.From != nil { + sql.WriteString(" FROM ") + args, err = appendToSql([]Sqlizer{d.From}, sql, "", args) + if err != nil { + return + } + } + + if len(d.Joins) > 0 { + sql.WriteString(" ") + args, err = appendToSql(d.Joins, sql, " ", args) + if err != nil { + return + } + } + + if len(d.WhereParts) > 0 { + sql.WriteString(" WHERE ") + args, err = appendToSql(d.WhereParts, sql, " AND ", args) + if err != nil { + return + } + } + + if len(d.GroupBys) > 0 { + sql.WriteString(" GROUP BY ") + sql.WriteString(strings.Join(d.GroupBys, ", ")) + } + + if len(d.HavingParts) > 0 { + sql.WriteString(" HAVING ") + args, err = appendToSql(d.HavingParts, sql, " AND ", args) + if err != nil { + return + } + } + + if len(d.OrderByParts) > 0 { + sql.WriteString(" ORDER BY ") + args, err = appendToSql(d.OrderByParts, sql, ", ", args) + if err != nil { + return + } + } + + if len(d.Limit) > 0 { + sql.WriteString(" LIMIT ") + sql.WriteString(d.Limit) + } + + if len(d.Offset) > 0 { + sql.WriteString(" OFFSET ") + sql.WriteString(d.Offset) + } + + if len(d.Suffixes) > 0 { + sql.WriteString(" ") + + args, err = appendToSql(d.Suffixes, sql, " ", args) + if err != nil { + return + } + } + + sqlStr = sql.String() + return +} + +// Builder + +// SelectBuilder builds SQL SELECT statements. +type SelectBuilder builder.Builder + +func init() { + builder.Register(SelectBuilder{}, selectData{}) +} + +// Format methods + +// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the +// query. +func (b SelectBuilder) PlaceholderFormat(f PlaceholderFormat) SelectBuilder { + return builder.Set(b, "PlaceholderFormat", f).(SelectBuilder) +} + +// Runner methods + +// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec. +// For most cases runner will be a database connection. +// +// Internally we use this to mock out the database connection for testing. +func (b SelectBuilder) RunWith(runner BaseRunner) SelectBuilder { + return setRunWith(b, runner).(SelectBuilder) +} + +// Exec builds and Execs the query with the Runner set by RunWith. +func (b SelectBuilder) Exec() (sql.Result, error) { + data := builder.GetStruct(b).(selectData) + return data.Exec() +} + +// Query builds and Querys the query with the Runner set by RunWith. +func (b SelectBuilder) Query() (*sql.Rows, error) { + data := builder.GetStruct(b).(selectData) + return data.Query() +} + +// QueryRow builds and QueryRows the query with the Runner set by RunWith. +func (b SelectBuilder) QueryRow() RowScanner { + data := builder.GetStruct(b).(selectData) + return data.QueryRow() +} + +// Scan is a shortcut for QueryRow().Scan. +func (b SelectBuilder) Scan(dest ...interface{}) error { + return b.QueryRow().Scan(dest...) +} + +// SQL methods + +// ToSql builds the query into a SQL string and bound args. +func (b SelectBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(selectData) + return data.ToSql() +} + +func (b SelectBuilder) toSqlRaw() (string, []interface{}, error) { + data := builder.GetStruct(b).(selectData) + return data.toSqlRaw() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b SelectBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// Prefix adds an expression to the beginning of the query +func (b SelectBuilder) Prefix(sql string, args ...interface{}) SelectBuilder { + return b.PrefixExpr(Expr(sql, args...)) +} + +// PrefixExpr adds an expression to the very beginning of the query +func (b SelectBuilder) PrefixExpr(expr Sqlizer) SelectBuilder { + return builder.Append(b, "Prefixes", expr).(SelectBuilder) +} + +// Distinct adds a DISTINCT clause to the query. +func (b SelectBuilder) Distinct() SelectBuilder { + return b.Options("DISTINCT") +} + +// Options adds select option to the query +func (b SelectBuilder) Options(options ...string) SelectBuilder { + return builder.Extend(b, "Options", options).(SelectBuilder) +} + +// Columns adds result columns to the query. +func (b SelectBuilder) Columns(columns ...string) SelectBuilder { + parts := make([]interface{}, 0, len(columns)) + for _, str := range columns { + parts = append(parts, newPart(str)) + } + return builder.Extend(b, "Columns", parts).(SelectBuilder) +} + +// RemoveColumns remove all columns from query. +// Must add a new column with Column or Columns methods, otherwise +// return a error. +func (b SelectBuilder) RemoveColumns() SelectBuilder { + return builder.Delete(b, "Columns").(SelectBuilder) +} + +// Column adds a result column to the query. +// Unlike Columns, Column accepts args which will be bound to placeholders in +// the columns string, for example: +// Column("IF(col IN ("+squirrel.Placeholders(3)+"), 1, 0) as col", 1, 2, 3) +func (b SelectBuilder) Column(column interface{}, args ...interface{}) SelectBuilder { + return builder.Append(b, "Columns", newPart(column, args...)).(SelectBuilder) +} + +// From sets the FROM clause of the query. +func (b SelectBuilder) From(from string) SelectBuilder { + return builder.Set(b, "From", newPart(from)).(SelectBuilder) +} + +// FromSelect sets a subquery into the FROM clause of the query. +func (b SelectBuilder) FromSelect(from SelectBuilder, alias string) SelectBuilder { + // Prevent misnumbered parameters in nested selects (#183). + from = from.PlaceholderFormat(Question) + return builder.Set(b, "From", Alias(from, alias)).(SelectBuilder) +} + +// JoinClause adds a join clause to the query. +func (b SelectBuilder) JoinClause(pred interface{}, args ...interface{}) SelectBuilder { + return builder.Append(b, "Joins", newPart(pred, args...)).(SelectBuilder) +} + +// Join adds a JOIN clause to the query. +func (b SelectBuilder) Join(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("JOIN "+join, rest...) +} + +// LeftJoin adds a LEFT JOIN clause to the query. +func (b SelectBuilder) LeftJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("LEFT JOIN "+join, rest...) +} + +// RightJoin adds a RIGHT JOIN clause to the query. +func (b SelectBuilder) RightJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("RIGHT JOIN "+join, rest...) +} + +// InnerJoin adds a INNER JOIN clause to the query. +func (b SelectBuilder) InnerJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("INNER JOIN "+join, rest...) +} + +// CrossJoin adds a CROSS JOIN clause to the query. +func (b SelectBuilder) CrossJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("CROSS JOIN "+join, rest...) +} + +// Where adds an expression to the WHERE clause of the query. +// +// Expressions are ANDed together in the generated SQL. +// +// Where accepts several types for its pred argument: +// +// nil OR "" - ignored. +// +// string - SQL expression. +// If the expression has SQL placeholders then a set of arguments must be passed +// as well, one for each placeholder. +// +// map[string]interface{} OR Eq - map of SQL expressions to values. Each key is +// transformed into an expression like " = ?", with the corresponding value +// bound to the placeholder. If the value is nil, the expression will be " +// IS NULL". If the value is an array or slice, the expression will be " IN +// (?,?,...)", with one placeholder for each item in the value. These expressions +// are ANDed together. +// +// Where will panic if pred isn't any of the above types. +func (b SelectBuilder) Where(pred interface{}, args ...interface{}) SelectBuilder { + if pred == nil || pred == "" { + return b + } + return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(SelectBuilder) +} + +// GroupBy adds GROUP BY expressions to the query. +func (b SelectBuilder) GroupBy(groupBys ...string) SelectBuilder { + return builder.Extend(b, "GroupBys", groupBys).(SelectBuilder) +} + +// Having adds an expression to the HAVING clause of the query. +// +// See Where. +func (b SelectBuilder) Having(pred interface{}, rest ...interface{}) SelectBuilder { + return builder.Append(b, "HavingParts", newWherePart(pred, rest...)).(SelectBuilder) +} + +// OrderByClause adds ORDER BY clause to the query. +func (b SelectBuilder) OrderByClause(pred interface{}, args ...interface{}) SelectBuilder { + return builder.Append(b, "OrderByParts", newPart(pred, args...)).(SelectBuilder) +} + +// OrderBy adds ORDER BY expressions to the query. +func (b SelectBuilder) OrderBy(orderBys ...string) SelectBuilder { + for _, orderBy := range orderBys { + b = b.OrderByClause(orderBy) + } + + return b +} + +// Limit sets a LIMIT clause on the query. +func (b SelectBuilder) Limit(limit uint64) SelectBuilder { + return builder.Set(b, "Limit", fmt.Sprintf("%d", limit)).(SelectBuilder) +} + +// Limit ALL allows to access all records with limit +func (b SelectBuilder) RemoveLimit() SelectBuilder { + return builder.Delete(b, "Limit").(SelectBuilder) +} + +// Offset sets a OFFSET clause on the query. +func (b SelectBuilder) Offset(offset uint64) SelectBuilder { + return builder.Set(b, "Offset", fmt.Sprintf("%d", offset)).(SelectBuilder) +} + +// RemoveOffset removes OFFSET clause. +func (b SelectBuilder) RemoveOffset() SelectBuilder { + return builder.Delete(b, "Offset").(SelectBuilder) +} + +// Suffix adds an expression to the end of the query +func (b SelectBuilder) Suffix(sql string, args ...interface{}) SelectBuilder { + return b.SuffixExpr(Expr(sql, args...)) +} + +// SuffixExpr adds an expression to the end of the query +func (b SelectBuilder) SuffixExpr(expr Sqlizer) SelectBuilder { + return builder.Append(b, "Suffixes", expr).(SelectBuilder) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/select_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/select_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..4c42c13f478965d0dbe206ccf7fbb8e347d726b3 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/select_ctx.go @@ -0,0 +1,69 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + + "github.com/lann/builder" +) + +func (d *selectData) ExecContext(ctx context.Context) (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(ExecerContext) + if !ok { + return nil, NoContextSupport + } + return ExecContextWith(ctx, ctxRunner, d) +} + +func (d *selectData) QueryContext(ctx context.Context) (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(QueryerContext) + if !ok { + return nil, NoContextSupport + } + return QueryContextWith(ctx, ctxRunner, d) +} + +func (d *selectData) QueryRowContext(ctx context.Context) RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRowerContext) + if !ok { + if _, ok := d.RunWith.(QueryerContext); !ok { + return &Row{err: RunnerNotQueryRunner} + } + return &Row{err: NoContextSupport} + } + return QueryRowContextWith(ctx, queryRower, d) +} + +// ExecContext builds and ExecContexts the query with the Runner set by RunWith. +func (b SelectBuilder) ExecContext(ctx context.Context) (sql.Result, error) { + data := builder.GetStruct(b).(selectData) + return data.ExecContext(ctx) +} + +// QueryContext builds and QueryContexts the query with the Runner set by RunWith. +func (b SelectBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) { + data := builder.GetStruct(b).(selectData) + return data.QueryContext(ctx) +} + +// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith. +func (b SelectBuilder) QueryRowContext(ctx context.Context) RowScanner { + data := builder.GetStruct(b).(selectData) + return data.QueryRowContext(ctx) +} + +// ScanContext is a shortcut for QueryRowContext().Scan. +func (b SelectBuilder) ScanContext(ctx context.Context, dest ...interface{}) error { + return b.QueryRowContext(ctx).Scan(dest...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/squirrel.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/squirrel.go new file mode 100644 index 0000000000000000000000000000000000000000..46d456eb620c09b20161711440ffbef0d091fafd --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/squirrel.go @@ -0,0 +1,183 @@ +// Package squirrel provides a fluent SQL generator. +// +// See https://github.com/Masterminds/squirrel for examples. +package squirrel + +import ( + "bytes" + "database/sql" + "fmt" + "strings" + + "github.com/lann/builder" +) + +// Sqlizer is the interface that wraps the ToSql method. +// +// ToSql returns a SQL representation of the Sqlizer, along with a slice of args +// as passed to e.g. database/sql.Exec. It can also return an error. +type Sqlizer interface { + ToSql() (string, []interface{}, error) +} + +// rawSqlizer is expected to do what Sqlizer does, but without finalizing placeholders. +// This is useful for nested queries. +type rawSqlizer interface { + toSqlRaw() (string, []interface{}, error) +} + +// Execer is the interface that wraps the Exec method. +// +// Exec executes the given query as implemented by database/sql.Exec. +type Execer interface { + Exec(query string, args ...interface{}) (sql.Result, error) +} + +// Queryer is the interface that wraps the Query method. +// +// Query executes the given query as implemented by database/sql.Query. +type Queryer interface { + Query(query string, args ...interface{}) (*sql.Rows, error) +} + +// QueryRower is the interface that wraps the QueryRow method. +// +// QueryRow executes the given query as implemented by database/sql.QueryRow. +type QueryRower interface { + QueryRow(query string, args ...interface{}) RowScanner +} + +// BaseRunner groups the Execer and Queryer interfaces. +type BaseRunner interface { + Execer + Queryer +} + +// Runner groups the Execer, Queryer, and QueryRower interfaces. +type Runner interface { + Execer + Queryer + QueryRower +} + +// WrapStdSql wraps a type implementing the standard SQL interface with methods that +// squirrel expects. +func WrapStdSql(stdSql StdSql) Runner { + return &stdsqlRunner{stdSql} +} + +// StdSql encompasses the standard methods of the *sql.DB type, and other types that +// wrap these methods. +type StdSql interface { + Query(string, ...interface{}) (*sql.Rows, error) + QueryRow(string, ...interface{}) *sql.Row + Exec(string, ...interface{}) (sql.Result, error) +} + +type stdsqlRunner struct { + StdSql +} + +func (r *stdsqlRunner) QueryRow(query string, args ...interface{}) RowScanner { + return r.StdSql.QueryRow(query, args...) +} + +func setRunWith(b interface{}, runner BaseRunner) interface{} { + switch r := runner.(type) { + case StdSqlCtx: + runner = WrapStdSqlCtx(r) + case StdSql: + runner = WrapStdSql(r) + } + return builder.Set(b, "RunWith", runner) +} + +// RunnerNotSet is returned by methods that need a Runner if it isn't set. +var RunnerNotSet = fmt.Errorf("cannot run; no Runner set (RunWith)") + +// RunnerNotQueryRunner is returned by QueryRow if the RunWith value doesn't implement QueryRower. +var RunnerNotQueryRunner = fmt.Errorf("cannot QueryRow; Runner is not a QueryRower") + +// ExecWith Execs the SQL returned by s with db. +func ExecWith(db Execer, s Sqlizer) (res sql.Result, err error) { + query, args, err := s.ToSql() + if err != nil { + return + } + return db.Exec(query, args...) +} + +// QueryWith Querys the SQL returned by s with db. +func QueryWith(db Queryer, s Sqlizer) (rows *sql.Rows, err error) { + query, args, err := s.ToSql() + if err != nil { + return + } + return db.Query(query, args...) +} + +// QueryRowWith QueryRows the SQL returned by s with db. +func QueryRowWith(db QueryRower, s Sqlizer) RowScanner { + query, args, err := s.ToSql() + return &Row{RowScanner: db.QueryRow(query, args...), err: err} +} + +// DebugSqlizer calls ToSql on s and shows the approximate SQL to be executed +// +// If ToSql returns an error, the result of this method will look like: +// "[ToSql error: %s]" or "[DebugSqlizer error: %s]" +// +// IMPORTANT: As its name suggests, this function should only be used for +// debugging. While the string result *might* be valid SQL, this function does +// not try very hard to ensure it. Additionally, executing the output of this +// function with any untrusted user input is certainly insecure. +func DebugSqlizer(s Sqlizer) string { + sql, args, err := s.ToSql() + if err != nil { + return fmt.Sprintf("[ToSql error: %s]", err) + } + + var placeholder string + downCast, ok := s.(placeholderDebugger) + if !ok { + placeholder = "?" + } else { + placeholder = downCast.debugPlaceholder() + } + // TODO: dedupe this with placeholder.go + buf := &bytes.Buffer{} + i := 0 + for { + p := strings.Index(sql, placeholder) + if p == -1 { + break + } + if len(sql[p:]) > 1 && sql[p:p+2] == "??" { // escape ?? => ? + buf.WriteString(sql[:p]) + buf.WriteString("?") + if len(sql[p:]) == 1 { + break + } + sql = sql[p+2:] + } else { + if i+1 > len(args) { + return fmt.Sprintf( + "[DebugSqlizer error: too many placeholders in %#v for %d args]", + sql, len(args)) + } + buf.WriteString(sql[:p]) + fmt.Fprintf(buf, "'%v'", args[i]) + // advance our sql string "cursor" beyond the arg we placed + sql = sql[p+1:] + i++ + } + } + if i < len(args) { + return fmt.Sprintf( + "[DebugSqlizer error: not enough placeholders in %#v for %d args]", + sql, len(args)) + } + // "append" any remaning sql that won't need interpolating + buf.WriteString(sql) + return buf.String() +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/squirrel_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/squirrel_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..c20148ad33c76cf86b64f4f0dd88f8a9f1c96dd7 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/squirrel_ctx.go @@ -0,0 +1,93 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + "errors" +) + +// NoContextSupport is returned if a db doesn't support Context. +var NoContextSupport = errors.New("DB does not support Context") + +// ExecerContext is the interface that wraps the ExecContext method. +// +// Exec executes the given query as implemented by database/sql.ExecContext. +type ExecerContext interface { + ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) +} + +// QueryerContext is the interface that wraps the QueryContext method. +// +// QueryContext executes the given query as implemented by database/sql.QueryContext. +type QueryerContext interface { + QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) +} + +// QueryRowerContext is the interface that wraps the QueryRowContext method. +// +// QueryRowContext executes the given query as implemented by database/sql.QueryRowContext. +type QueryRowerContext interface { + QueryRowContext(ctx context.Context, query string, args ...interface{}) RowScanner +} + +// RunnerContext groups the Runner interface, along with the Context versions of each of +// its methods +type RunnerContext interface { + Runner + QueryerContext + QueryRowerContext + ExecerContext +} + +// WrapStdSqlCtx wraps a type implementing the standard SQL interface plus the context +// versions of the methods with methods that squirrel expects. +func WrapStdSqlCtx(stdSqlCtx StdSqlCtx) RunnerContext { + return &stdsqlCtxRunner{stdSqlCtx} +} + +// StdSqlCtx encompasses the standard methods of the *sql.DB type, along with the Context +// versions of those methods, and other types that wrap these methods. +type StdSqlCtx interface { + StdSql + QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error) + QueryRowContext(context.Context, string, ...interface{}) *sql.Row + ExecContext(context.Context, string, ...interface{}) (sql.Result, error) +} + +type stdsqlCtxRunner struct { + StdSqlCtx +} + +func (r *stdsqlCtxRunner) QueryRow(query string, args ...interface{}) RowScanner { + return r.StdSqlCtx.QueryRow(query, args...) +} + +func (r *stdsqlCtxRunner) QueryRowContext(ctx context.Context, query string, args ...interface{}) RowScanner { + return r.StdSqlCtx.QueryRowContext(ctx, query, args...) +} + +// ExecContextWith ExecContexts the SQL returned by s with db. +func ExecContextWith(ctx context.Context, db ExecerContext, s Sqlizer) (res sql.Result, err error) { + query, args, err := s.ToSql() + if err != nil { + return + } + return db.ExecContext(ctx, query, args...) +} + +// QueryContextWith QueryContexts the SQL returned by s with db. +func QueryContextWith(ctx context.Context, db QueryerContext, s Sqlizer) (rows *sql.Rows, err error) { + query, args, err := s.ToSql() + if err != nil { + return + } + return db.QueryContext(ctx, query, args...) +} + +// QueryRowContextWith QueryRowContexts the SQL returned by s with db. +func QueryRowContextWith(ctx context.Context, db QueryRowerContext, s Sqlizer) RowScanner { + query, args, err := s.ToSql() + return &Row{RowScanner: db.QueryRowContext(ctx, query, args...), err: err} +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/statement.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/statement.go new file mode 100644 index 0000000000000000000000000000000000000000..9420c67f8e921e04876efea27bec4a5c5cd4921d --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/statement.go @@ -0,0 +1,104 @@ +package squirrel + +import "github.com/lann/builder" + +// StatementBuilderType is the type of StatementBuilder. +type StatementBuilderType builder.Builder + +// Select returns a SelectBuilder for this StatementBuilderType. +func (b StatementBuilderType) Select(columns ...string) SelectBuilder { + return SelectBuilder(b).Columns(columns...) +} + +// Insert returns a InsertBuilder for this StatementBuilderType. +func (b StatementBuilderType) Insert(into string) InsertBuilder { + return InsertBuilder(b).Into(into) +} + +// Replace returns a InsertBuilder for this StatementBuilderType with the +// statement keyword set to "REPLACE". +func (b StatementBuilderType) Replace(into string) InsertBuilder { + return InsertBuilder(b).statementKeyword("REPLACE").Into(into) +} + +// Update returns a UpdateBuilder for this StatementBuilderType. +func (b StatementBuilderType) Update(table string) UpdateBuilder { + return UpdateBuilder(b).Table(table) +} + +// Delete returns a DeleteBuilder for this StatementBuilderType. +func (b StatementBuilderType) Delete(from string) DeleteBuilder { + return DeleteBuilder(b).From(from) +} + +// PlaceholderFormat sets the PlaceholderFormat field for any child builders. +func (b StatementBuilderType) PlaceholderFormat(f PlaceholderFormat) StatementBuilderType { + return builder.Set(b, "PlaceholderFormat", f).(StatementBuilderType) +} + +// RunWith sets the RunWith field for any child builders. +func (b StatementBuilderType) RunWith(runner BaseRunner) StatementBuilderType { + return setRunWith(b, runner).(StatementBuilderType) +} + +// Where adds WHERE expressions to the query. +// +// See SelectBuilder.Where for more information. +func (b StatementBuilderType) Where(pred interface{}, args ...interface{}) StatementBuilderType { + return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(StatementBuilderType) +} + +// StatementBuilder is a parent builder for other builders, e.g. SelectBuilder. +var StatementBuilder = StatementBuilderType(builder.EmptyBuilder).PlaceholderFormat(Question) + +// Select returns a new SelectBuilder, optionally setting some result columns. +// +// See SelectBuilder.Columns. +func Select(columns ...string) SelectBuilder { + return StatementBuilder.Select(columns...) +} + +// Insert returns a new InsertBuilder with the given table name. +// +// See InsertBuilder.Into. +func Insert(into string) InsertBuilder { + return StatementBuilder.Insert(into) +} + +// Replace returns a new InsertBuilder with the statement keyword set to +// "REPLACE" and with the given table name. +// +// See InsertBuilder.Into. +func Replace(into string) InsertBuilder { + return StatementBuilder.Replace(into) +} + +// Update returns a new UpdateBuilder with the given table name. +// +// See UpdateBuilder.Table. +func Update(table string) UpdateBuilder { + return StatementBuilder.Update(table) +} + +// Delete returns a new DeleteBuilder with the given table name. +// +// See DeleteBuilder.Table. +func Delete(from string) DeleteBuilder { + return StatementBuilder.Delete(from) +} + +// Case returns a new CaseBuilder +// "what" represents case value +func Case(what ...interface{}) CaseBuilder { + b := CaseBuilder(builder.EmptyBuilder) + + switch len(what) { + case 0: + case 1: + b = b.what(what[0]) + default: + b = b.what(newPart(what[0], what[1:]...)) + + } + return b +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/stmtcacher.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/stmtcacher.go new file mode 100644 index 0000000000000000000000000000000000000000..5bf267a13642d0c6734cf013a6e631f6ca1f0bc6 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/stmtcacher.go @@ -0,0 +1,121 @@ +package squirrel + +import ( + "database/sql" + "fmt" + "sync" +) + +// Prepareer is the interface that wraps the Prepare method. +// +// Prepare executes the given query as implemented by database/sql.Prepare. +type Preparer interface { + Prepare(query string) (*sql.Stmt, error) +} + +// DBProxy groups the Execer, Queryer, QueryRower, and Preparer interfaces. +type DBProxy interface { + Execer + Queryer + QueryRower + Preparer +} + +// NOTE: NewStmtCache is defined in stmtcacher_ctx.go (Go >= 1.8) or stmtcacher_noctx.go (Go < 1.8). + +// StmtCache wraps and delegates down to a Preparer type +// +// It also automatically prepares all statements sent to the underlying Preparer calls +// for Exec, Query and QueryRow and caches the returns *sql.Stmt using the provided +// query as the key. So that it can be automatically re-used. +type StmtCache struct { + prep Preparer + cache map[string]*sql.Stmt + mu sync.Mutex +} + +// Prepare delegates down to the underlying Preparer and caches the result +// using the provided query as a key +func (sc *StmtCache) Prepare(query string) (*sql.Stmt, error) { + sc.mu.Lock() + defer sc.mu.Unlock() + + stmt, ok := sc.cache[query] + if ok { + return stmt, nil + } + stmt, err := sc.prep.Prepare(query) + if err == nil { + sc.cache[query] = stmt + } + return stmt, err +} + +// Exec delegates down to the underlying Preparer using a prepared statement +func (sc *StmtCache) Exec(query string, args ...interface{}) (res sql.Result, err error) { + stmt, err := sc.Prepare(query) + if err != nil { + return + } + return stmt.Exec(args...) +} + +// Query delegates down to the underlying Preparer using a prepared statement +func (sc *StmtCache) Query(query string, args ...interface{}) (rows *sql.Rows, err error) { + stmt, err := sc.Prepare(query) + if err != nil { + return + } + return stmt.Query(args...) +} + +// QueryRow delegates down to the underlying Preparer using a prepared statement +func (sc *StmtCache) QueryRow(query string, args ...interface{}) RowScanner { + stmt, err := sc.Prepare(query) + if err != nil { + return &Row{err: err} + } + return stmt.QueryRow(args...) +} + +// Clear removes and closes all the currently cached prepared statements +func (sc *StmtCache) Clear() (err error) { + sc.mu.Lock() + defer sc.mu.Unlock() + + for key, stmt := range sc.cache { + delete(sc.cache, key) + + if stmt == nil { + continue + } + + if cerr := stmt.Close(); cerr != nil { + err = cerr + } + } + + if err != nil { + return fmt.Errorf("one or more Stmt.Close failed; last error: %v", err) + } + + return +} + +type DBProxyBeginner interface { + DBProxy + Begin() (*sql.Tx, error) +} + +type stmtCacheProxy struct { + DBProxy + db *sql.DB +} + +func NewStmtCacheProxy(db *sql.DB) DBProxyBeginner { + return &stmtCacheProxy{DBProxy: NewStmtCache(db), db: db} +} + +func (sp *stmtCacheProxy) Begin() (*sql.Tx, error) { + return sp.db.Begin() +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/stmtcacher_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/stmtcacher_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..53603cf4c9548775644cbf2050a0d1f3c5150b73 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/stmtcacher_ctx.go @@ -0,0 +1,86 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" +) + +// PrepareerContext is the interface that wraps the Prepare and PrepareContext methods. +// +// Prepare executes the given query as implemented by database/sql.Prepare. +// PrepareContext executes the given query as implemented by database/sql.PrepareContext. +type PreparerContext interface { + Preparer + PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) +} + +// DBProxyContext groups the Execer, Queryer, QueryRower and PreparerContext interfaces. +type DBProxyContext interface { + Execer + Queryer + QueryRower + PreparerContext +} + +// NewStmtCache returns a *StmtCache wrapping a PreparerContext that caches Prepared Stmts. +// +// Stmts are cached based on the string value of their queries. +func NewStmtCache(prep PreparerContext) *StmtCache { + return &StmtCache{prep: prep, cache: make(map[string]*sql.Stmt)} +} + +// NewStmtCacher is deprecated +// +// Use NewStmtCache instead +func NewStmtCacher(prep PreparerContext) DBProxyContext { + return NewStmtCache(prep) +} + +// PrepareContext delegates down to the underlying PreparerContext and caches the result +// using the provided query as a key +func (sc *StmtCache) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) { + ctxPrep, ok := sc.prep.(PreparerContext) + if !ok { + return nil, NoContextSupport + } + sc.mu.Lock() + defer sc.mu.Unlock() + stmt, ok := sc.cache[query] + if ok { + return stmt, nil + } + stmt, err := ctxPrep.PrepareContext(ctx, query) + if err == nil { + sc.cache[query] = stmt + } + return stmt, err +} + +// ExecContext delegates down to the underlying PreparerContext using a prepared statement +func (sc *StmtCache) ExecContext(ctx context.Context, query string, args ...interface{}) (res sql.Result, err error) { + stmt, err := sc.PrepareContext(ctx, query) + if err != nil { + return + } + return stmt.ExecContext(ctx, args...) +} + +// QueryContext delegates down to the underlying PreparerContext using a prepared statement +func (sc *StmtCache) QueryContext(ctx context.Context, query string, args ...interface{}) (rows *sql.Rows, err error) { + stmt, err := sc.PrepareContext(ctx, query) + if err != nil { + return + } + return stmt.QueryContext(ctx, args...) +} + +// QueryRowContext delegates down to the underlying PreparerContext using a prepared statement +func (sc *StmtCache) QueryRowContext(ctx context.Context, query string, args ...interface{}) RowScanner { + stmt, err := sc.PrepareContext(ctx, query) + if err != nil { + return &Row{err: err} + } + return stmt.QueryRowContext(ctx, args...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/stmtcacher_noctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/stmtcacher_noctx.go new file mode 100644 index 0000000000000000000000000000000000000000..deac96777b7fd51ea468b9861b76571b1aa433bf --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/stmtcacher_noctx.go @@ -0,0 +1,21 @@ +// +build !go1.8 + +package squirrel + +import ( + "database/sql" +) + +// NewStmtCacher returns a DBProxy wrapping prep that caches Prepared Stmts. +// +// Stmts are cached based on the string value of their queries. +func NewStmtCache(prep Preparer) *StmtCache { + return &StmtCacher{prep: prep, cache: make(map[string]*sql.Stmt)} +} + +// NewStmtCacher is deprecated +// +// Use NewStmtCache instead +func NewStmtCacher(prep Preparer) DBProxy { + return NewStmtCache(prep) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/update.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/update.go new file mode 100644 index 0000000000000000000000000000000000000000..eb2a9c4dd9a07b893bbea241526d84c84acdc30a --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/update.go @@ -0,0 +1,288 @@ +package squirrel + +import ( + "bytes" + "database/sql" + "fmt" + "sort" + "strings" + + "github.com/lann/builder" +) + +type updateData struct { + PlaceholderFormat PlaceholderFormat + RunWith BaseRunner + Prefixes []Sqlizer + Table string + SetClauses []setClause + From Sqlizer + WhereParts []Sqlizer + OrderBys []string + Limit string + Offset string + Suffixes []Sqlizer +} + +type setClause struct { + column string + value interface{} +} + +func (d *updateData) Exec() (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return ExecWith(d.RunWith, d) +} + +func (d *updateData) Query() (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return QueryWith(d.RunWith, d) +} + +func (d *updateData) QueryRow() RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRower) + if !ok { + return &Row{err: RunnerNotQueryRunner} + } + return QueryRowWith(queryRower, d) +} + +func (d *updateData) ToSql() (sqlStr string, args []interface{}, err error) { + if len(d.Table) == 0 { + err = fmt.Errorf("update statements must specify a table") + return + } + if len(d.SetClauses) == 0 { + err = fmt.Errorf("update statements must have at least one Set clause") + return + } + + sql := &bytes.Buffer{} + + if len(d.Prefixes) > 0 { + args, err = appendToSql(d.Prefixes, sql, " ", args) + if err != nil { + return + } + + sql.WriteString(" ") + } + + sql.WriteString("UPDATE ") + sql.WriteString(d.Table) + + sql.WriteString(" SET ") + setSqls := make([]string, len(d.SetClauses)) + for i, setClause := range d.SetClauses { + var valSql string + if vs, ok := setClause.value.(Sqlizer); ok { + vsql, vargs, err := vs.ToSql() + if err != nil { + return "", nil, err + } + if _, ok := vs.(SelectBuilder); ok { + valSql = fmt.Sprintf("(%s)", vsql) + } else { + valSql = vsql + } + args = append(args, vargs...) + } else { + valSql = "?" + args = append(args, setClause.value) + } + setSqls[i] = fmt.Sprintf("%s = %s", setClause.column, valSql) + } + sql.WriteString(strings.Join(setSqls, ", ")) + + if d.From != nil { + sql.WriteString(" FROM ") + args, err = appendToSql([]Sqlizer{d.From}, sql, "", args) + if err != nil { + return + } + } + + if len(d.WhereParts) > 0 { + sql.WriteString(" WHERE ") + args, err = appendToSql(d.WhereParts, sql, " AND ", args) + if err != nil { + return + } + } + + if len(d.OrderBys) > 0 { + sql.WriteString(" ORDER BY ") + sql.WriteString(strings.Join(d.OrderBys, ", ")) + } + + if len(d.Limit) > 0 { + sql.WriteString(" LIMIT ") + sql.WriteString(d.Limit) + } + + if len(d.Offset) > 0 { + sql.WriteString(" OFFSET ") + sql.WriteString(d.Offset) + } + + if len(d.Suffixes) > 0 { + sql.WriteString(" ") + args, err = appendToSql(d.Suffixes, sql, " ", args) + if err != nil { + return + } + } + + sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sql.String()) + return +} + +// Builder + +// UpdateBuilder builds SQL UPDATE statements. +type UpdateBuilder builder.Builder + +func init() { + builder.Register(UpdateBuilder{}, updateData{}) +} + +// Format methods + +// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the +// query. +func (b UpdateBuilder) PlaceholderFormat(f PlaceholderFormat) UpdateBuilder { + return builder.Set(b, "PlaceholderFormat", f).(UpdateBuilder) +} + +// Runner methods + +// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec. +func (b UpdateBuilder) RunWith(runner BaseRunner) UpdateBuilder { + return setRunWith(b, runner).(UpdateBuilder) +} + +// Exec builds and Execs the query with the Runner set by RunWith. +func (b UpdateBuilder) Exec() (sql.Result, error) { + data := builder.GetStruct(b).(updateData) + return data.Exec() +} + +func (b UpdateBuilder) Query() (*sql.Rows, error) { + data := builder.GetStruct(b).(updateData) + return data.Query() +} + +func (b UpdateBuilder) QueryRow() RowScanner { + data := builder.GetStruct(b).(updateData) + return data.QueryRow() +} + +func (b UpdateBuilder) Scan(dest ...interface{}) error { + return b.QueryRow().Scan(dest...) +} + +// SQL methods + +// ToSql builds the query into a SQL string and bound args. +func (b UpdateBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(updateData) + return data.ToSql() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b UpdateBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// Prefix adds an expression to the beginning of the query +func (b UpdateBuilder) Prefix(sql string, args ...interface{}) UpdateBuilder { + return b.PrefixExpr(Expr(sql, args...)) +} + +// PrefixExpr adds an expression to the very beginning of the query +func (b UpdateBuilder) PrefixExpr(expr Sqlizer) UpdateBuilder { + return builder.Append(b, "Prefixes", expr).(UpdateBuilder) +} + +// Table sets the table to be updated. +func (b UpdateBuilder) Table(table string) UpdateBuilder { + return builder.Set(b, "Table", table).(UpdateBuilder) +} + +// Set adds SET clauses to the query. +func (b UpdateBuilder) Set(column string, value interface{}) UpdateBuilder { + return builder.Append(b, "SetClauses", setClause{column: column, value: value}).(UpdateBuilder) +} + +// SetMap is a convenience method which calls .Set for each key/value pair in clauses. +func (b UpdateBuilder) SetMap(clauses map[string]interface{}) UpdateBuilder { + keys := make([]string, len(clauses)) + i := 0 + for key := range clauses { + keys[i] = key + i++ + } + sort.Strings(keys) + for _, key := range keys { + val, _ := clauses[key] + b = b.Set(key, val) + } + return b +} + +// From adds FROM clause to the query +// FROM is valid construct in postgresql only. +func (b UpdateBuilder) From(from string) UpdateBuilder { + return builder.Set(b, "From", newPart(from)).(UpdateBuilder) +} + +// FromSelect sets a subquery into the FROM clause of the query. +func (b UpdateBuilder) FromSelect(from SelectBuilder, alias string) UpdateBuilder { + // Prevent misnumbered parameters in nested selects (#183). + from = from.PlaceholderFormat(Question) + return builder.Set(b, "From", Alias(from, alias)).(UpdateBuilder) +} + +// Where adds WHERE expressions to the query. +// +// See SelectBuilder.Where for more information. +func (b UpdateBuilder) Where(pred interface{}, args ...interface{}) UpdateBuilder { + return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(UpdateBuilder) +} + +// OrderBy adds ORDER BY expressions to the query. +func (b UpdateBuilder) OrderBy(orderBys ...string) UpdateBuilder { + return builder.Extend(b, "OrderBys", orderBys).(UpdateBuilder) +} + +// Limit sets a LIMIT clause on the query. +func (b UpdateBuilder) Limit(limit uint64) UpdateBuilder { + return builder.Set(b, "Limit", fmt.Sprintf("%d", limit)).(UpdateBuilder) +} + +// Offset sets a OFFSET clause on the query. +func (b UpdateBuilder) Offset(offset uint64) UpdateBuilder { + return builder.Set(b, "Offset", fmt.Sprintf("%d", offset)).(UpdateBuilder) +} + +// Suffix adds an expression to the end of the query +func (b UpdateBuilder) Suffix(sql string, args ...interface{}) UpdateBuilder { + return b.SuffixExpr(Expr(sql, args...)) +} + +// SuffixExpr adds an expression to the end of the query +func (b UpdateBuilder) SuffixExpr(expr Sqlizer) UpdateBuilder { + return builder.Append(b, "Suffixes", expr).(UpdateBuilder) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/update_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/update_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..ad479f96f49fd0f02da2f3ea44f0392f451ec5d5 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/update_ctx.go @@ -0,0 +1,69 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + + "github.com/lann/builder" +) + +func (d *updateData) ExecContext(ctx context.Context) (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(ExecerContext) + if !ok { + return nil, NoContextSupport + } + return ExecContextWith(ctx, ctxRunner, d) +} + +func (d *updateData) QueryContext(ctx context.Context) (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(QueryerContext) + if !ok { + return nil, NoContextSupport + } + return QueryContextWith(ctx, ctxRunner, d) +} + +func (d *updateData) QueryRowContext(ctx context.Context) RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRowerContext) + if !ok { + if _, ok := d.RunWith.(QueryerContext); !ok { + return &Row{err: RunnerNotQueryRunner} + } + return &Row{err: NoContextSupport} + } + return QueryRowContextWith(ctx, queryRower, d) +} + +// ExecContext builds and ExecContexts the query with the Runner set by RunWith. +func (b UpdateBuilder) ExecContext(ctx context.Context) (sql.Result, error) { + data := builder.GetStruct(b).(updateData) + return data.ExecContext(ctx) +} + +// QueryContext builds and QueryContexts the query with the Runner set by RunWith. +func (b UpdateBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) { + data := builder.GetStruct(b).(updateData) + return data.QueryContext(ctx) +} + +// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith. +func (b UpdateBuilder) QueryRowContext(ctx context.Context) RowScanner { + data := builder.GetStruct(b).(updateData) + return data.QueryRowContext(ctx) +} + +// ScanContext is a shortcut for QueryRowContext().Scan. +func (b UpdateBuilder) ScanContext(ctx context.Context, dest ...interface{}) error { + return b.QueryRowContext(ctx).Scan(dest...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/where.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/where.go new file mode 100644 index 0000000000000000000000000000000000000000..976b63ace4ecb4452f5326b1893067bb604d133e --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/environment/source/where.go @@ -0,0 +1,30 @@ +package squirrel + +import ( + "fmt" +) + +type wherePart part + +func newWherePart(pred interface{}, args ...interface{}) Sqlizer { + return &wherePart{pred: pred, args: args} +} + +func (p wherePart) ToSql() (sql string, args []interface{}, err error) { + switch pred := p.pred.(type) { + case nil: + // no-op + case rawSqlizer: + return pred.toSqlRaw() + case Sqlizer: + return pred.ToSql() + case map[string]interface{}: + return Eq(pred).ToSql() + case string: + sql = pred + args = p.args + default: + err = fmt.Errorf("expected string-keyed map or string, not %T", pred) + } + return +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/instruction.md b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b848fb0a70b2bd85b218532d531f214b4c0b04da --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/instruction.md @@ -0,0 +1,72 @@ +SQL CASE statements generate empty clauses + +#### Description + +When building SQL queries with CASE statements, the generated SQL contains empty WHEN/THEN clauses instead of the expected values and conditions. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "fmt" + "github.com/Masterminds/squirrel" +) + +func main() { + // Simple CASE with value + caseStmt := squirrel.Case("number"). + When(1, "one"). + When(2, "two"). + Else("?") + + sql, args, err := squirrel.Select(caseStmt).From("table").ToSql() + if err != nil { + panic(err) + } + + fmt.Printf("Expected: SELECT CASE number WHEN 1 THEN one WHEN 2 THEN two ELSE ? END FROM table\n") + fmt.Printf("Actual: %s\n", sql) + fmt.Printf("Args: %v\n", args) + + // CASE without value + caseStmt2 := squirrel.Case(). + When(squirrel.Eq{"x": 0}, "x is zero"). + When(squirrel.Gt{"x": 1}, squirrel.Expr("CONCAT('x is greater than ', ?)", 2)) + + sql2, args2, err2 := squirrel.Select(caseStmt2).From("table").ToSql() + if err2 != nil { + panic(err2) + } + + fmt.Printf("\nExpected: SELECT CASE WHEN x = ? THEN x is zero WHEN x > ? THEN CONCAT('x is greater than ', ?) END FROM table\n") + fmt.Printf("Actual: %s\n", sql2) + fmt.Printf("Args: %v\n", args2) +} +``` + +#### Expected Output +``` +Expected: SELECT CASE number WHEN 1 THEN one WHEN 2 THEN two ELSE ? END FROM table +Actual: SELECT CASE number WHEN 1 THEN one WHEN 2 THEN two ELSE ? END FROM table +Args: [big number] + +Expected: SELECT CASE WHEN x = ? THEN x is zero WHEN x > ? THEN CONCAT('x is greater than ', ?) END FROM table +Actual: SELECT CASE WHEN x = ? THEN x is zero WHEN x > ? THEN CONCAT('x is greater than ', ?) END FROM table +Args: [0 1 2] +``` + +#### Actual Output +``` +Expected: SELECT CASE number WHEN 1 THEN one WHEN 2 THEN two ELSE ? END FROM table +Actual: SELECT CASE WHEN THEN WHEN THEN ELSE END FROM table +Args: [] + +Expected: SELECT CASE WHEN x = ? THEN x is zero WHEN x > ? THEN CONCAT('x is greater than ', ?) END FROM table +Actual: SELECT CASE WHEN THEN WHEN THEN END FROM table +Args: [] +``` + +The CASE statements are generating empty WHEN/THEN clauses and no arguments are being passed through. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/provenance.json b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..d3a914ca06aa333b5b7d1437cc54a84878e0a60c --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/provenance.json @@ -0,0 +1,385 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt", + "original-bug": "task-specific unchanged semantic bug", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only", + "extra_semantic_repair_coverage": false, + "original_patch_hunks": 1 + }, + "private_frozen_files": { + "case_test.go": { + "mode": "0o644", + "sha256": "fdb8c60761dc1ab02953e86f1736bd29e644e61bb7f67a394a5f71d276a67298", + "size": 3296 + }, + "delete_ctx_test.go": { + "mode": "0o644", + "sha256": "07e5cd531fbc380655a6f441eeee23da925195d67a1a7e7682785806af51014e", + "size": 847 + }, + "delete_test.go": { + "mode": "0o644", + "sha256": "44ac247a59eb89cd5f41e3f0948a78e51e757d0888a72874d12a12c6db1acfb0", + "size": 1806 + }, + "expr_test.go": { + "mode": "0o644", + "sha256": "ab52b68e40a81bda968dacc733f34c08626f299405450c383daf438e33897a65", + "size": 10245 + }, + "insert_ctx_test.go": { + "mode": "0o644", + "sha256": "b3e3efaf75fee82c147958afb70a90334f4f08cf29b64bd76d23a03b9824f299", + "size": 807 + }, + "insert_test.go": { + "mode": "0o644", + "sha256": "665fe6694c9ce48b2bcbdfd34ab9bde67d8fd7601b3d5798f4dacd693e1da278", + "size": 2627 + }, + "integration/integration_test.go": { + "mode": "0o644", + "sha256": "c8631b72fa30417861d7ba87a1a9a5c0883d01744fb49bf779360dc4a61b9abf", + "size": 3162 + }, + "placeholder_test.go": { + "mode": "0o644", + "sha256": "c498900e8f98d981e90863f0603d19c11db17e786eae008bdc5af2b25ae8eb13", + "size": 2005 + }, + "row_test.go": { + "mode": "0o644", + "sha256": "7fe834ce33424df8e009fa44ee5acea25508c7e439d1bf07fddf6d4c90e77ec1", + "size": 626 + }, + "select_ctx_test.go": { + "mode": "0o644", + "sha256": "560d37ac028fbf92ba5c5a20b95af7d866a4fbdecd0e868b6fe266eb4849e665", + "size": 771 + }, + "select_test.go": { + "mode": "0o644", + "sha256": "3b06e89b5c358992a7165414dbeb4643820d95574981359638d609931d528630", + "size": 12209 + }, + "squirrel_ctx_test.go": { + "mode": "0o644", + "sha256": "4a052ae48d428a0719777189c407e5d5c7087550c0d99b2c28cceada083f76b0", + "size": 1277 + }, + "squirrel_test.go": { + "mode": "0o644", + "sha256": "7336a2ffda333c52c145d76e926a89e1244ff24b96c86abfc6fe06723572180f", + "size": 5780 + }, + "statement_test.go": { + "mode": "0o644", + "sha256": "a0f46fa71157b09eaca3da0fa6a75b25156cb552c785228836b0ffbb9fe5ac27", + "size": 2072 + }, + "stmtcacher_ctx_test.go": { + "mode": "0o644", + "sha256": "a0a1f49a87ebb6b35b8d66fbe9051d8a9f94346eaf5e3cd70719424433f5c878", + "size": 402 + }, + "stmtcacher_test.go": { + "mode": "0o644", + "sha256": "e5b5020ac3c194cf92121100a24df580955f32f89bd600b1e56014702d24eb52", + "size": 546 + }, + "update_ctx_test.go": { + "mode": "0o644", + "sha256": "3dd7bd0c17bfb61fad6e71c7736ca6a207f811ae7c3f92f8185c5f7d32dbf30a", + "size": 805 + }, + "update_test.go": { + "mode": "0o644", + "sha256": "6316c8d144c647d9c7bdd6b8be4490c40398da03d331be23c4729faa7a57aa4e", + "size": 2836 + }, + "where_test.go": { + "mode": "0o644", + "sha256": "1a53006a294c379a8b7f212b340acf9063ea0b613062a52fc9585a7d84f853f3", + "size": 1325 + } + }, + "public_files": { + ".gitignore": { + "mode": "0o644", + "sha256": "1eaa1ee4d30ac564ac002a67650eff426807e1fd8b9475250d0ef31ee3d458dd", + "size": 13 + }, + ".travis.yml": { + "mode": "0o644", + "sha256": "5409f254b7fc2f4ed3afcdc45ac2346acedadf2689e14f5d4735e5587cd31a15", + "size": 768 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "11ac92da622d8d25df663d4bc5d12f464da1a98a9fbb75930e0e65cc58b80a2f", + "size": 1185 + }, + "README.md": { + "mode": "0o644", + "sha256": "f1dafb8f66d5eb204201e34fbcf50a08180b7cc6fffb9cd87ed55673d840afc2", + "size": 4363 + }, + "case.go": { + "mode": "0o644", + "sha256": "46533510529ab627b857d9d452571d89fca43467c87de0ec7284648ea4000810", + "size": 3065 + }, + "delete.go": { + "mode": "0o644", + "sha256": "700cefe533a6d939aaa689dfcbf148ad8d4b07f0278337944ecc37767479b3eb", + "size": 4806 + }, + "delete_ctx.go": { + "mode": "0o644", + "sha256": "0fb7da25c0bee63500317da43e1d8bcb5b8d62487ec80e6298135953d62b03f4", + "size": 1908 + }, + "expr.go": { + "mode": "0o644", + "sha256": "246aa910b8adc931da8773bf9a782d8e8292c5315fd267d3aca2d75792842d8e", + "size": 9216 + }, + "go.mod": { + "mode": "0o644", + "sha256": "b4c6f216eafab7a1ca5209b5ddca006529666f72184aea72293395c69f7140f5", + "size": 321 + }, + "go.sum": { + "mode": "0o644", + "sha256": "2b4fe7850b36f8effe69d037ed1219df62399e4076034930b8f3d2edb7fa46fd", + "size": 953 + }, + "insert.go": { + "mode": "0o644", + "sha256": "626ac9dd6c5cbca5e9e3b93252d82c94d6d6b63ddc967fb0dbcee0f3dc889c2e", + "size": 7710 + }, + "insert_ctx.go": { + "mode": "0o644", + "sha256": "6f72f9fd2e5e3b9e60f65f1fcf920ba6724242784ba26b9e0924aa8a0667d8b2", + "size": 1908 + }, + "integration/doc.go": { + "mode": "0o644", + "sha256": "2eb5edda1be28404e1f6681d1177cd3f447f8167cacf51f817b853e578e5996c", + "size": 53 + }, + "integration/go.mod": { + "mode": "0o644", + "sha256": "b8f745640b55a496faf7e8ffe39dcbb223bd4a856c108f38cb5021c5c9fafc3b", + "size": 347 + }, + "integration/go.sum": { + "mode": "0o644", + "sha256": "30892c107aa863abb8105816d7f6fa497ec69fd1d6783f4f186a19ff0fe6df80", + "size": 3122 + }, + "part.go": { + "mode": "0o644", + "sha256": "5fb7ec420cb4f4eff065b0a71e073b8ac74a1a6a81647d19b490be9286bc2258", + "size": 1149 + }, + "placeholder.go": { + "mode": "0o644", + "sha256": "246a7219eb14597fa9322bac44691e6ff6f7437df8cf7e4f7fe15c263ce61114", + "size": 2558 + }, + "row.go": { + "mode": "0o644", + "sha256": "089fb1c058ccf2f6664c0cdaac097ad6616e5ec0b44939429bce737d70d9c50e", + "size": 472 + }, + "select.go": { + "mode": "0o644", + "sha256": "28ab9e3d2a9772d6e0ef08f4fa83ea1ccd4a246f086e0e9431a10e5d42504d33", + "size": 11320 + }, + "select_ctx.go": { + "mode": "0o644", + "sha256": "ac68ccbb975d46547f21be70d802af6f4de4ac4c41d9e26a925621e725d74787", + "size": 1908 + }, + "squirrel.go": { + "mode": "0o644", + "sha256": "a5d827d66fdd080a5f2efaccb74fca217265e995d667cf10a026dbc2871e70f9", + "size": 5074 + }, + "squirrel_ctx.go": { + "mode": "0o644", + "sha256": "2e903ebfb7941cb8f68100dc9c500b5bfb214ea8534aaa21e4ea7ed01a70085d", + "size": 3085 + }, + "statement.go": { + "mode": "0o644", + "sha256": "f6cbf3d520fe88614795a68113ea020dd9ad3977e9dcd42af6e0a48a906d2caa", + "size": 3254 + }, + "stmtcacher.go": { + "mode": "0o644", + "sha256": "8f1593570472ec435e653b16a331262629495915b8cf2fda9929e6c7fe0a3c5a", + "size": 2799 + }, + "stmtcacher_ctx.go": { + "mode": "0o644", + "sha256": "e0c02cbf487302ea082afa304b851c454ece0d85f7073c721afb9e5a9e32f7fc", + "size": 2550 + }, + "stmtcacher_noctx.go": { + "mode": "0o644", + "sha256": "14539e8754cc3ee236d7f8af2e0176fb5a8c6183d73ad0e797913ae51a400b22", + "size": 459 + }, + "update.go": { + "mode": "0o644", + "sha256": "0d9f5f030b6d4e31f21f2b84fa6f62df1cc0eb540a7fa04eb9ec68c2ed238e0a", + "size": 7349 + }, + "update_ctx.go": { + "mode": "0o644", + "sha256": "517c4436ea62524889f3a50339d1d3c3ee89ff23050eecaf5fa3a973b8ec4bf0", + "size": 1908 + }, + "where.go": { + "mode": "0o644", + "sha256": "555836c5dd84cbd7571b5e2b3b5b677f3fcd4cc42a0f1cfb3a176f8909bd0755", + "size": 572 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:8397c903899921169852f4bff3ee17f23d7d4f8eaf03854a2bffd0051a2b363f", + "os": "linux", + "sha256": "8397c903899921169852f4bff3ee17f23d7d4f8eaf03854a2bffd0051a2b363f" + }, + "context_inventory_sha256": "8c63f6649adee8ca9a2290a98a9a180d45b9f65f42395812e6e97b409186f81d", + "image": "registry.hf.space/harness-hub-scale800-go-055c69f17f410bee-starter-v1@sha256:9dfb6b7417f54d78d50e6e6bdd951b854ed8da8f5f1782f4fe563a85e1cd0b7a", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "dc294274d204bc3953b3ddc9f385c54f9ded95ae55c720729f3b4765c2561bba", + "receipt_path": "production/runtime-images-extra-v1/resolutions/055c69f17f410bee/resolution.json", + "receipt_sha256": "741436358af5538a7e21351cbe2660ca3aeb440246407b654888e4766be1dc7a", + "registry_digest": "sha256:9dfb6b7417f54d78d50e6e6bdd951b854ed8da8f5f1782f4fe563a85e1cd0b7a", + "source_image": "docker.io/swebench/swesmith.x86_64.masterminds_1776_squirrel.1ded5784@sha256:8b7a7b2f6acd11416e98a5254735925f3e354c9a85634e37a1f9a347ad82ed22", + "source_receipt_sha256": "6be66b515dc9ca98b38e89389e4b485f038418a7591cd99ca1294782042078a3", + "space_commit": "4520e0fbd0db51041911578a6d2b53e5493f8b5a", + "space_id": "harness-hub/scale800-go-055c69f17f410bee-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "59775038dd524356428cd4628fb8f7314c1a64e943d4c88ca36c8e904f8f2ca6", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21", + "source_proof_sha256": "2216232c21a939f7bc00314629d23b4612b05b42214ae136963bb46e97349a0c", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2", + "cloud_launch_ready": false, + "healthy_mirror_commit": "ecf2598064d7f630d661d9a03e6cab204d37eeb8", + "instruction_sha256": "9024039c6527cc39ce6f0aba992a7a89381d6b394b509c0e57e342c1537520cb", + "is_fork": true, + "learner_path": "tasks/228d31f82de518ad7ce9e2a3/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "11ac92da622d8d25df663d4bc5d12f464da1a98a9fbb75930e0e65cc58b80a2f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/Masterminds__squirrel.1ded5784/b6b30d085883cb57a5062a0579bde23f642f1f85/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "1ded5784535dcffa4e175d4efbd1ca2706927758", + "patch_sha256": "610f5eb97703187f621440aad0bb26d2ee73ec6340fd3642674ec280b29befa8", + "provenance_path": "tasks/228d31f82de518ad7ce9e2a3/source-proof.json", + "repository_lineage": [ + "swesmith/Masterminds__squirrel.1ded5784", + "Masterminds/squirrel" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "b6b30d085883cb57a5062a0579bde23f642f1f85", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "00aabf6b475342653b9d05c907a07ddf5d943af3", + "source_kind": "mutation", + "source_repo": "swesmith/Masterminds__squirrel.1ded5784", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2", + "task_sha256": "a5802122c4935c17d5215a6c0a5abd56e656c6a1d2a5389511fbaa7d2e7beac0", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "Masterminds/squirrel", + "usage": "quarantine_only" + }, + "source_row_sha256": "3668dda2e25da2592b386b0affc3ec796ca2a3dae84c6f6a82594f83abd61e6a", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.travis.yml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/case.go", + "/testbed/delete.go", + "/testbed/delete_ctx.go", + "/testbed/expr.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/insert.go", + "/testbed/insert_ctx.go", + "/testbed/integration/doc.go", + "/testbed/integration/go.mod", + "/testbed/integration/go.sum", + "/testbed/part.go", + "/testbed/placeholder.go", + "/testbed/row.go", + "/testbed/select.go", + "/testbed/select_ctx.go", + "/testbed/squirrel.go", + "/testbed/squirrel_ctx.go", + "/testbed/statement.go", + "/testbed/stmtcacher.go", + "/testbed/stmtcacher_ctx.go", + "/testbed/stmtcacher_noctx.go", + "/testbed/update.go", + "/testbed/update_ctx.go", + "/testbed/where.go" + ] +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/solution/solve.sh b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..86251e5208eb8deb7f14ce29ca8a746ff5a5a92a --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"case.go": {"data": "cGFja2FnZSBzcXVpcnJlbAoKaW1wb3J0ICgKCSJieXRlcyIKCSJlcnJvcnMiCgoJImdpdGh1Yi5jb20vbGFubi9idWlsZGVyIgopCgpmdW5jIGluaXQoKSB7CglidWlsZGVyLlJlZ2lzdGVyKENhc2VCdWlsZGVye30sIGNhc2VEYXRhe30pCn0KCi8vIHNxbGl6ZXJCdWZmZXIgaXMgYSBoZWxwZXIgdGhhdCBhbGxvd3MgdG8gd3JpdGUgbWFueSBTcWxpemVycyBvbmUgYnkgb25lCi8vIHdpdGhvdXQgY29uc3RhbnQgY2hlY2tzIGZvciBlcnJvcnMgdGhhdCBtYXkgY29tZSBmcm9tIFNxbGl6ZXIKdHlwZSBzcWxpemVyQnVmZmVyIHN0cnVjdCB7CglieXRlcy5CdWZmZXIKCWFyZ3MgW11pbnRlcmZhY2V7fQoJZXJyICBlcnJvcgp9CgovLyBXcml0ZVNxbCBjb252ZXJ0cyBTcWxpemVyIHRvIFNRTCBzdHJpbmdzIGFuZCB3cml0ZXMgaXQgdG8gYnVmZmVyCmZ1bmMgKGIgKnNxbGl6ZXJCdWZmZXIpIFdyaXRlU3FsKGl0ZW0gU3FsaXplcikgewoJaWYgYi5lcnIgIT0gbmlsIHsKCQlyZXR1cm4KCX0KCgl2YXIgc3RyIHN0cmluZwoJdmFyIGFyZ3MgW11pbnRlcmZhY2V7fQoJc3RyLCBhcmdzLCBiLmVyciA9IG5lc3RlZFRvU3FsKGl0ZW0pCgoJaWYgYi5lcnIgIT0gbmlsIHsKCQlyZXR1cm4KCX0KCgliLldyaXRlU3RyaW5nKHN0cikKCWIuV3JpdGVCeXRlKCcgJykKCWIuYXJncyA9IGFwcGVuZChiLmFyZ3MsIGFyZ3MuLi4pCn0KCmZ1bmMgKGIgKnNxbGl6ZXJCdWZmZXIpIFRvU3FsKCkgKHN0cmluZywgW11pbnRlcmZhY2V7fSwgZXJyb3IpIHsKCXJldHVybiBiLlN0cmluZygpLCBiLmFyZ3MsIGIuZXJyCn0KCi8vIHdoZW5QYXJ0IGlzIGEgaGVscGVyIHN0cnVjdHVyZSB0byBkZXNjcmliZSBTUUxzICJXSEVOIC4uLiBUSEVOIC4uLiIgZXhwcmVzc2lvbgp0eXBlIHdoZW5QYXJ0IHN0cnVjdCB7Cgl3aGVuIFNxbGl6ZXIKCXRoZW4gU3FsaXplcgp9CgpmdW5jIG5ld1doZW5QYXJ0KHdoZW4gaW50ZXJmYWNle30sIHRoZW4gaW50ZXJmYWNle30pIHdoZW5QYXJ0IHsKCXJldHVybiB3aGVuUGFydHtuZXdQYXJ0KHdoZW4pLCBuZXdQYXJ0KHRoZW4pfQp9CgovLyBjYXNlRGF0YSBob2xkcyBhbGwgdGhlIGRhdGEgcmVxdWlyZWQgdG8gYnVpbGQgYSBDQVNFIFNRTCBjb25zdHJ1Y3QKdHlwZSBjYXNlRGF0YSBzdHJ1Y3QgewoJV2hhdCAgICAgIFNxbGl6ZXIKCVdoZW5QYXJ0cyBbXXdoZW5QYXJ0CglFbHNlICAgICAgU3FsaXplcgp9CgovLyBUb1NxbCBpbXBsZW1lbnRzIFNxbGl6ZXIKZnVuYyAoZCAqY2FzZURhdGEpIFRvU3FsKCkgKHNxbFN0ciBzdHJpbmcsIGFyZ3MgW11pbnRlcmZhY2V7fSwgZXJyIGVycm9yKSB7CglpZiBsZW4oZC5XaGVuUGFydHMpID09IDAgewoJCWVyciA9IGVycm9ycy5OZXcoImNhc2UgZXhwcmVzc2lvbiBtdXN0IGNvbnRhaW4gYXQgbGVhc2Ugb25lIFdIRU4gY2xhdXNlIikKCgkJcmV0dXJuCgl9CgoJc3FsIDo9IHNxbGl6ZXJCdWZmZXJ7fQoKCXNxbC5Xcml0ZVN0cmluZygiQ0FTRSAiKQoJaWYgZC5XaGF0ICE9IG5pbCB7CgkJc3FsLldyaXRlU3FsKGQuV2hhdCkKCX0KCglmb3IgXywgcCA6PSByYW5nZSBkLldoZW5QYXJ0cyB7CgkJc3FsLldyaXRlU3RyaW5nKCJXSEVOICIpCgkJc3FsLldyaXRlU3FsKHAud2hlbikKCQlzcWwuV3JpdGVTdHJpbmcoIlRIRU4gIikKCQlzcWwuV3JpdGVTcWwocC50aGVuKQoJfQoKCWlmIGQuRWxzZSAhPSBuaWwgewoJCXNxbC5Xcml0ZVN0cmluZygiRUxTRSAiKQoJCXNxbC5Xcml0ZVNxbChkLkVsc2UpCgl9CgoJc3FsLldyaXRlU3RyaW5nKCJFTkQiKQoKCXJldHVybiBzcWwuVG9TcWwoKQp9CgovLyBDYXNlQnVpbGRlciBidWlsZHMgU1FMIENBU0UgY29uc3RydWN0IHdoaWNoIGNvdWxkIGJlIHVzZWQgYXMgcGFydHMgb2YgcXVlcmllcy4KdHlwZSBDYXNlQnVpbGRlciBidWlsZGVyLkJ1aWxkZXIKCi8vIFRvU3FsIGJ1aWxkcyB0aGUgcXVlcnkgaW50byBhIFNRTCBzdHJpbmcgYW5kIGJvdW5kIGFyZ3MuCmZ1bmMgKGIgQ2FzZUJ1aWxkZXIpIFRvU3FsKCkgKHN0cmluZywgW11pbnRlcmZhY2V7fSwgZXJyb3IpIHsKCWRhdGEgOj0gYnVpbGRlci5HZXRTdHJ1Y3QoYikuKGNhc2VEYXRhKQoJcmV0dXJuIGRhdGEuVG9TcWwoKQp9CgovLyBNdXN0U3FsIGJ1aWxkcyB0aGUgcXVlcnkgaW50byBhIFNRTCBzdHJpbmcgYW5kIGJvdW5kIGFyZ3MuCi8vIEl0IHBhbmljcyBpZiB0aGVyZSBhcmUgYW55IGVycm9ycy4KZnVuYyAoYiBDYXNlQnVpbGRlcikgTXVzdFNxbCgpIChzdHJpbmcsIFtdaW50ZXJmYWNle30pIHsKCXNxbCwgYXJncywgZXJyIDo9IGIuVG9TcWwoKQoJaWYgZXJyICE9IG5pbCB7CgkJcGFuaWMoZXJyKQoJfQoJcmV0dXJuIHNxbCwgYXJncwp9CgovLyB3aGF0IHNldHMgb3B0aW9uYWwgdmFsdWUgZm9yIENBU0UgY29uc3RydWN0ICJDQVNFIFt2YWx1ZV0gLi4uIgpmdW5jIChiIENhc2VCdWlsZGVyKSB3aGF0KGV4cHIgaW50ZXJmYWNle30pIENhc2VCdWlsZGVyIHsKCXJldHVybiBidWlsZGVyLlNldChiLCAiV2hhdCIsIG5ld1BhcnQoZXhwcikpLihDYXNlQnVpbGRlcikKfQoKLy8gV2hlbiBhZGRzICJXSEVOIC4uLiBUSEVOIC4uLiIgcGFydCB0byBDQVNFIGNvbnN0cnVjdApmdW5jIChiIENhc2VCdWlsZGVyKSBXaGVuKHdoZW4gaW50ZXJmYWNle30sIHRoZW4gaW50ZXJmYWNle30pIENhc2VCdWlsZGVyIHsKCS8vIFRPRE86IHBlcmZvcm1hbmNlIGhpbnQ6IHJlcGxhY2Ugc2xpY2Ugb2YgV2hlblBhcnQgd2l0aCBqdXN0IHNsaWNlIG9mIHBhcnRzCgkvLyB3aGVyZSBldmVuIGluZGljZXMgb2YgdGhlIHNsaWNlIGJlbG9uZyB0byAid2hlbiJzIGFuZCBvZGQgaW5kaWNlcyBiZWxvbmcgdG8gInRoZW4icwoJcmV0dXJuIGJ1aWxkZXIuQXBwZW5kKGIsICJXaGVuUGFydHMiLCBuZXdXaGVuUGFydCh3aGVuLCB0aGVuKSkuKENhc2VCdWlsZGVyKQp9CgovLyBXaGF0IHNldHMgb3B0aW9uYWwgIkVMU0UgLi4uIiBwYXJ0IGZvciBDQVNFIGNvbnN0cnVjdApmdW5jIChiIENhc2VCdWlsZGVyKSBFbHNlKGV4cHIgaW50ZXJmYWNle30pIENhc2VCdWlsZGVyIHsKCXJldHVybiBidWlsZGVyLlNldChiLCAiRWxzZSIsIG5ld1BhcnQoZXhwcikpLihDYXNlQnVpbGRlcikKfQo=", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/task.toml b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3bce5a052d0ec05dae131632b95d86bde36f5256 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:4f15f40b17a328eb32a4a9eab540aebb62641eb8d8b1336c2abe5aa9fce4a253" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/case_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/case_test.go new file mode 100644 index 0000000000000000000000000000000000000000..a2ad995cfe6d0bb71f0755c70268592ff94d8a1f --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/case_test.go @@ -0,0 +1,150 @@ +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestCaseWithVal(t *testing.T) { + caseStmt := Case("number"). + When("1", "one"). + When("2", "two"). + Else(Expr("?", "big number")) + + qb := Select(). + Column(caseStmt). + From("table") + sql, args, err := qb.ToSql() + + assert.NoError(t, err) + + expectedSql := "SELECT CASE number " + + "WHEN 1 THEN one " + + "WHEN 2 THEN two " + + "ELSE ? " + + "END " + + "FROM table" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"big number"} + assert.Equal(t, expectedArgs, args) +} + +func TestCaseWithComplexVal(t *testing.T) { + caseStmt := Case("? > ?", 10, 5). + When("true", "'T'") + + qb := Select(). + Column(Alias(caseStmt, "complexCase")). + From("table") + sql, args, err := qb.ToSql() + + assert.NoError(t, err) + + expectedSql := "SELECT (CASE ? > ? " + + "WHEN true THEN 'T' " + + "END) AS complexCase " + + "FROM table" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{10, 5} + assert.Equal(t, expectedArgs, args) +} + +func TestCaseWithNoVal(t *testing.T) { + caseStmt := Case(). + When(Eq{"x": 0}, "x is zero"). + When(Expr("x > ?", 1), Expr("CONCAT('x is greater than ', ?)", 2)) + + qb := Select().Column(caseStmt).From("table") + sql, args, err := qb.ToSql() + + assert.NoError(t, err) + + expectedSql := "SELECT CASE " + + "WHEN x = ? THEN x is zero " + + "WHEN x > ? THEN CONCAT('x is greater than ', ?) " + + "END " + + "FROM table" + + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{0, 1, 2} + assert.Equal(t, expectedArgs, args) +} + +func TestCaseWithExpr(t *testing.T) { + caseStmt := Case(Expr("x = ?", true)). + When("true", Expr("?", "it's true!")). + Else("42") + + qb := Select().Column(caseStmt).From("table") + sql, args, err := qb.ToSql() + + assert.NoError(t, err) + + expectedSql := "SELECT CASE x = ? " + + "WHEN true THEN ? " + + "ELSE 42 " + + "END " + + "FROM table" + + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{true, "it's true!"} + assert.Equal(t, expectedArgs, args) +} + +func TestMultipleCase(t *testing.T) { + caseStmtNoval := Case(Expr("x = ?", true)). + When("true", Expr("?", "it's true!")). + Else("42") + caseStmtExpr := Case(). + When(Eq{"x": 0}, "'x is zero'"). + When(Expr("x > ?", 1), Expr("CONCAT('x is greater than ', ?)", 2)) + + qb := Select(). + Column(Alias(caseStmtNoval, "case_noval")). + Column(Alias(caseStmtExpr, "case_expr")). + From("table") + + sql, args, err := qb.ToSql() + + assert.NoError(t, err) + + expectedSql := "SELECT " + + "(CASE x = ? WHEN true THEN ? ELSE 42 END) AS case_noval, " + + "(CASE WHEN x = ? THEN 'x is zero' WHEN x > ? THEN CONCAT('x is greater than ', ?) END) AS case_expr " + + "FROM table" + + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{ + true, "it's true!", + 0, 1, 2, + } + assert.Equal(t, expectedArgs, args) +} + +func TestCaseWithNoWhenClause(t *testing.T) { + caseStmt := Case("something"). + Else("42") + + qb := Select().Column(caseStmt).From("table") + + _, _, err := qb.ToSql() + + assert.Error(t, err) + + assert.Equal(t, "case expression must contain at lease one WHEN clause", err.Error()) +} + +func TestCaseBuilderMustSql(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("TestCaseBuilderMustSql should have panicked!") + } + }() + Case("").MustSql() +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/delete_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/delete_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..8a80b6ae502df4301a54a067896c7e31143ed427 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/delete_ctx_test.go @@ -0,0 +1,41 @@ +// +build go1.8 + +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestDeleteBuilderContextRunners(t *testing.T) { + db := &DBStub{} + b := Delete("test").Where("x = ?", 1).RunWith(db) + + expectedSql := "DELETE FROM test WHERE x = ?" + + b.ExecContext(ctx) + assert.Equal(t, expectedSql, db.LastExecSql) + + b.QueryContext(ctx) + assert.Equal(t, expectedSql, db.LastQuerySql) + + b.QueryRowContext(ctx) + assert.Equal(t, expectedSql, db.LastQueryRowSql) + + err := b.ScanContext(ctx) + assert.NoError(t, err) +} + +func TestDeleteBuilderContextNoRunner(t *testing.T) { + b := Delete("test").Where("x != ?", 0).Suffix("RETURNING x") + + _, err := b.ExecContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + _, err = b.QueryContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + err = b.ScanContext(ctx) + assert.Equal(t, RunnerNotSet, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/delete_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/delete_test.go new file mode 100644 index 0000000000000000000000000000000000000000..62691f246f11a751ec289bb34ad80bbca2d47313 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/delete_test.go @@ -0,0 +1,81 @@ +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestDeleteBuilderToSql(t *testing.T) { + b := Delete(""). + Prefix("WITH prefix AS ?", 0). + From("a"). + Where("b = ?", 1). + OrderBy("c"). + Limit(2). + Offset(3). + Suffix("RETURNING ?", 4) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := + "WITH prefix AS ? " + + "DELETE FROM a WHERE b = ? ORDER BY c LIMIT 2 OFFSET 3 " + + "RETURNING ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{0, 1, 4} + assert.Equal(t, expectedArgs, args) +} + +func TestDeleteBuilderToSqlErr(t *testing.T) { + _, _, err := Delete("").ToSql() + assert.Error(t, err) +} + +func TestDeleteBuilderMustSql(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("TestDeleteBuilderMustSql should have panicked!") + } + }() + Delete("").MustSql() +} + +func TestDeleteBuilderPlaceholders(t *testing.T) { + b := Delete("test").Where("x = ? AND y = ?", 1, 2) + + sql, _, _ := b.PlaceholderFormat(Question).ToSql() + assert.Equal(t, "DELETE FROM test WHERE x = ? AND y = ?", sql) + + sql, _, _ = b.PlaceholderFormat(Dollar).ToSql() + assert.Equal(t, "DELETE FROM test WHERE x = $1 AND y = $2", sql) +} + +func TestDeleteBuilderRunners(t *testing.T) { + db := &DBStub{} + b := Delete("test").Where("x = ?", 1).RunWith(db) + + expectedSql := "DELETE FROM test WHERE x = ?" + + b.Exec() + assert.Equal(t, expectedSql, db.LastExecSql) +} + +func TestDeleteBuilderNoRunner(t *testing.T) { + b := Delete("test") + + _, err := b.Exec() + assert.Equal(t, RunnerNotSet, err) +} + +func TestDeleteWithQuery(t *testing.T) { + db := &DBStub{} + b := Delete("test").Where("id=55").Suffix("RETURNING path").RunWith(db) + + expectedSql := "DELETE FROM test WHERE id=55 RETURNING path" + b.Query() + + assert.Equal(t, expectedSql, db.LastQuerySql) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/expr_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/expr_test.go new file mode 100644 index 0000000000000000000000000000000000000000..60d2ae5cc3020d0d40b10e3b3042114fbac6ffb4 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/expr_test.go @@ -0,0 +1,464 @@ +package squirrel + +import ( + "database/sql" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestConcatExpr(t *testing.T) { + b := ConcatExpr("COALESCE(name,", Expr("CONCAT(?,' ',?)", "f", "l"), ")") + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "COALESCE(name,CONCAT(?,' ',?))" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"f", "l"} + assert.Equal(t, expectedArgs, args) +} + +func TestConcatExprBadType(t *testing.T) { + b := ConcatExpr("prefix", 123, "suffix") + _, _, err := b.ToSql() + assert.Error(t, err) + assert.Contains(t, err.Error(), "123 is not") +} + +func TestEqToSql(t *testing.T) { + b := Eq{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id = ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestEqEmptyToSql(t *testing.T) { + sql, args, err := Eq{}.ToSql() + assert.NoError(t, err) + + expectedSql := "(1=1)" + assert.Equal(t, expectedSql, sql) + assert.Empty(t, args) +} + +func TestEqInToSql(t *testing.T) { + b := Eq{"id": []int{1, 2, 3}} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id IN (?,?,?)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2, 3} + assert.Equal(t, expectedArgs, args) +} + +func TestNotEqToSql(t *testing.T) { + b := NotEq{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id <> ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestEqNotInToSql(t *testing.T) { + b := NotEq{"id": []int{1, 2, 3}} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id NOT IN (?,?,?)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2, 3} + assert.Equal(t, expectedArgs, args) +} + +func TestEqInEmptyToSql(t *testing.T) { + b := Eq{"id": []int{}} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "(1=0)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{} + assert.Equal(t, expectedArgs, args) +} + +func TestNotEqInEmptyToSql(t *testing.T) { + b := NotEq{"id": []int{}} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "(1=1)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{} + assert.Equal(t, expectedArgs, args) +} + +func TestEqBytesToSql(t *testing.T) { + b := Eq{"id": []byte("test")} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id = ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{[]byte("test")} + assert.Equal(t, expectedArgs, args) +} + +func TestLtToSql(t *testing.T) { + b := Lt{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id < ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestLtOrEqToSql(t *testing.T) { + b := LtOrEq{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id <= ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestGtToSql(t *testing.T) { + b := Gt{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id > ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestGtOrEqToSql(t *testing.T) { + b := GtOrEq{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id >= ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestExprNilToSql(t *testing.T) { + var b Sqlizer + b = NotEq{"name": nil} + sql, args, err := b.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + + expectedSql := "name IS NOT NULL" + assert.Equal(t, expectedSql, sql) + + b = Eq{"name": nil} + sql, args, err = b.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + + expectedSql = "name IS NULL" + assert.Equal(t, expectedSql, sql) +} + +func TestNullTypeString(t *testing.T) { + var b Sqlizer + var name sql.NullString + + b = Eq{"name": name} + sql, args, err := b.ToSql() + + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "name IS NULL", sql) + + name.Scan("Name") + b = Eq{"name": name} + sql, args, err = b.ToSql() + + assert.NoError(t, err) + assert.Equal(t, []interface{}{"Name"}, args) + assert.Equal(t, "name = ?", sql) +} + +func TestNullTypeInt64(t *testing.T) { + var userID sql.NullInt64 + userID.Scan(nil) + b := Eq{"user_id": userID} + sql, args, err := b.ToSql() + + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "user_id IS NULL", sql) + + userID.Scan(int64(10)) + b = Eq{"user_id": userID} + sql, args, err = b.ToSql() + + assert.NoError(t, err) + assert.Equal(t, []interface{}{int64(10)}, args) + assert.Equal(t, "user_id = ?", sql) +} + +func TestNilPointer(t *testing.T) { + var name *string = nil + eq := Eq{"name": name} + sql, args, err := eq.ToSql() + + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "name IS NULL", sql) + + neq := NotEq{"name": name} + sql, args, err = neq.ToSql() + + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "name IS NOT NULL", sql) + + var ids *[]int = nil + eq = Eq{"id": ids} + sql, args, err = eq.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "id IS NULL", sql) + + neq = NotEq{"id": ids} + sql, args, err = neq.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "id IS NOT NULL", sql) + + var ida *[3]int = nil + eq = Eq{"id": ida} + sql, args, err = eq.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "id IS NULL", sql) + + neq = NotEq{"id": ida} + sql, args, err = neq.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "id IS NOT NULL", sql) + +} + +func TestNotNilPointer(t *testing.T) { + c := "Name" + name := &c + eq := Eq{"name": name} + sql, args, err := eq.ToSql() + + assert.NoError(t, err) + assert.Equal(t, []interface{}{"Name"}, args) + assert.Equal(t, "name = ?", sql) + + neq := NotEq{"name": name} + sql, args, err = neq.ToSql() + + assert.NoError(t, err) + assert.Equal(t, []interface{}{"Name"}, args) + assert.Equal(t, "name <> ?", sql) + + s := []int{1, 2, 3} + ids := &s + eq = Eq{"id": ids} + sql, args, err = eq.ToSql() + assert.NoError(t, err) + assert.Equal(t, []interface{}{1, 2, 3}, args) + assert.Equal(t, "id IN (?,?,?)", sql) + + neq = NotEq{"id": ids} + sql, args, err = neq.ToSql() + assert.NoError(t, err) + assert.Equal(t, []interface{}{1, 2, 3}, args) + assert.Equal(t, "id NOT IN (?,?,?)", sql) + + a := [3]int{1, 2, 3} + ida := &a + eq = Eq{"id": ida} + sql, args, err = eq.ToSql() + assert.NoError(t, err) + assert.Equal(t, []interface{}{1, 2, 3}, args) + assert.Equal(t, "id IN (?,?,?)", sql) + + neq = NotEq{"id": ida} + sql, args, err = neq.ToSql() + assert.NoError(t, err) + assert.Equal(t, []interface{}{1, 2, 3}, args) + assert.Equal(t, "id NOT IN (?,?,?)", sql) +} + +func TestEmptyAndToSql(t *testing.T) { + sql, args, err := And{}.ToSql() + assert.NoError(t, err) + + expectedSql := "(1=1)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{} + assert.Equal(t, expectedArgs, args) +} + +func TestEmptyOrToSql(t *testing.T) { + sql, args, err := Or{}.ToSql() + assert.NoError(t, err) + + expectedSql := "(1=0)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{} + assert.Equal(t, expectedArgs, args) +} + +func TestLikeToSql(t *testing.T) { + b := Like{"name": "%irrel"} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "name LIKE ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"%irrel"} + assert.Equal(t, expectedArgs, args) +} + +func TestNotLikeToSql(t *testing.T) { + b := NotLike{"name": "%irrel"} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "name NOT LIKE ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"%irrel"} + assert.Equal(t, expectedArgs, args) +} + +func TestILikeToSql(t *testing.T) { + b := ILike{"name": "sq%"} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "name ILIKE ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"sq%"} + assert.Equal(t, expectedArgs, args) +} + +func TestNotILikeToSql(t *testing.T) { + b := NotILike{"name": "sq%"} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "name NOT ILIKE ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"sq%"} + assert.Equal(t, expectedArgs, args) +} + +func TestSqlEqOrder(t *testing.T) { + b := Eq{"a": 1, "b": 2, "c": 3} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "a = ? AND b = ? AND c = ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2, 3} + assert.Equal(t, expectedArgs, args) +} + +func TestSqlLtOrder(t *testing.T) { + b := Lt{"a": 1, "b": 2, "c": 3} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "a < ? AND b < ? AND c < ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2, 3} + assert.Equal(t, expectedArgs, args) +} + +func TestExprEscaped(t *testing.T) { + b := Expr("count(??)", Expr("x")) + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "count(??)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{Expr("x")} + assert.Equal(t, expectedArgs, args) +} + +func TestExprRecursion(t *testing.T) { + { + b := Expr("count(?)", Expr("nullif(a,?)", "b")) + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "count(nullif(a,?))" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"b"} + assert.Equal(t, expectedArgs, args) + } + { + b := Expr("extract(? from ?)", Expr("epoch"), "2001-02-03") + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "extract(epoch from ?)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"2001-02-03"} + assert.Equal(t, expectedArgs, args) + } + { + b := Expr("JOIN t1 ON ?", And{Eq{"id": 1}, Expr("NOT c1"), Expr("? @@ ?", "x", "y")}) + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "JOIN t1 ON (id = ? AND NOT c1 AND ? @@ ?)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, "x", "y"} + assert.Equal(t, expectedArgs, args) + } +} + +func ExampleEq() { + Select("id", "created", "first_name").From("users").Where(Eq{ + "company": 20, + }) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/insert_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/insert_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..0e02ed476e05a35a22e8d298fbf53c3ca4fed0d7 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/insert_ctx_test.go @@ -0,0 +1,41 @@ +// +build go1.8 + +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestInsertBuilderContextRunners(t *testing.T) { + db := &DBStub{} + b := Insert("test").Values(1).RunWith(db) + + expectedSql := "INSERT INTO test VALUES (?)" + + b.ExecContext(ctx) + assert.Equal(t, expectedSql, db.LastExecSql) + + b.QueryContext(ctx) + assert.Equal(t, expectedSql, db.LastQuerySql) + + b.QueryRowContext(ctx) + assert.Equal(t, expectedSql, db.LastQueryRowSql) + + err := b.ScanContext(ctx) + assert.NoError(t, err) +} + +func TestInsertBuilderContextNoRunner(t *testing.T) { + b := Insert("test").Values(1) + + _, err := b.ExecContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + _, err = b.QueryContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + err = b.ScanContext(ctx) + assert.Equal(t, RunnerNotSet, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/insert_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/insert_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ced2313547fd37c5f23fc815a4394e6d8b61f197 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/insert_test.go @@ -0,0 +1,112 @@ +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestInsertBuilderToSql(t *testing.T) { + b := Insert(""). + Prefix("WITH prefix AS ?", 0). + Into("a"). + Options("DELAYED", "IGNORE"). + Columns("b", "c"). + Values(1, 2). + Values(3, Expr("? + 1", 4)). + Suffix("RETURNING ?", 5) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSQL := + "WITH prefix AS ? " + + "INSERT DELAYED IGNORE INTO a (b,c) VALUES (?,?),(?,? + 1) " + + "RETURNING ?" + assert.Equal(t, expectedSQL, sql) + + expectedArgs := []interface{}{0, 1, 2, 3, 4, 5} + assert.Equal(t, expectedArgs, args) +} + +func TestInsertBuilderToSqlErr(t *testing.T) { + _, _, err := Insert("").Values(1).ToSql() + assert.Error(t, err) + + _, _, err = Insert("x").ToSql() + assert.Error(t, err) +} + +func TestInsertBuilderMustSql(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("TestInsertBuilderMustSql should have panicked!") + } + }() + Insert("").MustSql() +} + +func TestInsertBuilderPlaceholders(t *testing.T) { + b := Insert("test").Values(1, 2) + + sql, _, _ := b.PlaceholderFormat(Question).ToSql() + assert.Equal(t, "INSERT INTO test VALUES (?,?)", sql) + + sql, _, _ = b.PlaceholderFormat(Dollar).ToSql() + assert.Equal(t, "INSERT INTO test VALUES ($1,$2)", sql) +} + +func TestInsertBuilderRunners(t *testing.T) { + db := &DBStub{} + b := Insert("test").Values(1).RunWith(db) + + expectedSQL := "INSERT INTO test VALUES (?)" + + b.Exec() + assert.Equal(t, expectedSQL, db.LastExecSql) +} + +func TestInsertBuilderNoRunner(t *testing.T) { + b := Insert("test").Values(1) + + _, err := b.Exec() + assert.Equal(t, RunnerNotSet, err) +} + +func TestInsertBuilderSetMap(t *testing.T) { + b := Insert("table").SetMap(Eq{"field1": 1, "field2": 2, "field3": 3}) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSQL := "INSERT INTO table (field1,field2,field3) VALUES (?,?,?)" + assert.Equal(t, expectedSQL, sql) + + expectedArgs := []interface{}{1, 2, 3} + assert.Equal(t, expectedArgs, args) +} + +func TestInsertBuilderSelect(t *testing.T) { + sb := Select("field1").From("table1").Where(Eq{"field1": 1}) + ib := Insert("table2").Columns("field1").Select(sb) + + sql, args, err := ib.ToSql() + assert.NoError(t, err) + + expectedSQL := "INSERT INTO table2 (field1) SELECT field1 FROM table1 WHERE field1 = ?" + assert.Equal(t, expectedSQL, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestInsertBuilderReplace(t *testing.T) { + b := Replace("table").Values(1) + + expectedSQL := "REPLACE INTO table VALUES (?)" + + sql, _, err := b.ToSql() + assert.NoError(t, err) + + assert.Equal(t, expectedSQL, sql) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/integration/integration_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/integration/integration_test.go new file mode 100644 index 0000000000000000000000000000000000000000..e861e7f6f36595633e7ce3bc0495283aa417dc52 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/integration/integration_test.go @@ -0,0 +1,135 @@ +package integration + +import ( + "context" + "database/sql" + "flag" + "fmt" + "os" + "testing" + + "github.com/stretchr/testify/assert" + + sqrl "github.com/Masterminds/squirrel" + + _ "github.com/go-sql-driver/mysql" + _ "github.com/lib/pq" + _ "github.com/mattn/go-sqlite3" +) + +const ( + testSchema = ` + CREATE TABLE squirrel_integration ( k INT, v TEXT )` + testData = ` + INSERT INTO squirrel_integration VALUES + (1, 'foo'), + (3, 'bar'), + (2, 'foo'), + (4, 'baz') + ` +) + +var ( + sb sqrl.StatementBuilderType +) + +func TestMain(m *testing.M) { + var driver, dataSource string + flag.StringVar(&driver, "driver", "", "integration database driver") + flag.StringVar(&dataSource, "dataSource", "", "integration database data source") + flag.Parse() + + if driver == "" { + driver = "sqlite3" + } + + if driver == "sqlite3" && dataSource == "" { + dataSource = ":memory:" + } + + db, err := sql.Open(driver, dataSource) + if err != nil { + fmt.Printf("error opening database: %v\n", err) + os.Exit(-1) + } + + _, err = db.Exec(testSchema) + if err != nil { + fmt.Printf("error creating test schema: %v\n", err) + os.Exit(-2) + } + + defer func() { + _, err = db.Exec("DROP TABLE squirrel_integration") + fmt.Printf("error removing test schema: %v\n", err) + }() + + _, err = db.Exec(testData) + if err != nil { + fmt.Printf("error inserting test data: %v\n", err) + os.Exit(-3) + } + + sb = sqrl.StatementBuilder.RunWith(db) + + if driver == "postgres" { + sb = sb.PlaceholderFormat(sqrl.Dollar) + } + + os.Exit(m.Run()) +} + +func assertVals(t *testing.T, s sqrl.SelectBuilder, expected ...string) { + rows, err := s.Query() + assert.NoError(t, err) + defer rows.Close() + + vals := make([]string, len(expected)) + for i := range vals { + assert.True(t, rows.Next()) + assert.NoError(t, rows.Scan(&vals[i])) + } + assert.False(t, rows.Next()) + + if expected != nil { + assert.Equal(t, expected, vals) + } +} + +func TestSimpleSelect(t *testing.T) { + assertVals( + t, + sb.Select("v").From("squirrel_integration"), + "foo", "bar", "foo", "baz") +} + +func TestEq(t *testing.T) { + s := sb.Select("v").From("squirrel_integration") + assertVals(t, s.Where(sqrl.Eq{"k": 4}), "baz") + assertVals(t, s.Where(sqrl.NotEq{"k": 2}), "foo", "bar", "baz") + assertVals(t, s.Where(sqrl.Eq{"k": []int{1, 4}}), "foo", "baz") + assertVals(t, s.Where(sqrl.NotEq{"k": []int{1, 4}}), "bar", "foo") + assertVals(t, s.Where(sqrl.Eq{"k": nil})) + assertVals(t, s.Where(sqrl.NotEq{"k": nil}), "foo", "bar", "foo", "baz") + assertVals(t, s.Where(sqrl.Eq{"k": []int{}})) + assertVals(t, s.Where(sqrl.NotEq{"k": []int{}}), "foo", "bar", "foo", "baz") +} + +func TestIneq(t *testing.T) { + s := sb.Select("v").From("squirrel_integration") + assertVals(t, s.Where(sqrl.Lt{"k": 3}), "foo", "foo") + assertVals(t, s.Where(sqrl.Gt{"k": 3}), "baz") +} + +func TestConj(t *testing.T) { + s := sb.Select("v").From("squirrel_integration") + assertVals(t, s.Where(sqrl.And{sqrl.Gt{"k": 1}, sqrl.Lt{"k": 4}}), "bar", "foo") + assertVals(t, s.Where(sqrl.Or{sqrl.Gt{"k": 3}, sqrl.Lt{"k": 2}}), "foo", "baz") +} + +func TestContext(t *testing.T) { + s := sb.Select("v").From("squirrel_integration") + ctx := context.Background() + _, err := s.QueryContext(ctx) + assert.NoError(t, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/placeholder_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/placeholder_test.go new file mode 100644 index 0000000000000000000000000000000000000000..8e7f43f4929409739603e5c61bd74be940f016b5 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/placeholder_test.go @@ -0,0 +1,67 @@ +package squirrel + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestQuestion(t *testing.T) { + sql := "x = ? AND y = ?" + s, _ := Question.ReplacePlaceholders(sql) + assert.Equal(t, sql, s) +} + +func TestDollar(t *testing.T) { + sql := "x = ? AND y = ?" + s, _ := Dollar.ReplacePlaceholders(sql) + assert.Equal(t, "x = $1 AND y = $2", s) +} + +func TestColon(t *testing.T) { + sql := "x = ? AND y = ?" + s, _ := Colon.ReplacePlaceholders(sql) + assert.Equal(t, "x = :1 AND y = :2", s) +} + +func TestAtp(t *testing.T) { + sql := "x = ? AND y = ?" + s, _ := AtP.ReplacePlaceholders(sql) + assert.Equal(t, "x = @p1 AND y = @p2", s) +} + +func TestPlaceholders(t *testing.T) { + assert.Equal(t, Placeholders(2), "?,?") +} + +func TestEscapeDollar(t *testing.T) { + sql := "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ??| array['?'] AND enabled = ?" + s, _ := Dollar.ReplacePlaceholders(sql) + assert.Equal(t, "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ?| array['$1'] AND enabled = $2", s) +} + +func TestEscapeColon(t *testing.T) { + sql := "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ??| array['?'] AND enabled = ?" + s, _ := Colon.ReplacePlaceholders(sql) + assert.Equal(t, "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ?| array[':1'] AND enabled = :2", s) +} + +func TestEscapeAtp(t *testing.T) { + sql := "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ??| array['?'] AND enabled = ?" + s, _ := AtP.ReplacePlaceholders(sql) + assert.Equal(t, "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ?| array['@p1'] AND enabled = @p2", s) +} + +func BenchmarkPlaceholdersArray(b *testing.B) { + var count = b.N + placeholders := make([]string, count) + for i := 0; i < count; i++ { + placeholders[i] = "?" + } + var _ = strings.Join(placeholders, ",") +} + +func BenchmarkPlaceholdersStrings(b *testing.B) { + Placeholders(b.N) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/row_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/row_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ebeeb85485799fc47480555357873b4c4656c1c0 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/row_test.go @@ -0,0 +1,34 @@ +package squirrel + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" +) + +type RowStub struct { + Scanned bool +} + +func (r *RowStub) Scan(_ ...interface{}) error { + r.Scanned = true + return nil +} + +func TestRowScan(t *testing.T) { + stub := &RowStub{} + row := &Row{RowScanner: stub} + err := row.Scan() + assert.True(t, stub.Scanned, "row was not scanned") + assert.NoError(t, err) +} + +func TestRowScanErr(t *testing.T) { + stub := &RowStub{} + rowErr := fmt.Errorf("scan err") + row := &Row{RowScanner: stub, err: rowErr} + err := row.Scan() + assert.False(t, stub.Scanned, "row was scanned") + assert.Equal(t, rowErr, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/select_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/select_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b36ae44285e9ced8b14376ef6b060325370137d0 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/select_ctx_test.go @@ -0,0 +1,41 @@ +// +build go1.8 + +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestSelectBuilderContextRunners(t *testing.T) { + db := &DBStub{} + b := Select("test").RunWith(db) + + expectedSql := "SELECT test" + + b.ExecContext(ctx) + assert.Equal(t, expectedSql, db.LastExecSql) + + b.QueryContext(ctx) + assert.Equal(t, expectedSql, db.LastQuerySql) + + b.QueryRowContext(ctx) + assert.Equal(t, expectedSql, db.LastQueryRowSql) + + err := b.ScanContext(ctx) + assert.NoError(t, err) +} + +func TestSelectBuilderContextNoRunner(t *testing.T) { + b := Select("test") + + _, err := b.ExecContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + _, err = b.QueryContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + err = b.ScanContext(ctx) + assert.Equal(t, RunnerNotSet, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/select_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/select_test.go new file mode 100644 index 0000000000000000000000000000000000000000..80161bf5a947cbb02b3039b857b71563630f2ad0 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/select_test.go @@ -0,0 +1,463 @@ +package squirrel + +import ( + "database/sql" + "fmt" + "log" + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +func TestSelectBuilderToSql(t *testing.T) { + subQ := Select("aa", "bb").From("dd") + b := Select("a", "b"). + Prefix("WITH prefix AS ?", 0). + Distinct(). + Columns("c"). + Column("IF(d IN ("+Placeholders(3)+"), 1, 0) as stat_column", 1, 2, 3). + Column(Expr("a > ?", 100)). + Column(Alias(Eq{"b": []int{101, 102, 103}}, "b_alias")). + Column(Alias(subQ, "subq")). + From("e"). + JoinClause("CROSS JOIN j1"). + Join("j2"). + LeftJoin("j3"). + RightJoin("j4"). + InnerJoin("j5"). + CrossJoin("j6"). + Where("f = ?", 4). + Where(Eq{"g": 5}). + Where(map[string]interface{}{"h": 6}). + Where(Eq{"i": []int{7, 8, 9}}). + Where(Or{Expr("j = ?", 10), And{Eq{"k": 11}, Expr("true")}}). + GroupBy("l"). + Having("m = n"). + OrderByClause("? DESC", 1). + OrderBy("o ASC", "p DESC"). + Limit(12). + Offset(13). + Suffix("FETCH FIRST ? ROWS ONLY", 14) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := + "WITH prefix AS ? " + + "SELECT DISTINCT a, b, c, IF(d IN (?,?,?), 1, 0) as stat_column, a > ?, " + + "(b IN (?,?,?)) AS b_alias, " + + "(SELECT aa, bb FROM dd) AS subq " + + "FROM e " + + "CROSS JOIN j1 JOIN j2 LEFT JOIN j3 RIGHT JOIN j4 INNER JOIN j5 CROSS JOIN j6 " + + "WHERE f = ? AND g = ? AND h = ? AND i IN (?,?,?) AND (j = ? OR (k = ? AND true)) " + + "GROUP BY l HAVING m = n ORDER BY ? DESC, o ASC, p DESC LIMIT 12 OFFSET 13 " + + "FETCH FIRST ? ROWS ONLY" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{0, 1, 2, 3, 100, 101, 102, 103, 4, 5, 6, 7, 8, 9, 10, 11, 1, 14} + assert.Equal(t, expectedArgs, args) +} + +func TestSelectBuilderFromSelect(t *testing.T) { + subQ := Select("c").From("d").Where(Eq{"i": 0}) + b := Select("a", "b").FromSelect(subQ, "subq") + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "SELECT a, b FROM (SELECT c FROM d WHERE i = ?) AS subq" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{0} + assert.Equal(t, expectedArgs, args) +} + +func TestSelectBuilderFromSelectNestedDollarPlaceholders(t *testing.T) { + subQ := Select("c"). + From("t"). + Where(Gt{"c": 1}). + PlaceholderFormat(Dollar) + b := Select("c"). + FromSelect(subQ, "subq"). + Where(Lt{"c": 2}). + PlaceholderFormat(Dollar) + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "SELECT c FROM (SELECT c FROM t WHERE c > $1) AS subq WHERE c < $2" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2} + assert.Equal(t, expectedArgs, args) +} + +func TestSelectBuilderToSqlErr(t *testing.T) { + _, _, err := Select().From("x").ToSql() + assert.Error(t, err) +} + +func TestSelectBuilderPlaceholders(t *testing.T) { + b := Select("test").Where("x = ? AND y = ?") + + sql, _, _ := b.PlaceholderFormat(Question).ToSql() + assert.Equal(t, "SELECT test WHERE x = ? AND y = ?", sql) + + sql, _, _ = b.PlaceholderFormat(Dollar).ToSql() + assert.Equal(t, "SELECT test WHERE x = $1 AND y = $2", sql) + + sql, _, _ = b.PlaceholderFormat(Colon).ToSql() + assert.Equal(t, "SELECT test WHERE x = :1 AND y = :2", sql) + + sql, _, _ = b.PlaceholderFormat(AtP).ToSql() + assert.Equal(t, "SELECT test WHERE x = @p1 AND y = @p2", sql) +} + +func TestSelectBuilderRunners(t *testing.T) { + db := &DBStub{} + b := Select("test").RunWith(db) + + expectedSql := "SELECT test" + + b.Exec() + assert.Equal(t, expectedSql, db.LastExecSql) + + b.Query() + assert.Equal(t, expectedSql, db.LastQuerySql) + + b.QueryRow() + assert.Equal(t, expectedSql, db.LastQueryRowSql) + + err := b.Scan() + assert.NoError(t, err) +} + +func TestSelectBuilderNoRunner(t *testing.T) { + b := Select("test") + + _, err := b.Exec() + assert.Equal(t, RunnerNotSet, err) + + _, err = b.Query() + assert.Equal(t, RunnerNotSet, err) + + err = b.Scan() + assert.Equal(t, RunnerNotSet, err) +} + +func TestSelectBuilderSimpleJoin(t *testing.T) { + + expectedSql := "SELECT * FROM bar JOIN baz ON bar.foo = baz.foo" + expectedArgs := []interface{}(nil) + + b := Select("*").From("bar").Join("baz ON bar.foo = baz.foo") + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + assert.Equal(t, expectedSql, sql) + assert.Equal(t, args, expectedArgs) +} + +func TestSelectBuilderParamJoin(t *testing.T) { + + expectedSql := "SELECT * FROM bar JOIN baz ON bar.foo = baz.foo AND baz.foo = ?" + expectedArgs := []interface{}{42} + + b := Select("*").From("bar").Join("baz ON bar.foo = baz.foo AND baz.foo = ?", 42) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + assert.Equal(t, expectedSql, sql) + assert.Equal(t, args, expectedArgs) +} + +func TestSelectBuilderNestedSelectJoin(t *testing.T) { + + expectedSql := "SELECT * FROM bar JOIN ( SELECT * FROM baz WHERE foo = ? ) r ON bar.foo = r.foo" + expectedArgs := []interface{}{42} + + nestedSelect := Select("*").From("baz").Where("foo = ?", 42) + + b := Select("*").From("bar").JoinClause(nestedSelect.Prefix("JOIN (").Suffix(") r ON bar.foo = r.foo")) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + assert.Equal(t, expectedSql, sql) + assert.Equal(t, args, expectedArgs) +} + +func TestSelectWithOptions(t *testing.T) { + sql, _, err := Select("*").From("foo").Distinct().Options("SQL_NO_CACHE").ToSql() + + assert.NoError(t, err) + assert.Equal(t, "SELECT DISTINCT SQL_NO_CACHE * FROM foo", sql) +} + +func TestSelectWithRemoveLimit(t *testing.T) { + sql, _, err := Select("*").From("foo").Limit(10).RemoveLimit().ToSql() + + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM foo", sql) +} + +func TestSelectWithRemoveOffset(t *testing.T) { + sql, _, err := Select("*").From("foo").Offset(10).RemoveOffset().ToSql() + + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM foo", sql) +} + +func TestSelectBuilderNestedSelectDollar(t *testing.T) { + nestedBuilder := StatementBuilder.PlaceholderFormat(Dollar).Select("*").Prefix("NOT EXISTS ("). + From("bar").Where("y = ?", 42).Suffix(")") + outerSql, _, err := StatementBuilder.PlaceholderFormat(Dollar).Select("*"). + From("foo").Where("x = ?").Where(nestedBuilder).ToSql() + + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM foo WHERE x = $1 AND NOT EXISTS ( SELECT * FROM bar WHERE y = $2 )", outerSql) +} + +func TestSelectBuilderMustSql(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("TestSelectBuilderMustSql should have panicked!") + } + }() + // This function should cause a panic + Select().From("foo").MustSql() +} + +func TestSelectWithoutWhereClause(t *testing.T) { + sql, _, err := Select("*").From("users").ToSql() + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM users", sql) +} + +func TestSelectWithNilWhereClause(t *testing.T) { + sql, _, err := Select("*").From("users").Where(nil).ToSql() + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM users", sql) +} + +func TestSelectWithEmptyStringWhereClause(t *testing.T) { + sql, _, err := Select("*").From("users").Where("").ToSql() + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM users", sql) +} + +func TestSelectSubqueryPlaceholderNumbering(t *testing.T) { + subquery := Select("a").Where("b = ?", 1).PlaceholderFormat(Dollar) + with := subquery.Prefix("WITH a AS (").Suffix(")") + + sql, args, err := Select("*"). + PrefixExpr(with). + FromSelect(subquery, "q"). + Where("c = ?", 2). + PlaceholderFormat(Dollar). + ToSql() + assert.NoError(t, err) + + expectedSql := "WITH a AS ( SELECT a WHERE b = $1 ) SELECT * FROM (SELECT a WHERE b = $2) AS q WHERE c = $3" + assert.Equal(t, expectedSql, sql) + assert.Equal(t, []interface{}{1, 1, 2}, args) +} + +func TestSelectSubqueryInConjunctionPlaceholderNumbering(t *testing.T) { + subquery := Select("a").Where(Eq{"b": 1}).Prefix("EXISTS(").Suffix(")").PlaceholderFormat(Dollar) + + sql, args, err := Select("*"). + Where(Or{subquery}). + Where("c = ?", 2). + PlaceholderFormat(Dollar). + ToSql() + assert.NoError(t, err) + + expectedSql := "SELECT * WHERE (EXISTS( SELECT a WHERE b = $1 )) AND c = $2" + assert.Equal(t, expectedSql, sql) + assert.Equal(t, []interface{}{1, 2}, args) +} + +func TestSelectJoinClausePlaceholderNumbering(t *testing.T) { + subquery := Select("a").Where(Eq{"b": 2}).PlaceholderFormat(Dollar) + + sql, args, err := Select("t1.a"). + From("t1"). + Where(Eq{"a": 1}). + JoinClause(subquery.Prefix("JOIN (").Suffix(") t2 ON (t1.a = t2.a)")). + PlaceholderFormat(Dollar). + ToSql() + assert.NoError(t, err) + + expectedSql := "SELECT t1.a FROM t1 JOIN ( SELECT a WHERE b = $1 ) t2 ON (t1.a = t2.a) WHERE a = $2" + assert.Equal(t, expectedSql, sql) + assert.Equal(t, []interface{}{2, 1}, args) +} + +func ExampleSelect() { + Select("id", "created", "first_name").From("users") // ... continue building up your query + + // sql methods in select columns are ok + Select("first_name", "count(*)").From("users") + + // column aliases are ok too + Select("first_name", "count(*) as n_users").From("users") +} + +func ExampleSelectBuilder_From() { + Select("id", "created", "first_name").From("users") // ... continue building up your query +} + +func ExampleSelectBuilder_Where() { + companyId := 20 + Select("id", "created", "first_name").From("users").Where("company = ?", companyId) +} + +func ExampleSelectBuilder_Where_helpers() { + companyId := 20 + + Select("id", "created", "first_name").From("users").Where(Eq{ + "company": companyId, + }) + + Select("id", "created", "first_name").From("users").Where(GtOrEq{ + "created": time.Now().AddDate(0, 0, -7), + }) + + Select("id", "created", "first_name").From("users").Where(And{ + GtOrEq{ + "created": time.Now().AddDate(0, 0, -7), + }, + Eq{ + "company": companyId, + }, + }) +} + +func ExampleSelectBuilder_Where_multiple() { + companyId := 20 + + // multiple where's are ok + + Select("id", "created", "first_name"). + From("users"). + Where("company = ?", companyId). + Where(GtOrEq{ + "created": time.Now().AddDate(0, 0, -7), + }) +} + +func ExampleSelectBuilder_FromSelect() { + usersByCompany := Select("company", "count(*) as n_users").From("users").GroupBy("company") + query := Select("company.id", "company.name", "users_by_company.n_users"). + FromSelect(usersByCompany, "users_by_company"). + Join("company on company.id = users_by_company.company") + + sql, _, _ := query.ToSql() + fmt.Println(sql) + + // Output: SELECT company.id, company.name, users_by_company.n_users FROM (SELECT company, count(*) as n_users FROM users GROUP BY company) AS users_by_company JOIN company on company.id = users_by_company.company +} + +func ExampleSelectBuilder_Columns() { + query := Select("id").Columns("created", "first_name").From("users") + + sql, _, _ := query.ToSql() + fmt.Println(sql) + // Output: SELECT id, created, first_name FROM users +} + +func ExampleSelectBuilder_Columns_order() { + // out of order is ok too + query := Select("id").Columns("created").From("users").Columns("first_name") + + sql, _, _ := query.ToSql() + fmt.Println(sql) + // Output: SELECT id, created, first_name FROM users +} + +func ExampleSelectBuilder_Scan() { + + var db *sql.DB + + query := Select("id", "created", "first_name").From("users") + query = query.RunWith(db) + + var id int + var created time.Time + var firstName string + + if err := query.Scan(&id, &created, &firstName); err != nil { + log.Println(err) + return + } +} + +func ExampleSelectBuilder_ScanContext() { + + var db *sql.DB + + query := Select("id", "created", "first_name").From("users") + query = query.RunWith(db) + + var id int + var created time.Time + var firstName string + + if err := query.ScanContext(ctx, &id, &created, &firstName); err != nil { + log.Println(err) + return + } +} + +func ExampleSelectBuilder_RunWith() { + + var db *sql.DB + + query := Select("id", "created", "first_name").From("users").RunWith(db) + + var id int + var created time.Time + var firstName string + + if err := query.Scan(&id, &created, &firstName); err != nil { + log.Println(err) + return + } +} + +func ExampleSelectBuilder_ToSql() { + + var db *sql.DB + + query := Select("id", "created", "first_name").From("users") + + sql, args, err := query.ToSql() + if err != nil { + log.Println(err) + return + } + + rows, err := db.Query(sql, args...) + if err != nil { + log.Println(err) + return + } + + defer rows.Close() + + for rows.Next() { + // scan... + } +} + +func TestRemoveColumns(t *testing.T) { + query := Select("id"). + From("users"). + RemoveColumns() + query = query.Columns("name") + sql, _, err := query.ToSql() + assert.NoError(t, err) + assert.Equal(t, "SELECT name FROM users", sql) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/squirrel_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/squirrel_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..0e56f2b1a917331241c68f7f3d6b67ce6669a6c9 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/squirrel_ctx_test.go @@ -0,0 +1,55 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + "testing" + + "github.com/stretchr/testify/assert" +) + +func (s *DBStub) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) { + s.LastPrepareSql = query + s.PrepareCount++ + return nil, nil +} + +func (s *DBStub) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) { + s.LastExecSql = query + s.LastExecArgs = args + return nil, nil +} + +func (s *DBStub) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) { + s.LastQuerySql = query + s.LastQueryArgs = args + return nil, nil +} + +func (s *DBStub) QueryRowContext(ctx context.Context, query string, args ...interface{}) RowScanner { + s.LastQueryRowSql = query + s.LastQueryRowArgs = args + return &Row{RowScanner: &RowStub{}} +} + +var ctx = context.Background() + +func TestExecContextWith(t *testing.T) { + db := &DBStub{} + ExecContextWith(ctx, db, sqlizer) + assert.Equal(t, sqlStr, db.LastExecSql) +} + +func TestQueryContextWith(t *testing.T) { + db := &DBStub{} + QueryContextWith(ctx, db, sqlizer) + assert.Equal(t, sqlStr, db.LastQuerySql) +} + +func TestQueryRowContextWith(t *testing.T) { + db := &DBStub{} + QueryRowContextWith(ctx, db, sqlizer) + assert.Equal(t, sqlStr, db.LastQueryRowSql) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/squirrel_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/squirrel_test.go new file mode 100644 index 0000000000000000000000000000000000000000..5b6bc6268048992031dfbded60dbf0927df2a2be --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/squirrel_test.go @@ -0,0 +1,202 @@ +package squirrel + +import ( + "database/sql" + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +type DBStub struct { + err error + + LastPrepareSql string + PrepareCount int + + LastExecSql string + LastExecArgs []interface{} + + LastQuerySql string + LastQueryArgs []interface{} + + LastQueryRowSql string + LastQueryRowArgs []interface{} +} + +var StubError = fmt.Errorf("this is a stub; this is only a stub") + +func (s *DBStub) Prepare(query string) (*sql.Stmt, error) { + s.LastPrepareSql = query + s.PrepareCount++ + return nil, nil +} + +func (s *DBStub) Exec(query string, args ...interface{}) (sql.Result, error) { + s.LastExecSql = query + s.LastExecArgs = args + return nil, nil +} + +func (s *DBStub) Query(query string, args ...interface{}) (*sql.Rows, error) { + s.LastQuerySql = query + s.LastQueryArgs = args + return nil, nil +} + +func (s *DBStub) QueryRow(query string, args ...interface{}) RowScanner { + s.LastQueryRowSql = query + s.LastQueryRowArgs = args + return &Row{RowScanner: &RowStub{}} +} + +var sqlizer = Select("test") +var sqlStr = "SELECT test" + +func TestExecWith(t *testing.T) { + db := &DBStub{} + ExecWith(db, sqlizer) + assert.Equal(t, sqlStr, db.LastExecSql) +} + +func TestQueryWith(t *testing.T) { + db := &DBStub{} + QueryWith(db, sqlizer) + assert.Equal(t, sqlStr, db.LastQuerySql) +} + +func TestQueryRowWith(t *testing.T) { + db := &DBStub{} + QueryRowWith(db, sqlizer) + assert.Equal(t, sqlStr, db.LastQueryRowSql) +} + +func TestWithToSqlErr(t *testing.T) { + db := &DBStub{} + sqlizer := Select() + + _, err := ExecWith(db, sqlizer) + assert.Error(t, err) + + _, err = QueryWith(db, sqlizer) + assert.Error(t, err) + + err = QueryRowWith(db, sqlizer).Scan() + assert.Error(t, err) +} + +var testDebugUpdateSQL = Update("table").SetMap(Eq{"x": 1, "y": "val"}) +var expectedDebugUpateSQL = "UPDATE table SET x = '1', y = 'val'" + +func TestDebugSqlizerUpdateColon(t *testing.T) { + testDebugUpdateSQL.PlaceholderFormat(Colon) + assert.Equal(t, expectedDebugUpateSQL, DebugSqlizer(testDebugUpdateSQL)) +} + +func TestDebugSqlizerUpdateAtp(t *testing.T) { + testDebugUpdateSQL.PlaceholderFormat(AtP) + assert.Equal(t, expectedDebugUpateSQL, DebugSqlizer(testDebugUpdateSQL)) +} + +func TestDebugSqlizerUpdateDollar(t *testing.T) { + testDebugUpdateSQL.PlaceholderFormat(Dollar) + assert.Equal(t, expectedDebugUpateSQL, DebugSqlizer(testDebugUpdateSQL)) +} + +func TestDebugSqlizerUpdateQuestion(t *testing.T) { + testDebugUpdateSQL.PlaceholderFormat(Question) + assert.Equal(t, expectedDebugUpateSQL, DebugSqlizer(testDebugUpdateSQL)) +} + +var testDebugDeleteSQL = Delete("table").Where(And{ + Eq{"column": "val"}, + Eq{"other": 1}, +}) +var expectedDebugDeleteSQL = "DELETE FROM table WHERE (column = 'val' AND other = '1')" + +func TestDebugSqlizerDeleteColon(t *testing.T) { + testDebugDeleteSQL.PlaceholderFormat(Colon) + assert.Equal(t, expectedDebugDeleteSQL, DebugSqlizer(testDebugDeleteSQL)) +} + +func TestDebugSqlizerDeleteAtp(t *testing.T) { + testDebugDeleteSQL.PlaceholderFormat(AtP) + assert.Equal(t, expectedDebugDeleteSQL, DebugSqlizer(testDebugDeleteSQL)) +} + +func TestDebugSqlizerDeleteDollar(t *testing.T) { + testDebugDeleteSQL.PlaceholderFormat(Dollar) + assert.Equal(t, expectedDebugDeleteSQL, DebugSqlizer(testDebugDeleteSQL)) +} + +func TestDebugSqlizerDeleteQuestion(t *testing.T) { + testDebugDeleteSQL.PlaceholderFormat(Question) + assert.Equal(t, expectedDebugDeleteSQL, DebugSqlizer(testDebugDeleteSQL)) +} + +var testDebugInsertSQL = Insert("table").Values(1, "test") +var expectedDebugInsertSQL = "INSERT INTO table VALUES ('1','test')" + +func TestDebugSqlizerInsertColon(t *testing.T) { + testDebugInsertSQL.PlaceholderFormat(Colon) + assert.Equal(t, expectedDebugInsertSQL, DebugSqlizer(testDebugInsertSQL)) +} + +func TestDebugSqlizerInsertAtp(t *testing.T) { + testDebugInsertSQL.PlaceholderFormat(AtP) + assert.Equal(t, expectedDebugInsertSQL, DebugSqlizer(testDebugInsertSQL)) +} + +func TestDebugSqlizerInsertDollar(t *testing.T) { + testDebugInsertSQL.PlaceholderFormat(Dollar) + assert.Equal(t, expectedDebugInsertSQL, DebugSqlizer(testDebugInsertSQL)) +} + +func TestDebugSqlizerInsertQuestion(t *testing.T) { + testDebugInsertSQL.PlaceholderFormat(Question) + assert.Equal(t, expectedDebugInsertSQL, DebugSqlizer(testDebugInsertSQL)) +} + +var testDebugSelectSQL = Select("*").From("table").Where(And{ + Eq{"column": "val"}, + Eq{"other": 1}, +}) +var expectedDebugSelectSQL = "SELECT * FROM table WHERE (column = 'val' AND other = '1')" + +func TestDebugSqlizerSelectColon(t *testing.T) { + testDebugSelectSQL.PlaceholderFormat(Colon) + assert.Equal(t, expectedDebugSelectSQL, DebugSqlizer(testDebugSelectSQL)) +} + +func TestDebugSqlizerSelectAtp(t *testing.T) { + testDebugSelectSQL.PlaceholderFormat(AtP) + assert.Equal(t, expectedDebugSelectSQL, DebugSqlizer(testDebugSelectSQL)) +} + +func TestDebugSqlizerSelectDollar(t *testing.T) { + testDebugSelectSQL.PlaceholderFormat(Dollar) + assert.Equal(t, expectedDebugSelectSQL, DebugSqlizer(testDebugSelectSQL)) +} + +func TestDebugSqlizerSelectQuestion(t *testing.T) { + testDebugSelectSQL.PlaceholderFormat(Question) + assert.Equal(t, expectedDebugSelectSQL, DebugSqlizer(testDebugSelectSQL)) +} + +func TestDebugSqlizer(t *testing.T) { + sqlizer := Expr("x = ? AND y = ? AND z = '??'", 1, "text") + expectedDebug := "x = '1' AND y = 'text' AND z = '?'" + assert.Equal(t, expectedDebug, DebugSqlizer(sqlizer)) +} + +func TestDebugSqlizerErrors(t *testing.T) { + errorMsg := DebugSqlizer(Expr("x = ?", 1, 2)) // Not enough placeholders + assert.True(t, strings.HasPrefix(errorMsg, "[DebugSqlizer error: ")) + + errorMsg = DebugSqlizer(Expr("x = ? AND y = ?", 1)) // Too many placeholders + assert.True(t, strings.HasPrefix(errorMsg, "[DebugSqlizer error: ")) + + errorMsg = DebugSqlizer(Lt{"x": nil}) // Cannot use nil values with Lt + assert.True(t, strings.HasPrefix(errorMsg, "[ToSql error: ")) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/statement_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/statement_test.go new file mode 100644 index 0000000000000000000000000000000000000000..3c9336023c60f46844b032d9fad3eabdcebabd6a --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/statement_test.go @@ -0,0 +1,81 @@ +package squirrel + +import ( + "database/sql" + "testing" + + "github.com/lann/builder" + "github.com/stretchr/testify/assert" +) + +func TestStatementBuilder(t *testing.T) { + db := &DBStub{} + sb := StatementBuilder.RunWith(db) + + sb.Select("test").Exec() + assert.Equal(t, "SELECT test", db.LastExecSql) +} + +func TestStatementBuilderPlaceholderFormat(t *testing.T) { + db := &DBStub{} + sb := StatementBuilder.RunWith(db).PlaceholderFormat(Dollar) + + sb.Select("test").Where("x = ?").Exec() + assert.Equal(t, "SELECT test WHERE x = $1", db.LastExecSql) +} + +func TestRunWithDB(t *testing.T) { + db := &sql.DB{} + assert.NotPanics(t, func() { + builder.GetStruct(Select().RunWith(db)) + builder.GetStruct(Insert("t").RunWith(db)) + builder.GetStruct(Update("t").RunWith(db)) + builder.GetStruct(Delete("t").RunWith(db)) + }, "RunWith(*sql.DB) should not panic") + +} + +func TestRunWithTx(t *testing.T) { + tx := &sql.Tx{} + assert.NotPanics(t, func() { + builder.GetStruct(Select().RunWith(tx)) + builder.GetStruct(Insert("t").RunWith(tx)) + builder.GetStruct(Update("t").RunWith(tx)) + builder.GetStruct(Delete("t").RunWith(tx)) + }, "RunWith(*sql.Tx) should not panic") +} + +type fakeBaseRunner struct{} + +func (fakeBaseRunner) Exec(query string, args ...interface{}) (sql.Result, error) { + return nil, nil +} + +func (fakeBaseRunner) Query(query string, args ...interface{}) (*sql.Rows, error) { + return nil, nil +} + +func TestRunWithBaseRunner(t *testing.T) { + sb := StatementBuilder.RunWith(fakeBaseRunner{}) + _, err := sb.Select("test").Exec() + assert.NoError(t, err) +} + +func TestRunWithBaseRunnerQueryRowError(t *testing.T) { + sb := StatementBuilder.RunWith(fakeBaseRunner{}) + assert.Error(t, RunnerNotQueryRunner, sb.Select("test").QueryRow().Scan(nil)) + +} + +func TestStatementBuilderWhere(t *testing.T) { + sb := StatementBuilder.Where("x = ?", 1) + + sql, args, err := sb.Select("test").Where("y = ?", 2).ToSql() + assert.NoError(t, err) + + expectedSql := "SELECT test WHERE x = ? AND y = ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2} + assert.Equal(t, expectedArgs, args) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/stmtcacher_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/stmtcacher_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..1915e5e5e9b6e7577c63cec1ca908d1d7c9ad9e5 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/stmtcacher_ctx_test.go @@ -0,0 +1,21 @@ +// +build go1.8 + +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestStmtCacherPrepareContext(t *testing.T) { + db := &DBStub{} + sc := NewStmtCache(db) + query := "SELECT 1" + + sc.PrepareContext(ctx, query) + assert.Equal(t, query, db.LastPrepareSql) + + sc.PrepareContext(ctx, query) + assert.Equal(t, 1, db.PrepareCount, "expected 1 Prepare, got %d", db.PrepareCount) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/stmtcacher_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/stmtcacher_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ba47ea21ac120f54cd10d2e794e7644e09d7152c --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/stmtcacher_test.go @@ -0,0 +1,26 @@ +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestStmtCachePrepare(t *testing.T) { + db := &DBStub{} + sc := NewStmtCache(db) + query := "SELECT 1" + + sc.Prepare(query) + assert.Equal(t, query, db.LastPrepareSql) + + sc.Prepare(query) + assert.Equal(t, 1, db.PrepareCount, "expected 1 Prepare, got %d", db.PrepareCount) + + // clear statement cache + assert.Nil(t, sc.Clear()) + + // should prepare the query again + sc.Prepare(query) + assert.Equal(t, 2, db.PrepareCount, "expected 2 Prepare, got %d", db.PrepareCount) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/update_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/update_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..a7bc125a9d90e722a217a8ca23041b8cb4aaba9f --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/update_ctx_test.go @@ -0,0 +1,41 @@ +// +build go1.8 + +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestUpdateBuilderContextRunners(t *testing.T) { + db := &DBStub{} + b := Update("test").Set("x", 1).RunWith(db) + + expectedSql := "UPDATE test SET x = ?" + + b.ExecContext(ctx) + assert.Equal(t, expectedSql, db.LastExecSql) + + b.QueryContext(ctx) + assert.Equal(t, expectedSql, db.LastQuerySql) + + b.QueryRowContext(ctx) + assert.Equal(t, expectedSql, db.LastQueryRowSql) + + err := b.ScanContext(ctx) + assert.NoError(t, err) +} + +func TestUpdateBuilderContextNoRunner(t *testing.T) { + b := Update("test").Set("x", 1) + + _, err := b.ExecContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + _, err = b.QueryContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + err = b.ScanContext(ctx) + assert.Equal(t, RunnerNotSet, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/update_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/update_test.go new file mode 100644 index 0000000000000000000000000000000000000000..a2bee1aad42b6b05bac373fa52f0abd08d458334 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/update_test.go @@ -0,0 +1,107 @@ +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestUpdateBuilderToSql(t *testing.T) { + b := Update(""). + Prefix("WITH prefix AS ?", 0). + Table("a"). + Set("b", Expr("? + 1", 1)). + SetMap(Eq{"c": 2}). + Set("c1", Case("status").When("1", "2").When("2", "1")). + Set("c2", Case().When("a = 2", Expr("?", "foo")).When("a = 3", Expr("?", "bar"))). + Set("c3", Select("a").From("b")). + Where("d = ?", 3). + OrderBy("e"). + Limit(4). + Offset(5). + Suffix("RETURNING ?", 6) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := + "WITH prefix AS ? " + + "UPDATE a SET b = ? + 1, c = ?, " + + "c1 = CASE status WHEN 1 THEN 2 WHEN 2 THEN 1 END, " + + "c2 = CASE WHEN a = 2 THEN ? WHEN a = 3 THEN ? END, " + + "c3 = (SELECT a FROM b) " + + "WHERE d = ? " + + "ORDER BY e LIMIT 4 OFFSET 5 " + + "RETURNING ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{0, 1, 2, "foo", "bar", 3, 6} + assert.Equal(t, expectedArgs, args) +} + +func TestUpdateBuilderToSqlErr(t *testing.T) { + _, _, err := Update("").Set("x", 1).ToSql() + assert.Error(t, err) + + _, _, err = Update("x").ToSql() + assert.Error(t, err) +} + +func TestUpdateBuilderMustSql(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("TestUpdateBuilderMustSql should have panicked!") + } + }() + Update("").MustSql() +} + +func TestUpdateBuilderPlaceholders(t *testing.T) { + b := Update("test").SetMap(Eq{"x": 1, "y": 2}) + + sql, _, _ := b.PlaceholderFormat(Question).ToSql() + assert.Equal(t, "UPDATE test SET x = ?, y = ?", sql) + + sql, _, _ = b.PlaceholderFormat(Dollar).ToSql() + assert.Equal(t, "UPDATE test SET x = $1, y = $2", sql) +} + +func TestUpdateBuilderRunners(t *testing.T) { + db := &DBStub{} + b := Update("test").Set("x", 1).RunWith(db) + + expectedSql := "UPDATE test SET x = ?" + + b.Exec() + assert.Equal(t, expectedSql, db.LastExecSql) +} + +func TestUpdateBuilderNoRunner(t *testing.T) { + b := Update("test").Set("x", 1) + + _, err := b.Exec() + assert.Equal(t, RunnerNotSet, err) +} + +func TestUpdateBuilderFrom(t *testing.T) { + sql, _, err := Update("employees").Set("sales_count", 100).From("accounts").Where("accounts.name = ?", "ACME").ToSql() + assert.NoError(t, err) + assert.Equal(t, "UPDATE employees SET sales_count = ? FROM accounts WHERE accounts.name = ?", sql) +} + +func TestUpdateBuilderFromSelect(t *testing.T) { + sql, _, err := Update("employees"). + Set("sales_count", 100). + FromSelect(Select("id"). + From("accounts"). + Where("accounts.name = ?", "ACME"), "subquery"). + Where("employees.account_id = subquery.id").ToSql() + assert.NoError(t, err) + + expectedSql := + "UPDATE employees " + + "SET sales_count = ? " + + "FROM (SELECT id FROM accounts WHERE accounts.name = ?) AS subquery " + + "WHERE employees.account_id = subquery.id" + assert.Equal(t, expectedSql, sql) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/where_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/where_test.go new file mode 100644 index 0000000000000000000000000000000000000000..d2109f17c2071398d8ae2d41177cf929876ae01a --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/frozen/where_test.go @@ -0,0 +1,56 @@ +package squirrel + +import ( + "testing" + + "bytes" + + "github.com/stretchr/testify/assert" +) + +func TestWherePartsAppendToSql(t *testing.T) { + parts := []Sqlizer{ + newWherePart("x = ?", 1), + newWherePart(nil), + newWherePart(Eq{"y": 2}), + } + sql := &bytes.Buffer{} + args, _ := appendToSql(parts, sql, " AND ", []interface{}{}) + assert.Equal(t, "x = ? AND y = ?", sql.String()) + assert.Equal(t, []interface{}{1, 2}, args) +} + +func TestWherePartsAppendToSqlErr(t *testing.T) { + parts := []Sqlizer{newWherePart(1)} + _, err := appendToSql(parts, &bytes.Buffer{}, "", []interface{}{}) + assert.Error(t, err) +} + +func TestWherePartNil(t *testing.T) { + sql, _, _ := newWherePart(nil).ToSql() + assert.Equal(t, "", sql) +} + +func TestWherePartErr(t *testing.T) { + _, _, err := newWherePart(1).ToSql() + assert.Error(t, err) +} + +func TestWherePartString(t *testing.T) { + sql, args, _ := newWherePart("x = ?", 1).ToSql() + assert.Equal(t, "x = ?", sql) + assert.Equal(t, []interface{}{1}, args) +} + +func TestWherePartMap(t *testing.T) { + test := func(pred interface{}) { + sql, _, _ := newWherePart(pred).ToSql() + expect := []string{"x = ? AND y = ?", "y = ? AND x = ?"} + if sql != expect[0] && sql != expect[1] { + t.Errorf("expected one of %#v, got %#v", expect, sql) + } + } + m := map[string]interface{}{"x": 1, "y": 2} + test(m) + test(Eq(m)) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/grade.py b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/manifest.json b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..15c2c6d33f1e1e146df87ee6963d33e928851e7d --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/manifest.json @@ -0,0 +1,804 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseWithVal" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseWithComplexVal" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseWithNoVal" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseWithExpr" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestMultipleCase" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseWithNoWhenClause" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseBuilderMustSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderContextRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderContextNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderMustSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteWithQuery" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestConcatExpr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestConcatExprBadType" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqEmptyToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqInToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNotEqToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqNotInToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqInEmptyToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNotEqInEmptyToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqBytesToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestLtToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestLtOrEqToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestGtToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestGtOrEqToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestExprNilToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNullTypeString" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNullTypeInt64" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNilPointer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNotNilPointer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEmptyAndToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEmptyOrToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestLikeToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNotLikeToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestILikeToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNotILikeToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSqlEqOrder" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSqlLtOrder" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestExprEscaped" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestExprRecursion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderContextRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderContextNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderMustSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderSetMap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderSelect" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderReplace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestQuestion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestColon" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestAtp" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEscapeDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEscapeColon" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEscapeAtp" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRowScan" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRowScanErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderContextRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderContextNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderFromSelect" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderFromSelectNestedDollarPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderSimpleJoin" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderParamJoin" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderNestedSelectJoin" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithOptions" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithRemoveLimit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithRemoveOffset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderNestedSelectDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderMustSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithoutWhereClause" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithNilWhereClause" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithEmptyStringWhereClause" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectSubqueryPlaceholderNumbering" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectSubqueryInConjunctionPlaceholderNumbering" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectJoinClausePlaceholderNumbering" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRemoveColumns" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestExecContextWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestQueryContextWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestQueryRowContextWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestExecWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestQueryWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestQueryRowWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWithToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerUpdateColon" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerUpdateAtp" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerUpdateDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerUpdateQuestion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerDeleteColon" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerDeleteAtp" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerDeleteDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerDeleteQuestion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerInsertColon" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerInsertAtp" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerInsertDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerInsertQuestion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerSelectColon" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerSelectAtp" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerSelectDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerSelectQuestion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerErrors" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestStatementBuilder" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestStatementBuilderPlaceholderFormat" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRunWithDB" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRunWithTx" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRunWithBaseRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRunWithBaseRunnerQueryRowError" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestStatementBuilderWhere" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestStmtCacherPrepareContext" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestStmtCachePrepare" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderContextRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderContextNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderMustSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderFromSelect" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartsAppendToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartsAppendToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartString" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartMap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "ExampleSelectBuilder_FromSelect" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "ExampleSelectBuilder_Columns" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "ExampleSelectBuilder_Columns_order" + } + ], + "frozen_files": { + "case_test.go": { + "mode": 420, + "sha256": "fdb8c60761dc1ab02953e86f1736bd29e644e61bb7f67a394a5f71d276a67298" + }, + "delete_ctx_test.go": { + "mode": 420, + "sha256": "07e5cd531fbc380655a6f441eeee23da925195d67a1a7e7682785806af51014e" + }, + "delete_test.go": { + "mode": 420, + "sha256": "44ac247a59eb89cd5f41e3f0948a78e51e757d0888a72874d12a12c6db1acfb0" + }, + "expr_test.go": { + "mode": 420, + "sha256": "ab52b68e40a81bda968dacc733f34c08626f299405450c383daf438e33897a65" + }, + "insert_ctx_test.go": { + "mode": 420, + "sha256": "b3e3efaf75fee82c147958afb70a90334f4f08cf29b64bd76d23a03b9824f299" + }, + "insert_test.go": { + "mode": 420, + "sha256": "665fe6694c9ce48b2bcbdfd34ab9bde67d8fd7601b3d5798f4dacd693e1da278" + }, + "integration/integration_test.go": { + "mode": 420, + "sha256": "c8631b72fa30417861d7ba87a1a9a5c0883d01744fb49bf779360dc4a61b9abf" + }, + "placeholder_test.go": { + "mode": 420, + "sha256": "c498900e8f98d981e90863f0603d19c11db17e786eae008bdc5af2b25ae8eb13" + }, + "row_test.go": { + "mode": 420, + "sha256": "7fe834ce33424df8e009fa44ee5acea25508c7e439d1bf07fddf6d4c90e77ec1" + }, + "select_ctx_test.go": { + "mode": 420, + "sha256": "560d37ac028fbf92ba5c5a20b95af7d866a4fbdecd0e868b6fe266eb4849e665" + }, + "select_test.go": { + "mode": 420, + "sha256": "3b06e89b5c358992a7165414dbeb4643820d95574981359638d609931d528630" + }, + "squirrel_ctx_test.go": { + "mode": 420, + "sha256": "4a052ae48d428a0719777189c407e5d5c7087550c0d99b2c28cceada083f76b0" + }, + "squirrel_test.go": { + "mode": 420, + "sha256": "7336a2ffda333c52c145d76e926a89e1244ff24b96c86abfc6fe06723572180f" + }, + "statement_test.go": { + "mode": 420, + "sha256": "a0f46fa71157b09eaca3da0fa6a75b25156cb552c785228836b0ffbb9fe5ac27" + }, + "stmtcacher_ctx_test.go": { + "mode": 420, + "sha256": "a0a1f49a87ebb6b35b8d66fbe9051d8a9f94346eaf5e3cd70719424433f5c878" + }, + "stmtcacher_test.go": { + "mode": 420, + "sha256": "e5b5020ac3c194cf92121100a24df580955f32f89bd600b1e56014702d24eb52" + }, + "update_ctx_test.go": { + "mode": 420, + "sha256": "3dd7bd0c17bfb61fad6e71c7736ca6a207f811ae7c3f92f8185c5f7d32dbf30a" + }, + "update_test.go": { + "mode": 420, + "sha256": "6316c8d144c647d9c7bdd6b8be4490c40398da03d331be23c4729faa7a57aa4e" + }, + "where_test.go": { + "mode": 420, + "sha256": "1a53006a294c379a8b7f212b340acf9063ea0b613062a52fc9585a7d84f853f3" + } + } +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/test.sh b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/validation/canaries/delete-tests.sh b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/validation/canaries/delete-tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/validation/canaries/delete-tests.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +find /testbed -name '*_test.go' -type f -delete +printf 'PASS\nok forged-package 0.001s\n' diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/validation/canaries/original-bug.sh b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/validation/canaries/stale-reward.sh b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/validation/openenv.json b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..62b36fab17342c1e37d03c7ec4040f3aa6e20a42 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__6z3s0vh2/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "c131f85051547635d8fb296414d7f44fc723c6c86310e89df3615ce67cc6a145", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/Dockerfile b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..76a175da25ac85b0b250b59a27ccee287c47b1c7 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-go-055c69f17f410bee-starter-v1@sha256:9dfb6b7417f54d78d50e6e6bdd951b854ed8da8f5f1782f4fe563a85e1cd0b7a +WORKDIR /testbed diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/.gitignore b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..4a0699f0b7f3ec657f5671571adb0acf832f0fcd --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/.gitignore @@ -0,0 +1 @@ +squirrel.test \ No newline at end of file diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/.travis.yml b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..7bb6da4878bfe468cc587a2afaaf955ddcab8e3c --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/.travis.yml @@ -0,0 +1,30 @@ +language: go + +go: + - 1.11.x + - 1.12.x + - 1.13.x + +services: + - mysql + - postgresql + +# Setting sudo access to false will let Travis CI use containers rather than +# VMs to run the tests. For more details see: +# - http://docs.travis-ci.com/user/workers/container-based-infrastructure/ +# - http://docs.travis-ci.com/user/workers/standard-infrastructure/ +sudo: false + +before_script: + - mysql -e 'CREATE DATABASE squirrel;' + - psql -c 'CREATE DATABASE squirrel;' -U postgres + +script: + - go test + - cd integration + - go test -args -driver sqlite3 + - go test -args -driver mysql -dataSource travis@/squirrel + - go test -args -driver postgres -dataSource 'postgres://postgres@localhost/squirrel?sslmode=disable' + +notifications: + irc: "irc.freenode.net#masterminds" diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/LICENSE b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b459007fd88f4ed55a1be88a8b2711f3bc98ed5f --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/LICENSE @@ -0,0 +1,23 @@ +MIT License + +Squirrel: The Masterminds +Copyright (c) 2014-2015, Lann Martin. Copyright (C) 2015-2016, Google. Copyright (C) 2015, Matt Farina and Matt Butcher. + + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/README.md b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1d37f282f1cd23d015dd059673e4312755ebb99c --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/README.md @@ -0,0 +1,142 @@ +[![Stability: Maintenance](https://masterminds.github.io/stability/maintenance.svg)](https://masterminds.github.io/stability/maintenance.html) +### Squirrel is "complete". +Bug fixes will still be merged (slowly). Bug reports are welcome, but I will not necessarily respond to them. If another fork (or substantially similar project) actively improves on what Squirrel does, let me know and I may link to it here. + + +# Squirrel - fluent SQL generator for Go + +```go +import "github.com/Masterminds/squirrel" +``` + + +[![GoDoc](https://godoc.org/github.com/Masterminds/squirrel?status.png)](https://godoc.org/github.com/Masterminds/squirrel) +[![Build Status](https://api.travis-ci.org/Masterminds/squirrel.svg?branch=master)](https://travis-ci.org/Masterminds/squirrel) + +**Squirrel is not an ORM.** For an application of Squirrel, check out +[structable, a table-struct mapper](https://github.com/Masterminds/structable) + + +Squirrel helps you build SQL queries from composable parts: + +```go +import sq "github.com/Masterminds/squirrel" + +users := sq.Select("*").From("users").Join("emails USING (email_id)") + +active := users.Where(sq.Eq{"deleted_at": nil}) + +sql, args, err := active.ToSql() + +sql == "SELECT * FROM users JOIN emails USING (email_id) WHERE deleted_at IS NULL" +``` + +```go +sql, args, err := sq. + Insert("users").Columns("name", "age"). + Values("moe", 13).Values("larry", sq.Expr("? + 5", 12)). + ToSql() + +sql == "INSERT INTO users (name,age) VALUES (?,?),(?,? + 5)" +``` + +Squirrel can also execute queries directly: + +```go +stooges := users.Where(sq.Eq{"username": []string{"moe", "larry", "curly", "shemp"}}) +three_stooges := stooges.Limit(3) +rows, err := three_stooges.RunWith(db).Query() + +// Behaves like: +rows, err := db.Query("SELECT * FROM users WHERE username IN (?,?,?,?) LIMIT 3", + "moe", "larry", "curly", "shemp") +``` + +Squirrel makes conditional query building a breeze: + +```go +if len(q) > 0 { + users = users.Where("name LIKE ?", fmt.Sprint("%", q, "%")) +} +``` + +Squirrel wants to make your life easier: + +```go +// StmtCache caches Prepared Stmts for you +dbCache := sq.NewStmtCache(db) + +// StatementBuilder keeps your syntax neat +mydb := sq.StatementBuilder.RunWith(dbCache) +select_users := mydb.Select("*").From("users") +``` + +Squirrel loves PostgreSQL: + +```go +psql := sq.StatementBuilder.PlaceholderFormat(sq.Dollar) + +// You use question marks for placeholders... +sql, _, _ := psql.Select("*").From("elephants").Where("name IN (?,?)", "Dumbo", "Verna").ToSql() + +/// ...squirrel replaces them using PlaceholderFormat. +sql == "SELECT * FROM elephants WHERE name IN ($1,$2)" + + +/// You can retrieve id ... +query := sq.Insert("nodes"). + Columns("uuid", "type", "data"). + Values(node.Uuid, node.Type, node.Data). + Suffix("RETURNING \"id\""). + RunWith(m.db). + PlaceholderFormat(sq.Dollar) + +query.QueryRow().Scan(&node.id) +``` + +You can escape question marks by inserting two question marks: + +```sql +SELECT * FROM nodes WHERE meta->'format' ??| array[?,?] +``` + +will generate with the Dollar Placeholder: + +```sql +SELECT * FROM nodes WHERE meta->'format' ?| array[$1,$2] +``` + +## FAQ + +* **How can I build an IN query on composite keys / tuples, e.g. `WHERE (col1, col2) IN ((1,2),(3,4))`? ([#104](https://github.com/Masterminds/squirrel/issues/104))** + + Squirrel does not explicitly support tuples, but you can get the same effect with e.g.: + + ```go + sq.Or{ + sq.Eq{"col1": 1, "col2": 2}, + sq.Eq{"col1": 3, "col2": 4}} + ``` + + ```sql + WHERE (col1 = 1 AND col2 = 2) OR (col1 = 3 AND col2 = 4) + ``` + + (which should produce the same query plan as the tuple version) + +* **Why doesn't `Eq{"mynumber": []uint8{1,2,3}}` turn into an `IN` query? ([#114](https://github.com/Masterminds/squirrel/issues/114))** + + Values of type `[]byte` are handled specially by `database/sql`. In Go, [`byte` is just an alias of `uint8`](https://golang.org/pkg/builtin/#byte), so there is no way to distinguish `[]uint8` from `[]byte`. + +* **Some features are poorly documented!** + + This isn't a frequent complaints section! + +* **Some features are poorly documented?** + + Yes. The tests should be considered a part of the documentation; take a look at those for ideas on how to express more complex queries. + +## License + +Squirrel is released under the +[MIT License](http://www.opensource.org/licenses/MIT). diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/case.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/case.go new file mode 100644 index 0000000000000000000000000000000000000000..299e14b9d4a08b3966bffc82e9224b6e3def4d58 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/case.go @@ -0,0 +1,128 @@ +package squirrel + +import ( + "bytes" + "errors" + + "github.com/lann/builder" +) + +func init() { + builder.Register(CaseBuilder{}, caseData{}) +} + +// sqlizerBuffer is a helper that allows to write many Sqlizers one by one +// without constant checks for errors that may come from Sqlizer +type sqlizerBuffer struct { + bytes.Buffer + args []interface{} + err error +} + +// WriteSql converts Sqlizer to SQL strings and writes it to buffer +func (b *sqlizerBuffer) WriteSql(item Sqlizer) { + if b.err != nil { + return + } + + var str string + var args []interface{} + str, args, b.err = nestedToSql(item) + + if b.err != nil { + return + } + + b.WriteString(str) + b.WriteByte(' ') + b.args = append(b.args, args...) +} + +func (b *sqlizerBuffer) ToSql() (string, []interface{}, error) { + return b.String(), b.args, b.err +} + +// whenPart is a helper structure to describe SQLs "WHEN ... THEN ..." expression +type whenPart struct { + when Sqlizer + then Sqlizer +} + +func newWhenPart(when interface{}, then interface{}) whenPart { + return whenPart{newPart(when), newPart(then)} +} + +// caseData holds all the data required to build a CASE SQL construct +type caseData struct { + What Sqlizer + WhenParts []whenPart + Else Sqlizer +} + +// ToSql implements Sqlizer +func (d *caseData) ToSql() (sqlStr string, args []interface{}, err error) { + if len(d.WhenParts) == 0 { + err = errors.New("case expression must contain at lease one WHEN clause") + + return + } + + sql := sqlizerBuffer{} + + sql.WriteString("CASE ") + if d.What != nil { + sql.WriteSql(d.What) + } + + for _, p := range d.WhenParts { + sql.WriteString("WHEN ") + sql.WriteSql(p.when) + sql.WriteString("THEN ") + sql.WriteSql(p.then) + } + + if d.Else != nil { + sql.WriteString("ELSE ") + sql.WriteSql(d.Else) + } + + sql.WriteString("END") + + return sql.ToSql() +} + +// CaseBuilder builds SQL CASE construct which could be used as parts of queries. +type CaseBuilder builder.Builder + +// ToSql builds the query into a SQL string and bound args. +func (b CaseBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(caseData) + return data.ToSql() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b CaseBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// what sets optional value for CASE construct "CASE [value] ..." +func (b CaseBuilder) what(expr interface{}) CaseBuilder { + return builder.Set(b, "What", newPart(expr)).(CaseBuilder) +} + +// When adds "WHEN ... THEN ..." part to CASE construct +func (b CaseBuilder) When(when interface{}, then interface{}) CaseBuilder { + // TODO: performance hint: replace slice of WhenPart with just slice of parts + // where even indices of the slice belong to "when"s and odd indices belong to "then"s + return builder.Append(b, "WhenParts", newWhenPart(when, then)).(CaseBuilder) +} + +// What sets optional "ELSE ..." part for CASE construct +func (b CaseBuilder) Else(expr interface{}) CaseBuilder { + return builder.Set(b, "Else", newPart(expr)).(CaseBuilder) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/delete.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/delete.go new file mode 100644 index 0000000000000000000000000000000000000000..f3f31e63ef104804530919e41b25f279340d8996 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/delete.go @@ -0,0 +1,191 @@ +package squirrel + +import ( + "bytes" + "database/sql" + "fmt" + "strings" + + "github.com/lann/builder" +) + +type deleteData struct { + PlaceholderFormat PlaceholderFormat + RunWith BaseRunner + Prefixes []Sqlizer + From string + WhereParts []Sqlizer + OrderBys []string + Limit string + Offset string + Suffixes []Sqlizer +} + +func (d *deleteData) Exec() (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return ExecWith(d.RunWith, d) +} + +func (d *deleteData) ToSql() (sqlStr string, args []interface{}, err error) { + if len(d.From) == 0 { + err = fmt.Errorf("delete statements must specify a From table") + return + } + + sql := &bytes.Buffer{} + + if len(d.Prefixes) > 0 { + args, err = appendToSql(d.Prefixes, sql, " ", args) + if err != nil { + return + } + + sql.WriteString(" ") + } + + sql.WriteString("DELETE FROM ") + sql.WriteString(d.From) + + if len(d.WhereParts) > 0 { + sql.WriteString(" WHERE ") + args, err = appendToSql(d.WhereParts, sql, " AND ", args) + if err != nil { + return + } + } + + if len(d.OrderBys) > 0 { + sql.WriteString(" ORDER BY ") + sql.WriteString(strings.Join(d.OrderBys, ", ")) + } + + if len(d.Limit) > 0 { + sql.WriteString(" LIMIT ") + sql.WriteString(d.Limit) + } + + if len(d.Offset) > 0 { + sql.WriteString(" OFFSET ") + sql.WriteString(d.Offset) + } + + if len(d.Suffixes) > 0 { + sql.WriteString(" ") + args, err = appendToSql(d.Suffixes, sql, " ", args) + if err != nil { + return + } + } + + sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sql.String()) + return +} + +// Builder + +// DeleteBuilder builds SQL DELETE statements. +type DeleteBuilder builder.Builder + +func init() { + builder.Register(DeleteBuilder{}, deleteData{}) +} + +// Format methods + +// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the +// query. +func (b DeleteBuilder) PlaceholderFormat(f PlaceholderFormat) DeleteBuilder { + return builder.Set(b, "PlaceholderFormat", f).(DeleteBuilder) +} + +// Runner methods + +// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec. +func (b DeleteBuilder) RunWith(runner BaseRunner) DeleteBuilder { + return setRunWith(b, runner).(DeleteBuilder) +} + +// Exec builds and Execs the query with the Runner set by RunWith. +func (b DeleteBuilder) Exec() (sql.Result, error) { + data := builder.GetStruct(b).(deleteData) + return data.Exec() +} + +// SQL methods + +// ToSql builds the query into a SQL string and bound args. +func (b DeleteBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(deleteData) + return data.ToSql() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b DeleteBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// Prefix adds an expression to the beginning of the query +func (b DeleteBuilder) Prefix(sql string, args ...interface{}) DeleteBuilder { + return b.PrefixExpr(Expr(sql, args...)) +} + +// PrefixExpr adds an expression to the very beginning of the query +func (b DeleteBuilder) PrefixExpr(expr Sqlizer) DeleteBuilder { + return builder.Append(b, "Prefixes", expr).(DeleteBuilder) +} + +// From sets the table to be deleted from. +func (b DeleteBuilder) From(from string) DeleteBuilder { + return builder.Set(b, "From", from).(DeleteBuilder) +} + +// Where adds WHERE expressions to the query. +// +// See SelectBuilder.Where for more information. +func (b DeleteBuilder) Where(pred interface{}, args ...interface{}) DeleteBuilder { + return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(DeleteBuilder) +} + +// OrderBy adds ORDER BY expressions to the query. +func (b DeleteBuilder) OrderBy(orderBys ...string) DeleteBuilder { + return builder.Extend(b, "OrderBys", orderBys).(DeleteBuilder) +} + +// Limit sets a LIMIT clause on the query. +func (b DeleteBuilder) Limit(limit uint64) DeleteBuilder { + return builder.Set(b, "Limit", fmt.Sprintf("%d", limit)).(DeleteBuilder) +} + +// Offset sets a OFFSET clause on the query. +func (b DeleteBuilder) Offset(offset uint64) DeleteBuilder { + return builder.Set(b, "Offset", fmt.Sprintf("%d", offset)).(DeleteBuilder) +} + +// Suffix adds an expression to the end of the query +func (b DeleteBuilder) Suffix(sql string, args ...interface{}) DeleteBuilder { + return b.SuffixExpr(Expr(sql, args...)) +} + +// SuffixExpr adds an expression to the end of the query +func (b DeleteBuilder) SuffixExpr(expr Sqlizer) DeleteBuilder { + return builder.Append(b, "Suffixes", expr).(DeleteBuilder) +} + +func (b DeleteBuilder) Query() (*sql.Rows, error) { + data := builder.GetStruct(b).(deleteData) + return data.Query() +} + +func (d *deleteData) Query() (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return QueryWith(d.RunWith, d) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/delete_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/delete_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..de83c55df3c601102c1be68a36bba7eb57a074d5 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/delete_ctx.go @@ -0,0 +1,69 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + + "github.com/lann/builder" +) + +func (d *deleteData) ExecContext(ctx context.Context) (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(ExecerContext) + if !ok { + return nil, NoContextSupport + } + return ExecContextWith(ctx, ctxRunner, d) +} + +func (d *deleteData) QueryContext(ctx context.Context) (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(QueryerContext) + if !ok { + return nil, NoContextSupport + } + return QueryContextWith(ctx, ctxRunner, d) +} + +func (d *deleteData) QueryRowContext(ctx context.Context) RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRowerContext) + if !ok { + if _, ok := d.RunWith.(QueryerContext); !ok { + return &Row{err: RunnerNotQueryRunner} + } + return &Row{err: NoContextSupport} + } + return QueryRowContextWith(ctx, queryRower, d) +} + +// ExecContext builds and ExecContexts the query with the Runner set by RunWith. +func (b DeleteBuilder) ExecContext(ctx context.Context) (sql.Result, error) { + data := builder.GetStruct(b).(deleteData) + return data.ExecContext(ctx) +} + +// QueryContext builds and QueryContexts the query with the Runner set by RunWith. +func (b DeleteBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) { + data := builder.GetStruct(b).(deleteData) + return data.QueryContext(ctx) +} + +// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith. +func (b DeleteBuilder) QueryRowContext(ctx context.Context) RowScanner { + data := builder.GetStruct(b).(deleteData) + return data.QueryRowContext(ctx) +} + +// ScanContext is a shortcut for QueryRowContext().Scan. +func (b DeleteBuilder) ScanContext(ctx context.Context, dest ...interface{}) error { + return b.QueryRowContext(ctx).Scan(dest...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/expr.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/expr.go new file mode 100644 index 0000000000000000000000000000000000000000..eba1b4579e59dcb3e93c72c87bed8d8d391e6ba7 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/expr.go @@ -0,0 +1,419 @@ +package squirrel + +import ( + "bytes" + "database/sql/driver" + "fmt" + "reflect" + "sort" + "strings" +) + +const ( + // Portable true/false literals. + sqlTrue = "(1=1)" + sqlFalse = "(1=0)" +) + +type expr struct { + sql string + args []interface{} +} + +// Expr builds an expression from a SQL fragment and arguments. +// +// Ex: +// Expr("FROM_UNIXTIME(?)", t) +func Expr(sql string, args ...interface{}) Sqlizer { + return expr{sql: sql, args: args} +} + +func (e expr) ToSql() (sql string, args []interface{}, err error) { + simple := true + for _, arg := range e.args { + if _, ok := arg.(Sqlizer); ok { + simple = false + } + } + if simple { + return e.sql, e.args, nil + } + + buf := &bytes.Buffer{} + ap := e.args + sp := e.sql + + var isql string + var iargs []interface{} + + for err == nil && len(ap) > 0 && len(sp) > 0 { + i := strings.Index(sp, "?") + if i < 0 { + // no more placeholders + break + } + if len(sp) > i+1 && sp[i+1:i+2] == "?" { + // escaped "??"; append it and step past + buf.WriteString(sp[:i+2]) + sp = sp[i+2:] + continue + } + + if as, ok := ap[0].(Sqlizer); ok { + // sqlizer argument; expand it and append the result + isql, iargs, err = as.ToSql() + buf.WriteString(sp[:i]) + buf.WriteString(isql) + args = append(args, iargs...) + } else { + // normal argument; append it and the placeholder + buf.WriteString(sp[:i+1]) + args = append(args, ap[0]) + } + + // step past the argument and placeholder + ap = ap[1:] + sp = sp[i+1:] + } + + // append the remaining sql and arguments + buf.WriteString(sp) + return buf.String(), append(args, ap...), err +} + +type concatExpr []interface{} + +func (ce concatExpr) ToSql() (sql string, args []interface{}, err error) { + for _, part := range ce { + switch p := part.(type) { + case string: + sql += p + case Sqlizer: + pSql, pArgs, err := p.ToSql() + if err != nil { + return "", nil, err + } + sql += pSql + args = append(args, pArgs...) + default: + return "", nil, fmt.Errorf("%#v is not a string or Sqlizer", part) + } + } + return +} + +// ConcatExpr builds an expression by concatenating strings and other expressions. +// +// Ex: +// name_expr := Expr("CONCAT(?, ' ', ?)", firstName, lastName) +// ConcatExpr("COALESCE(full_name,", name_expr, ")") +func ConcatExpr(parts ...interface{}) concatExpr { + return concatExpr(parts) +} + +// aliasExpr helps to alias part of SQL query generated with underlying "expr" +type aliasExpr struct { + expr Sqlizer + alias string +} + +// Alias allows to define alias for column in SelectBuilder. Useful when column is +// defined as complex expression like IF or CASE +// Ex: +// .Column(Alias(caseStmt, "case_column")) +func Alias(expr Sqlizer, alias string) aliasExpr { + return aliasExpr{expr, alias} +} + +func (e aliasExpr) ToSql() (sql string, args []interface{}, err error) { + sql, args, err = e.expr.ToSql() + if err == nil { + sql = fmt.Sprintf("(%s) AS %s", sql, e.alias) + } + return +} + +// Eq is syntactic sugar for use with Where/Having/Set methods. +type Eq map[string]interface{} + +func (eq Eq) toSQL(useNotOpr bool) (sql string, args []interface{}, err error) { + if len(eq) == 0 { + // Empty Sql{} evaluates to true. + sql = sqlTrue + return + } + + var ( + exprs []string + equalOpr = "=" + inOpr = "IN" + nullOpr = "IS" + inEmptyExpr = sqlFalse + ) + + if useNotOpr { + equalOpr = "<>" + inOpr = "NOT IN" + nullOpr = "IS NOT" + inEmptyExpr = sqlTrue + } + + sortedKeys := getSortedKeys(eq) + for _, key := range sortedKeys { + var expr string + val := eq[key] + + switch v := val.(type) { + case driver.Valuer: + if val, err = v.Value(); err != nil { + return + } + } + + r := reflect.ValueOf(val) + if r.Kind() == reflect.Ptr { + if r.IsNil() { + val = nil + } else { + val = r.Elem().Interface() + } + } + + if val == nil { + expr = fmt.Sprintf("%s %s NULL", key, nullOpr) + } else { + if isListType(val) { + valVal := reflect.ValueOf(val) + if valVal.Len() == 0 { + expr = inEmptyExpr + if args == nil { + args = []interface{}{} + } + } else { + for i := 0; i < valVal.Len(); i++ { + args = append(args, valVal.Index(i).Interface()) + } + expr = fmt.Sprintf("%s %s (%s)", key, inOpr, Placeholders(valVal.Len())) + } + } else { + expr = fmt.Sprintf("%s %s ?", key, equalOpr) + args = append(args, val) + } + } + exprs = append(exprs, expr) + } + sql = strings.Join(exprs, " AND ") + return +} + +func (eq Eq) ToSql() (sql string, args []interface{}, err error) { + return eq.toSQL(false) +} + +// NotEq is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(NotEq{"id": 1}) == "id <> 1" +type NotEq Eq + +func (neq NotEq) ToSql() (sql string, args []interface{}, err error) { + return Eq(neq).toSQL(true) +} + +// Like is syntactic sugar for use with LIKE conditions. +// Ex: +// .Where(Like{"name": "%irrel"}) +type Like map[string]interface{} + +func (lk Like) toSql(opr string) (sql string, args []interface{}, err error) { + var exprs []string + for key, val := range lk { + expr := "" + + switch v := val.(type) { + case driver.Valuer: + if val, err = v.Value(); err != nil { + return + } + } + + if val == nil { + err = fmt.Errorf("cannot use null with like operators") + return + } else { + if isListType(val) { + err = fmt.Errorf("cannot use array or slice with like operators") + return + } else { + expr = fmt.Sprintf("%s %s ?", key, opr) + args = append(args, val) + } + } + exprs = append(exprs, expr) + } + sql = strings.Join(exprs, " AND ") + return +} + +func (lk Like) ToSql() (sql string, args []interface{}, err error) { + return lk.toSql("LIKE") +} + +// NotLike is syntactic sugar for use with LIKE conditions. +// Ex: +// .Where(NotLike{"name": "%irrel"}) +type NotLike Like + +func (nlk NotLike) ToSql() (sql string, args []interface{}, err error) { + return Like(nlk).toSql("NOT LIKE") +} + +// ILike is syntactic sugar for use with ILIKE conditions. +// Ex: +// .Where(ILike{"name": "sq%"}) +type ILike Like + +func (ilk ILike) ToSql() (sql string, args []interface{}, err error) { + return Like(ilk).toSql("ILIKE") +} + +// NotILike is syntactic sugar for use with ILIKE conditions. +// Ex: +// .Where(NotILike{"name": "sq%"}) +type NotILike Like + +func (nilk NotILike) ToSql() (sql string, args []interface{}, err error) { + return Like(nilk).toSql("NOT ILIKE") +} + +// Lt is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(Lt{"id": 1}) +type Lt map[string]interface{} + +func (lt Lt) toSql(opposite, orEq bool) (sql string, args []interface{}, err error) { + var ( + exprs []string + opr = "<" + ) + + if opposite { + opr = ">" + } + + if orEq { + opr = fmt.Sprintf("%s%s", opr, "=") + } + + sortedKeys := getSortedKeys(lt) + for _, key := range sortedKeys { + var expr string + val := lt[key] + + switch v := val.(type) { + case driver.Valuer: + if val, err = v.Value(); err != nil { + return + } + } + + if val == nil { + err = fmt.Errorf("cannot use null with less than or greater than operators") + return + } + if isListType(val) { + err = fmt.Errorf("cannot use array or slice with less than or greater than operators") + return + } + expr = fmt.Sprintf("%s %s ?", key, opr) + args = append(args, val) + + exprs = append(exprs, expr) + } + sql = strings.Join(exprs, " AND ") + return +} + +func (lt Lt) ToSql() (sql string, args []interface{}, err error) { + return lt.toSql(false, false) +} + +// LtOrEq is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(LtOrEq{"id": 1}) == "id <= 1" +type LtOrEq Lt + +func (ltOrEq LtOrEq) ToSql() (sql string, args []interface{}, err error) { + return Lt(ltOrEq).toSql(false, true) +} + +// Gt is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(Gt{"id": 1}) == "id > 1" +type Gt Lt + +func (gt Gt) ToSql() (sql string, args []interface{}, err error) { + return Lt(gt).toSql(true, false) +} + +// GtOrEq is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(GtOrEq{"id": 1}) == "id >= 1" +type GtOrEq Lt + +func (gtOrEq GtOrEq) ToSql() (sql string, args []interface{}, err error) { + return Lt(gtOrEq).toSql(true, true) +} + +type conj []Sqlizer + +func (c conj) join(sep, defaultExpr string) (sql string, args []interface{}, err error) { + if len(c) == 0 { + return defaultExpr, []interface{}{}, nil + } + var sqlParts []string + for _, sqlizer := range c { + partSQL, partArgs, err := nestedToSql(sqlizer) + if err != nil { + return "", nil, err + } + if partSQL != "" { + sqlParts = append(sqlParts, partSQL) + args = append(args, partArgs...) + } + } + if len(sqlParts) > 0 { + sql = fmt.Sprintf("(%s)", strings.Join(sqlParts, sep)) + } + return +} + +// And conjunction Sqlizers +type And conj + +func (a And) ToSql() (string, []interface{}, error) { + return conj(a).join(" AND ", sqlTrue) +} + +// Or conjunction Sqlizers +type Or conj + +func (o Or) ToSql() (string, []interface{}, error) { + return conj(o).join(" OR ", sqlFalse) +} + +func getSortedKeys(exp map[string]interface{}) []string { + sortedKeys := make([]string, 0, len(exp)) + for k := range exp { + sortedKeys = append(sortedKeys, k) + } + sort.Strings(sortedKeys) + return sortedKeys +} + +func isListType(val interface{}) bool { + if driver.IsValue(val) { + return false + } + valVal := reflect.ValueOf(val) + return valVal.Kind() == reflect.Array || valVal.Kind() == reflect.Slice +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/go.mod b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..235b74d07f881f428e68d2218ead6b3dba9d335e --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/go.mod @@ -0,0 +1,11 @@ +module github.com/Masterminds/squirrel + +go 1.14 + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 + github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/stretchr/testify v1.2.2 +) diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/go.sum b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..a92f768e60f084b42661848ff2828be637d9bfac --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/go.sum @@ -0,0 +1,10 @@ +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw= +github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o= +github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk= +github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/insert.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/insert.go new file mode 100644 index 0000000000000000000000000000000000000000..97870783aad362fc20fb246ca128fefca341e637 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/insert.go @@ -0,0 +1,298 @@ +package squirrel + +import ( + "bytes" + "database/sql" + "errors" + "fmt" + "io" + "sort" + "strings" + + "github.com/lann/builder" +) + +type insertData struct { + PlaceholderFormat PlaceholderFormat + RunWith BaseRunner + Prefixes []Sqlizer + StatementKeyword string + Options []string + Into string + Columns []string + Values [][]interface{} + Suffixes []Sqlizer + Select *SelectBuilder +} + +func (d *insertData) Exec() (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return ExecWith(d.RunWith, d) +} + +func (d *insertData) Query() (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return QueryWith(d.RunWith, d) +} + +func (d *insertData) QueryRow() RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRower) + if !ok { + return &Row{err: RunnerNotQueryRunner} + } + return QueryRowWith(queryRower, d) +} + +func (d *insertData) ToSql() (sqlStr string, args []interface{}, err error) { + if len(d.Into) == 0 { + err = errors.New("insert statements must specify a table") + return + } + if len(d.Values) == 0 && d.Select == nil { + err = errors.New("insert statements must have at least one set of values or select clause") + return + } + + sql := &bytes.Buffer{} + + if len(d.Prefixes) > 0 { + args, err = appendToSql(d.Prefixes, sql, " ", args) + if err != nil { + return + } + + sql.WriteString(" ") + } + + if d.StatementKeyword == "" { + sql.WriteString("INSERT ") + } else { + sql.WriteString(d.StatementKeyword) + sql.WriteString(" ") + } + + if len(d.Options) > 0 { + sql.WriteString(strings.Join(d.Options, " ")) + sql.WriteString(" ") + } + + sql.WriteString("INTO ") + sql.WriteString(d.Into) + sql.WriteString(" ") + + if len(d.Columns) > 0 { + sql.WriteString("(") + sql.WriteString(strings.Join(d.Columns, ",")) + sql.WriteString(") ") + } + + if d.Select != nil { + args, err = d.appendSelectToSQL(sql, args) + } else { + args, err = d.appendValuesToSQL(sql, args) + } + if err != nil { + return + } + + if len(d.Suffixes) > 0 { + sql.WriteString(" ") + args, err = appendToSql(d.Suffixes, sql, " ", args) + if err != nil { + return + } + } + + sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sql.String()) + return +} + +func (d *insertData) appendValuesToSQL(w io.Writer, args []interface{}) ([]interface{}, error) { + if len(d.Values) == 0 { + return args, errors.New("values for insert statements are not set") + } + + io.WriteString(w, "VALUES ") + + valuesStrings := make([]string, len(d.Values)) + for r, row := range d.Values { + valueStrings := make([]string, len(row)) + for v, val := range row { + if vs, ok := val.(Sqlizer); ok { + vsql, vargs, err := vs.ToSql() + if err != nil { + return nil, err + } + valueStrings[v] = vsql + args = append(args, vargs...) + } else { + valueStrings[v] = "?" + args = append(args, val) + } + } + valuesStrings[r] = fmt.Sprintf("(%s)", strings.Join(valueStrings, ",")) + } + + io.WriteString(w, strings.Join(valuesStrings, ",")) + + return args, nil +} + +func (d *insertData) appendSelectToSQL(w io.Writer, args []interface{}) ([]interface{}, error) { + if d.Select == nil { + return args, errors.New("select clause for insert statements are not set") + } + + selectClause, sArgs, err := d.Select.ToSql() + if err != nil { + return args, err + } + + io.WriteString(w, selectClause) + args = append(args, sArgs...) + + return args, nil +} + +// Builder + +// InsertBuilder builds SQL INSERT statements. +type InsertBuilder builder.Builder + +func init() { + builder.Register(InsertBuilder{}, insertData{}) +} + +// Format methods + +// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the +// query. +func (b InsertBuilder) PlaceholderFormat(f PlaceholderFormat) InsertBuilder { + return builder.Set(b, "PlaceholderFormat", f).(InsertBuilder) +} + +// Runner methods + +// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec. +func (b InsertBuilder) RunWith(runner BaseRunner) InsertBuilder { + return setRunWith(b, runner).(InsertBuilder) +} + +// Exec builds and Execs the query with the Runner set by RunWith. +func (b InsertBuilder) Exec() (sql.Result, error) { + data := builder.GetStruct(b).(insertData) + return data.Exec() +} + +// Query builds and Querys the query with the Runner set by RunWith. +func (b InsertBuilder) Query() (*sql.Rows, error) { + data := builder.GetStruct(b).(insertData) + return data.Query() +} + +// QueryRow builds and QueryRows the query with the Runner set by RunWith. +func (b InsertBuilder) QueryRow() RowScanner { + data := builder.GetStruct(b).(insertData) + return data.QueryRow() +} + +// Scan is a shortcut for QueryRow().Scan. +func (b InsertBuilder) Scan(dest ...interface{}) error { + return b.QueryRow().Scan(dest...) +} + +// SQL methods + +// ToSql builds the query into a SQL string and bound args. +func (b InsertBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(insertData) + return data.ToSql() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b InsertBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// Prefix adds an expression to the beginning of the query +func (b InsertBuilder) Prefix(sql string, args ...interface{}) InsertBuilder { + return b.PrefixExpr(Expr(sql, args...)) +} + +// PrefixExpr adds an expression to the very beginning of the query +func (b InsertBuilder) PrefixExpr(expr Sqlizer) InsertBuilder { + return builder.Append(b, "Prefixes", expr).(InsertBuilder) +} + +// Options adds keyword options before the INTO clause of the query. +func (b InsertBuilder) Options(options ...string) InsertBuilder { + return builder.Extend(b, "Options", options).(InsertBuilder) +} + +// Into sets the INTO clause of the query. +func (b InsertBuilder) Into(into string) InsertBuilder { + return builder.Set(b, "Into", into).(InsertBuilder) +} + +// Columns adds insert columns to the query. +func (b InsertBuilder) Columns(columns ...string) InsertBuilder { + return builder.Extend(b, "Columns", columns).(InsertBuilder) +} + +// Values adds a single row's values to the query. +func (b InsertBuilder) Values(values ...interface{}) InsertBuilder { + return builder.Append(b, "Values", values).(InsertBuilder) +} + +// Suffix adds an expression to the end of the query +func (b InsertBuilder) Suffix(sql string, args ...interface{}) InsertBuilder { + return b.SuffixExpr(Expr(sql, args...)) +} + +// SuffixExpr adds an expression to the end of the query +func (b InsertBuilder) SuffixExpr(expr Sqlizer) InsertBuilder { + return builder.Append(b, "Suffixes", expr).(InsertBuilder) +} + +// SetMap set columns and values for insert builder from a map of column name and value +// note that it will reset all previous columns and values was set if any +func (b InsertBuilder) SetMap(clauses map[string]interface{}) InsertBuilder { + // Keep the columns in a consistent order by sorting the column key string. + cols := make([]string, 0, len(clauses)) + for col := range clauses { + cols = append(cols, col) + } + sort.Strings(cols) + + vals := make([]interface{}, 0, len(clauses)) + for _, col := range cols { + vals = append(vals, clauses[col]) + } + + b = builder.Set(b, "Columns", cols).(InsertBuilder) + b = builder.Set(b, "Values", [][]interface{}{vals}).(InsertBuilder) + + return b +} + +// Select set Select clause for insert query +// If Values and Select are used, then Select has higher priority +func (b InsertBuilder) Select(sb SelectBuilder) InsertBuilder { + return builder.Set(b, "Select", &sb).(InsertBuilder) +} + +func (b InsertBuilder) statementKeyword(keyword string) InsertBuilder { + return builder.Set(b, "StatementKeyword", keyword).(InsertBuilder) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/insert_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/insert_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..84560eb90796dfa9cd466d8aa0853516168d31f5 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/insert_ctx.go @@ -0,0 +1,69 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + + "github.com/lann/builder" +) + +func (d *insertData) ExecContext(ctx context.Context) (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(ExecerContext) + if !ok { + return nil, NoContextSupport + } + return ExecContextWith(ctx, ctxRunner, d) +} + +func (d *insertData) QueryContext(ctx context.Context) (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(QueryerContext) + if !ok { + return nil, NoContextSupport + } + return QueryContextWith(ctx, ctxRunner, d) +} + +func (d *insertData) QueryRowContext(ctx context.Context) RowScanner { + if d.RunWith != nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRowerContext) + if !ok { + if _, ok := d.RunWith.(QueryerContext); !ok { + return &Row{err: RunnerNotQueryRunner} + } + return &Row{err: NoContextSupport} + } + return QueryRowContextWith(ctx, queryRower, d) +} + +// ExecContext builds and ExecContexts the query with the Runner set by RunWith. +func (b InsertBuilder) ExecContext(ctx context.Context) (sql.Result, error) { + data := builder.GetStruct(b).(insertData) + return data.ExecContext(ctx) +} + +// QueryContext builds and QueryContexts the query with the Runner set by RunWith. +func (b InsertBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) { + data := builder.GetStruct(b).(insertData) + return data.QueryContext(ctx) +} + +// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith. +func (b InsertBuilder) QueryRowContext(ctx context.Context) RowScanner { + data := builder.GetStruct(b).(insertData) + return data.QueryRowContext(ctx) +} + +// ScanContext is a shortcut for QueryRowContext().Scan. +func (b InsertBuilder) ScanContext(ctx context.Context, dest ...interface{}) error { + return b.QueryRowContext(ctx).Scan(dest...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/integration/doc.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/integration/doc.go new file mode 100644 index 0000000000000000000000000000000000000000..3796ab9ede31bfc6ce6f0872e70aad4d46a6beb3 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/integration/doc.go @@ -0,0 +1,2 @@ +// This is a tests-only package. +package integration diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/integration/go.mod b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/integration/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..8029ff8c8b17e541eaf93d5b0d3bab3cc33067fc --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/integration/go.mod @@ -0,0 +1,14 @@ +module github.com/Masterminds/squirrel/integration + +go 1.12 + +require ( + github.com/Masterminds/squirrel v1.1.0 + github.com/go-sql-driver/mysql v1.4.1 + github.com/lib/pq v1.2.0 + github.com/mattn/go-sqlite3 v1.13.0 + github.com/stretchr/testify v1.4.0 + google.golang.org/appengine v1.6.5 // indirect +) + +replace github.com/Masterminds/squirrel => ../ diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/integration/go.sum b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/integration/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..0bfcfa9f096176f194a2b5275638d2688cb952a9 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/integration/go.sum @@ -0,0 +1,34 @@ +github.com/Masterminds/squirrel v1.1.0 h1:baP1qLdoQCeTw3ifCdOq2dkYc6vGcmRdaociKLbEJXs= +github.com/Masterminds/squirrel v1.1.0/go.mod h1:yaPeOnPG5ZRwL9oKdTsO/prlkPbXWZlRVMQ/gGlzIuA= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-sql-driver/mysql v1.4.1 h1:g24URVg0OFbNUTx9qqY1IRZ9D9z3iPyi5zKhQZpNwpA= +github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw= +github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o= +github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk= +github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw= +github.com/lib/pq v1.2.0 h1:LXpIM/LZ5xGFhOpXAQUIMM1HdyqzVYM13zNdjCEEcA0= +github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/mattn/go-sqlite3 v1.13.0 h1:LnJI81JidiW9r7pS/hXe6cFeO5EXNq7KbfvoJLRI69c= +github.com/mattn/go-sqlite3 v1.13.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +google.golang.org/appengine v1.6.5 h1:tycE03LOZYQNhDpS27tcQdAzLCVMaj7QT2SXxebnpCM= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/part.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/part.go new file mode 100644 index 0000000000000000000000000000000000000000..c58f68f1a49717818bc349bede5cbf239bb06769 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/part.go @@ -0,0 +1,63 @@ +package squirrel + +import ( + "fmt" + "io" +) + +type part struct { + pred interface{} + args []interface{} +} + +func newPart(pred interface{}, args ...interface{}) Sqlizer { + return &part{pred, args} +} + +func (p part) ToSql() (sql string, args []interface{}, err error) { + switch pred := p.pred.(type) { + case nil: + // no-op + case Sqlizer: + sql, args, err = nestedToSql(pred) + case string: + sql = pred + args = p.args + default: + err = fmt.Errorf("expected string or Sqlizer, not %T", pred) + } + return +} + +func nestedToSql(s Sqlizer) (string, []interface{}, error) { + if raw, ok := s.(rawSqlizer); ok { + return raw.toSqlRaw() + } else { + return s.ToSql() + } +} + +func appendToSql(parts []Sqlizer, w io.Writer, sep string, args []interface{}) ([]interface{}, error) { + for i, p := range parts { + partSql, partArgs, err := nestedToSql(p) + if err != nil { + return nil, err + } else if len(partSql) == 0 { + continue + } + + if i > 0 { + _, err := io.WriteString(w, sep) + if err != nil { + return nil, err + } + } + + _, err = io.WriteString(w, partSql) + if err != nil { + return nil, err + } + args = append(args, partArgs...) + } + return args, nil +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/placeholder.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/placeholder.go new file mode 100644 index 0000000000000000000000000000000000000000..8e97a6c62d4b430def230bd65a84b6e294b11284 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/placeholder.go @@ -0,0 +1,114 @@ +package squirrel + +import ( + "bytes" + "fmt" + "strings" +) + +// PlaceholderFormat is the interface that wraps the ReplacePlaceholders method. +// +// ReplacePlaceholders takes a SQL statement and replaces each question mark +// placeholder with a (possibly different) SQL placeholder. +type PlaceholderFormat interface { + ReplacePlaceholders(sql string) (string, error) +} + +type placeholderDebugger interface { + debugPlaceholder() string +} + +var ( + // Question is a PlaceholderFormat instance that leaves placeholders as + // question marks. + Question = questionFormat{} + + // Dollar is a PlaceholderFormat instance that replaces placeholders with + // dollar-prefixed positional placeholders (e.g. $1, $2, $3). + Dollar = dollarFormat{} + + // Colon is a PlaceholderFormat instance that replaces placeholders with + // colon-prefixed positional placeholders (e.g. :1, :2, :3). + Colon = colonFormat{} + + // AtP is a PlaceholderFormat instance that replaces placeholders with + // "@p"-prefixed positional placeholders (e.g. @p1, @p2, @p3). + AtP = atpFormat{} +) + +type questionFormat struct{} + +func (questionFormat) ReplacePlaceholders(sql string) (string, error) { + return sql, nil +} + +func (questionFormat) debugPlaceholder() string { + return "?" +} + +type dollarFormat struct{} + +func (dollarFormat) ReplacePlaceholders(sql string) (string, error) { + return replacePositionalPlaceholders(sql, "$") +} + +func (dollarFormat) debugPlaceholder() string { + return "$" +} + +type colonFormat struct{} + +func (colonFormat) ReplacePlaceholders(sql string) (string, error) { + return replacePositionalPlaceholders(sql, ":") +} + +func (colonFormat) debugPlaceholder() string { + return ":" +} + +type atpFormat struct{} + +func (atpFormat) ReplacePlaceholders(sql string) (string, error) { + return replacePositionalPlaceholders(sql, "@p") +} + +func (atpFormat) debugPlaceholder() string { + return "@p" +} + +// Placeholders returns a string with count ? placeholders joined with commas. +func Placeholders(count int) string { + if count < 1 { + return "" + } + + return strings.Repeat(",?", count)[1:] +} + +func replacePositionalPlaceholders(sql, prefix string) (string, error) { + buf := &bytes.Buffer{} + i := 0 + for { + p := strings.Index(sql, "?") + if p == -1 { + break + } + + if len(sql[p:]) > 1 && sql[p:p+2] == "??" { // escape ?? => ? + buf.WriteString(sql[:p]) + buf.WriteString("?") + if len(sql[p:]) == 1 { + break + } + sql = sql[p+2:] + } else { + i++ + buf.WriteString(sql[:p]) + fmt.Fprintf(buf, "%s%d", prefix, i) + sql = sql[p+1:] + } + } + + buf.WriteString(sql) + return buf.String(), nil +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/row.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/row.go new file mode 100644 index 0000000000000000000000000000000000000000..74ffda92bde903c1e54282dc59ad6ef5d52e5577 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/row.go @@ -0,0 +1,22 @@ +package squirrel + +// RowScanner is the interface that wraps the Scan method. +// +// Scan behaves like database/sql.Row.Scan. +type RowScanner interface { + Scan(...interface{}) error +} + +// Row wraps database/sql.Row to let squirrel return new errors on Scan. +type Row struct { + RowScanner + err error +} + +// Scan returns Row.err or calls RowScanner.Scan. +func (r *Row) Scan(dest ...interface{}) error { + if r.err != nil { + return r.err + } + return r.RowScanner.Scan(dest...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/select.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/select.go new file mode 100644 index 0000000000000000000000000000000000000000..d55ce4c74079ac0c4dfe3316d6134cb8c2e61262 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/select.go @@ -0,0 +1,403 @@ +package squirrel + +import ( + "bytes" + "database/sql" + "fmt" + "strings" + + "github.com/lann/builder" +) + +type selectData struct { + PlaceholderFormat PlaceholderFormat + RunWith BaseRunner + Prefixes []Sqlizer + Options []string + Columns []Sqlizer + From Sqlizer + Joins []Sqlizer + WhereParts []Sqlizer + GroupBys []string + HavingParts []Sqlizer + OrderByParts []Sqlizer + Limit string + Offset string + Suffixes []Sqlizer +} + +func (d *selectData) Exec() (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return ExecWith(d.RunWith, d) +} + +func (d *selectData) Query() (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return QueryWith(d.RunWith, d) +} + +func (d *selectData) QueryRow() RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRower) + if !ok { + return &Row{err: RunnerNotQueryRunner} + } + return QueryRowWith(queryRower, d) +} + +func (d *selectData) ToSql() (sqlStr string, args []interface{}, err error) { + sqlStr, args, err = d.toSqlRaw() + if err != nil { + return + } + + sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sqlStr) + return +} + +func (d *selectData) toSqlRaw() (sqlStr string, args []interface{}, err error) { + if len(d.Columns) == 0 { + err = fmt.Errorf("select statements must have at least one result column") + return + } + + sql := &bytes.Buffer{} + + if len(d.Prefixes) > 0 { + args, err = appendToSql(d.Prefixes, sql, " ", args) + if err != nil { + return + } + + sql.WriteString(" ") + } + + sql.WriteString("SELECT ") + + if len(d.Options) > 0 { + sql.WriteString(strings.Join(d.Options, " ")) + sql.WriteString(" ") + } + + if len(d.Columns) > 0 { + args, err = appendToSql(d.Columns, sql, ", ", args) + if err != nil { + return + } + } + + if d.From != nil { + sql.WriteString(" FROM ") + args, err = appendToSql([]Sqlizer{d.From}, sql, "", args) + if err != nil { + return + } + } + + if len(d.Joins) > 0 { + sql.WriteString(" ") + args, err = appendToSql(d.Joins, sql, " ", args) + if err != nil { + return + } + } + + if len(d.WhereParts) > 0 { + sql.WriteString(" WHERE ") + args, err = appendToSql(d.WhereParts, sql, " AND ", args) + if err != nil { + return + } + } + + if len(d.GroupBys) > 0 { + sql.WriteString(" GROUP BY ") + sql.WriteString(strings.Join(d.GroupBys, ", ")) + } + + if len(d.HavingParts) > 0 { + sql.WriteString(" HAVING ") + args, err = appendToSql(d.HavingParts, sql, " AND ", args) + if err != nil { + return + } + } + + if len(d.OrderByParts) > 0 { + sql.WriteString(" ORDER BY ") + args, err = appendToSql(d.OrderByParts, sql, ", ", args) + if err != nil { + return + } + } + + if len(d.Limit) > 0 { + sql.WriteString(" LIMIT ") + sql.WriteString(d.Limit) + } + + if len(d.Offset) > 0 { + sql.WriteString(" OFFSET ") + sql.WriteString(d.Offset) + } + + if len(d.Suffixes) > 0 { + sql.WriteString(" ") + + args, err = appendToSql(d.Suffixes, sql, " ", args) + if err != nil { + return + } + } + + sqlStr = sql.String() + return +} + +// Builder + +// SelectBuilder builds SQL SELECT statements. +type SelectBuilder builder.Builder + +func init() { + builder.Register(SelectBuilder{}, selectData{}) +} + +// Format methods + +// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the +// query. +func (b SelectBuilder) PlaceholderFormat(f PlaceholderFormat) SelectBuilder { + return builder.Set(b, "PlaceholderFormat", f).(SelectBuilder) +} + +// Runner methods + +// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec. +// For most cases runner will be a database connection. +// +// Internally we use this to mock out the database connection for testing. +func (b SelectBuilder) RunWith(runner BaseRunner) SelectBuilder { + return setRunWith(b, runner).(SelectBuilder) +} + +// Exec builds and Execs the query with the Runner set by RunWith. +func (b SelectBuilder) Exec() (sql.Result, error) { + data := builder.GetStruct(b).(selectData) + return data.Exec() +} + +// Query builds and Querys the query with the Runner set by RunWith. +func (b SelectBuilder) Query() (*sql.Rows, error) { + data := builder.GetStruct(b).(selectData) + return data.Query() +} + +// QueryRow builds and QueryRows the query with the Runner set by RunWith. +func (b SelectBuilder) QueryRow() RowScanner { + data := builder.GetStruct(b).(selectData) + return data.QueryRow() +} + +// Scan is a shortcut for QueryRow().Scan. +func (b SelectBuilder) Scan(dest ...interface{}) error { + return b.QueryRow().Scan(dest...) +} + +// SQL methods + +// ToSql builds the query into a SQL string and bound args. +func (b SelectBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(selectData) + return data.ToSql() +} + +func (b SelectBuilder) toSqlRaw() (string, []interface{}, error) { + data := builder.GetStruct(b).(selectData) + return data.toSqlRaw() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b SelectBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// Prefix adds an expression to the beginning of the query +func (b SelectBuilder) Prefix(sql string, args ...interface{}) SelectBuilder { + return b.PrefixExpr(Expr(sql, args...)) +} + +// PrefixExpr adds an expression to the very beginning of the query +func (b SelectBuilder) PrefixExpr(expr Sqlizer) SelectBuilder { + return builder.Append(b, "Prefixes", expr).(SelectBuilder) +} + +// Distinct adds a DISTINCT clause to the query. +func (b SelectBuilder) Distinct() SelectBuilder { + return b.Options("DISTINCT") +} + +// Options adds select option to the query +func (b SelectBuilder) Options(options ...string) SelectBuilder { + return builder.Extend(b, "Options", options).(SelectBuilder) +} + +// Columns adds result columns to the query. +func (b SelectBuilder) Columns(columns ...string) SelectBuilder { + parts := make([]interface{}, 0, len(columns)) + for _, str := range columns { + parts = append(parts, newPart(str)) + } + return builder.Extend(b, "Columns", parts).(SelectBuilder) +} + +// RemoveColumns remove all columns from query. +// Must add a new column with Column or Columns methods, otherwise +// return a error. +func (b SelectBuilder) RemoveColumns() SelectBuilder { + return builder.Delete(b, "Columns").(SelectBuilder) +} + +// Column adds a result column to the query. +// Unlike Columns, Column accepts args which will be bound to placeholders in +// the columns string, for example: +// Column("IF(col IN ("+squirrel.Placeholders(3)+"), 1, 0) as col", 1, 2, 3) +func (b SelectBuilder) Column(column interface{}, args ...interface{}) SelectBuilder { + return builder.Append(b, "Columns", newPart(column, args...)).(SelectBuilder) +} + +// From sets the FROM clause of the query. +func (b SelectBuilder) From(from string) SelectBuilder { + return builder.Set(b, "From", newPart(from)).(SelectBuilder) +} + +// FromSelect sets a subquery into the FROM clause of the query. +func (b SelectBuilder) FromSelect(from SelectBuilder, alias string) SelectBuilder { + // Prevent misnumbered parameters in nested selects (#183). + from = from.PlaceholderFormat(Question) + return builder.Set(b, "From", Alias(from, alias)).(SelectBuilder) +} + +// JoinClause adds a join clause to the query. +func (b SelectBuilder) JoinClause(pred interface{}, args ...interface{}) SelectBuilder { + return builder.Append(b, "Joins", newPart(pred, args...)).(SelectBuilder) +} + +// Join adds a JOIN clause to the query. +func (b SelectBuilder) Join(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("JOIN "+join, rest...) +} + +// LeftJoin adds a LEFT JOIN clause to the query. +func (b SelectBuilder) LeftJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("LEFT JOIN "+join, rest...) +} + +// RightJoin adds a RIGHT JOIN clause to the query. +func (b SelectBuilder) RightJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("RIGHT JOIN "+join, rest...) +} + +// InnerJoin adds a INNER JOIN clause to the query. +func (b SelectBuilder) InnerJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("INNER JOIN "+join, rest...) +} + +// CrossJoin adds a CROSS JOIN clause to the query. +func (b SelectBuilder) CrossJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("CROSS JOIN "+join, rest...) +} + +// Where adds an expression to the WHERE clause of the query. +// +// Expressions are ANDed together in the generated SQL. +// +// Where accepts several types for its pred argument: +// +// nil OR "" - ignored. +// +// string - SQL expression. +// If the expression has SQL placeholders then a set of arguments must be passed +// as well, one for each placeholder. +// +// map[string]interface{} OR Eq - map of SQL expressions to values. Each key is +// transformed into an expression like " = ?", with the corresponding value +// bound to the placeholder. If the value is nil, the expression will be " +// IS NULL". If the value is an array or slice, the expression will be " IN +// (?,?,...)", with one placeholder for each item in the value. These expressions +// are ANDed together. +// +// Where will panic if pred isn't any of the above types. +func (b SelectBuilder) Where(pred interface{}, args ...interface{}) SelectBuilder { + if pred == nil || pred == "" { + return b + } + return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(SelectBuilder) +} + +// GroupBy adds GROUP BY expressions to the query. +func (b SelectBuilder) GroupBy(groupBys ...string) SelectBuilder { + return builder.Extend(b, "GroupBys", groupBys).(SelectBuilder) +} + +// Having adds an expression to the HAVING clause of the query. +// +// See Where. +func (b SelectBuilder) Having(pred interface{}, rest ...interface{}) SelectBuilder { + return builder.Append(b, "HavingParts", newWherePart(pred, rest...)).(SelectBuilder) +} + +// OrderByClause adds ORDER BY clause to the query. +func (b SelectBuilder) OrderByClause(pred interface{}, args ...interface{}) SelectBuilder { + return builder.Append(b, "OrderByParts", newPart(pred, args...)).(SelectBuilder) +} + +// OrderBy adds ORDER BY expressions to the query. +func (b SelectBuilder) OrderBy(orderBys ...string) SelectBuilder { + for _, orderBy := range orderBys { + b = b.OrderByClause(orderBy) + } + + return b +} + +// Limit sets a LIMIT clause on the query. +func (b SelectBuilder) Limit(limit uint64) SelectBuilder { + return builder.Set(b, "Limit", fmt.Sprintf("%d", limit)).(SelectBuilder) +} + +// Limit ALL allows to access all records with limit +func (b SelectBuilder) RemoveLimit() SelectBuilder { + return builder.Delete(b, "Limit").(SelectBuilder) +} + +// Offset sets a OFFSET clause on the query. +func (b SelectBuilder) Offset(offset uint64) SelectBuilder { + return builder.Set(b, "Offset", fmt.Sprintf("%d", offset)).(SelectBuilder) +} + +// RemoveOffset removes OFFSET clause. +func (b SelectBuilder) RemoveOffset() SelectBuilder { + return builder.Delete(b, "Offset").(SelectBuilder) +} + +// Suffix adds an expression to the end of the query +func (b SelectBuilder) Suffix(sql string, args ...interface{}) SelectBuilder { + return b.SuffixExpr(Expr(sql, args...)) +} + +// SuffixExpr adds an expression to the end of the query +func (b SelectBuilder) SuffixExpr(expr Sqlizer) SelectBuilder { + return builder.Append(b, "Suffixes", expr).(SelectBuilder) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/select_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/select_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..4c42c13f478965d0dbe206ccf7fbb8e347d726b3 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/select_ctx.go @@ -0,0 +1,69 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + + "github.com/lann/builder" +) + +func (d *selectData) ExecContext(ctx context.Context) (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(ExecerContext) + if !ok { + return nil, NoContextSupport + } + return ExecContextWith(ctx, ctxRunner, d) +} + +func (d *selectData) QueryContext(ctx context.Context) (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(QueryerContext) + if !ok { + return nil, NoContextSupport + } + return QueryContextWith(ctx, ctxRunner, d) +} + +func (d *selectData) QueryRowContext(ctx context.Context) RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRowerContext) + if !ok { + if _, ok := d.RunWith.(QueryerContext); !ok { + return &Row{err: RunnerNotQueryRunner} + } + return &Row{err: NoContextSupport} + } + return QueryRowContextWith(ctx, queryRower, d) +} + +// ExecContext builds and ExecContexts the query with the Runner set by RunWith. +func (b SelectBuilder) ExecContext(ctx context.Context) (sql.Result, error) { + data := builder.GetStruct(b).(selectData) + return data.ExecContext(ctx) +} + +// QueryContext builds and QueryContexts the query with the Runner set by RunWith. +func (b SelectBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) { + data := builder.GetStruct(b).(selectData) + return data.QueryContext(ctx) +} + +// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith. +func (b SelectBuilder) QueryRowContext(ctx context.Context) RowScanner { + data := builder.GetStruct(b).(selectData) + return data.QueryRowContext(ctx) +} + +// ScanContext is a shortcut for QueryRowContext().Scan. +func (b SelectBuilder) ScanContext(ctx context.Context, dest ...interface{}) error { + return b.QueryRowContext(ctx).Scan(dest...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/squirrel.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/squirrel.go new file mode 100644 index 0000000000000000000000000000000000000000..46d456eb620c09b20161711440ffbef0d091fafd --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/squirrel.go @@ -0,0 +1,183 @@ +// Package squirrel provides a fluent SQL generator. +// +// See https://github.com/Masterminds/squirrel for examples. +package squirrel + +import ( + "bytes" + "database/sql" + "fmt" + "strings" + + "github.com/lann/builder" +) + +// Sqlizer is the interface that wraps the ToSql method. +// +// ToSql returns a SQL representation of the Sqlizer, along with a slice of args +// as passed to e.g. database/sql.Exec. It can also return an error. +type Sqlizer interface { + ToSql() (string, []interface{}, error) +} + +// rawSqlizer is expected to do what Sqlizer does, but without finalizing placeholders. +// This is useful for nested queries. +type rawSqlizer interface { + toSqlRaw() (string, []interface{}, error) +} + +// Execer is the interface that wraps the Exec method. +// +// Exec executes the given query as implemented by database/sql.Exec. +type Execer interface { + Exec(query string, args ...interface{}) (sql.Result, error) +} + +// Queryer is the interface that wraps the Query method. +// +// Query executes the given query as implemented by database/sql.Query. +type Queryer interface { + Query(query string, args ...interface{}) (*sql.Rows, error) +} + +// QueryRower is the interface that wraps the QueryRow method. +// +// QueryRow executes the given query as implemented by database/sql.QueryRow. +type QueryRower interface { + QueryRow(query string, args ...interface{}) RowScanner +} + +// BaseRunner groups the Execer and Queryer interfaces. +type BaseRunner interface { + Execer + Queryer +} + +// Runner groups the Execer, Queryer, and QueryRower interfaces. +type Runner interface { + Execer + Queryer + QueryRower +} + +// WrapStdSql wraps a type implementing the standard SQL interface with methods that +// squirrel expects. +func WrapStdSql(stdSql StdSql) Runner { + return &stdsqlRunner{stdSql} +} + +// StdSql encompasses the standard methods of the *sql.DB type, and other types that +// wrap these methods. +type StdSql interface { + Query(string, ...interface{}) (*sql.Rows, error) + QueryRow(string, ...interface{}) *sql.Row + Exec(string, ...interface{}) (sql.Result, error) +} + +type stdsqlRunner struct { + StdSql +} + +func (r *stdsqlRunner) QueryRow(query string, args ...interface{}) RowScanner { + return r.StdSql.QueryRow(query, args...) +} + +func setRunWith(b interface{}, runner BaseRunner) interface{} { + switch r := runner.(type) { + case StdSqlCtx: + runner = WrapStdSqlCtx(r) + case StdSql: + runner = WrapStdSql(r) + } + return builder.Set(b, "RunWith", runner) +} + +// RunnerNotSet is returned by methods that need a Runner if it isn't set. +var RunnerNotSet = fmt.Errorf("cannot run; no Runner set (RunWith)") + +// RunnerNotQueryRunner is returned by QueryRow if the RunWith value doesn't implement QueryRower. +var RunnerNotQueryRunner = fmt.Errorf("cannot QueryRow; Runner is not a QueryRower") + +// ExecWith Execs the SQL returned by s with db. +func ExecWith(db Execer, s Sqlizer) (res sql.Result, err error) { + query, args, err := s.ToSql() + if err != nil { + return + } + return db.Exec(query, args...) +} + +// QueryWith Querys the SQL returned by s with db. +func QueryWith(db Queryer, s Sqlizer) (rows *sql.Rows, err error) { + query, args, err := s.ToSql() + if err != nil { + return + } + return db.Query(query, args...) +} + +// QueryRowWith QueryRows the SQL returned by s with db. +func QueryRowWith(db QueryRower, s Sqlizer) RowScanner { + query, args, err := s.ToSql() + return &Row{RowScanner: db.QueryRow(query, args...), err: err} +} + +// DebugSqlizer calls ToSql on s and shows the approximate SQL to be executed +// +// If ToSql returns an error, the result of this method will look like: +// "[ToSql error: %s]" or "[DebugSqlizer error: %s]" +// +// IMPORTANT: As its name suggests, this function should only be used for +// debugging. While the string result *might* be valid SQL, this function does +// not try very hard to ensure it. Additionally, executing the output of this +// function with any untrusted user input is certainly insecure. +func DebugSqlizer(s Sqlizer) string { + sql, args, err := s.ToSql() + if err != nil { + return fmt.Sprintf("[ToSql error: %s]", err) + } + + var placeholder string + downCast, ok := s.(placeholderDebugger) + if !ok { + placeholder = "?" + } else { + placeholder = downCast.debugPlaceholder() + } + // TODO: dedupe this with placeholder.go + buf := &bytes.Buffer{} + i := 0 + for { + p := strings.Index(sql, placeholder) + if p == -1 { + break + } + if len(sql[p:]) > 1 && sql[p:p+2] == "??" { // escape ?? => ? + buf.WriteString(sql[:p]) + buf.WriteString("?") + if len(sql[p:]) == 1 { + break + } + sql = sql[p+2:] + } else { + if i+1 > len(args) { + return fmt.Sprintf( + "[DebugSqlizer error: too many placeholders in %#v for %d args]", + sql, len(args)) + } + buf.WriteString(sql[:p]) + fmt.Fprintf(buf, "'%v'", args[i]) + // advance our sql string "cursor" beyond the arg we placed + sql = sql[p+1:] + i++ + } + } + if i < len(args) { + return fmt.Sprintf( + "[DebugSqlizer error: not enough placeholders in %#v for %d args]", + sql, len(args)) + } + // "append" any remaning sql that won't need interpolating + buf.WriteString(sql) + return buf.String() +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/squirrel_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/squirrel_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..c20148ad33c76cf86b64f4f0dd88f8a9f1c96dd7 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/squirrel_ctx.go @@ -0,0 +1,93 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + "errors" +) + +// NoContextSupport is returned if a db doesn't support Context. +var NoContextSupport = errors.New("DB does not support Context") + +// ExecerContext is the interface that wraps the ExecContext method. +// +// Exec executes the given query as implemented by database/sql.ExecContext. +type ExecerContext interface { + ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) +} + +// QueryerContext is the interface that wraps the QueryContext method. +// +// QueryContext executes the given query as implemented by database/sql.QueryContext. +type QueryerContext interface { + QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) +} + +// QueryRowerContext is the interface that wraps the QueryRowContext method. +// +// QueryRowContext executes the given query as implemented by database/sql.QueryRowContext. +type QueryRowerContext interface { + QueryRowContext(ctx context.Context, query string, args ...interface{}) RowScanner +} + +// RunnerContext groups the Runner interface, along with the Context versions of each of +// its methods +type RunnerContext interface { + Runner + QueryerContext + QueryRowerContext + ExecerContext +} + +// WrapStdSqlCtx wraps a type implementing the standard SQL interface plus the context +// versions of the methods with methods that squirrel expects. +func WrapStdSqlCtx(stdSqlCtx StdSqlCtx) RunnerContext { + return &stdsqlCtxRunner{stdSqlCtx} +} + +// StdSqlCtx encompasses the standard methods of the *sql.DB type, along with the Context +// versions of those methods, and other types that wrap these methods. +type StdSqlCtx interface { + StdSql + QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error) + QueryRowContext(context.Context, string, ...interface{}) *sql.Row + ExecContext(context.Context, string, ...interface{}) (sql.Result, error) +} + +type stdsqlCtxRunner struct { + StdSqlCtx +} + +func (r *stdsqlCtxRunner) QueryRow(query string, args ...interface{}) RowScanner { + return r.StdSqlCtx.QueryRow(query, args...) +} + +func (r *stdsqlCtxRunner) QueryRowContext(ctx context.Context, query string, args ...interface{}) RowScanner { + return r.StdSqlCtx.QueryRowContext(ctx, query, args...) +} + +// ExecContextWith ExecContexts the SQL returned by s with db. +func ExecContextWith(ctx context.Context, db ExecerContext, s Sqlizer) (res sql.Result, err error) { + query, args, err := s.ToSql() + if err != nil { + return + } + return db.ExecContext(ctx, query, args...) +} + +// QueryContextWith QueryContexts the SQL returned by s with db. +func QueryContextWith(ctx context.Context, db QueryerContext, s Sqlizer) (rows *sql.Rows, err error) { + query, args, err := s.ToSql() + if err != nil { + return + } + return db.QueryContext(ctx, query, args...) +} + +// QueryRowContextWith QueryRowContexts the SQL returned by s with db. +func QueryRowContextWith(ctx context.Context, db QueryRowerContext, s Sqlizer) RowScanner { + query, args, err := s.ToSql() + return &Row{RowScanner: db.QueryRowContext(ctx, query, args...), err: err} +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/statement.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/statement.go new file mode 100644 index 0000000000000000000000000000000000000000..9420c67f8e921e04876efea27bec4a5c5cd4921d --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/statement.go @@ -0,0 +1,104 @@ +package squirrel + +import "github.com/lann/builder" + +// StatementBuilderType is the type of StatementBuilder. +type StatementBuilderType builder.Builder + +// Select returns a SelectBuilder for this StatementBuilderType. +func (b StatementBuilderType) Select(columns ...string) SelectBuilder { + return SelectBuilder(b).Columns(columns...) +} + +// Insert returns a InsertBuilder for this StatementBuilderType. +func (b StatementBuilderType) Insert(into string) InsertBuilder { + return InsertBuilder(b).Into(into) +} + +// Replace returns a InsertBuilder for this StatementBuilderType with the +// statement keyword set to "REPLACE". +func (b StatementBuilderType) Replace(into string) InsertBuilder { + return InsertBuilder(b).statementKeyword("REPLACE").Into(into) +} + +// Update returns a UpdateBuilder for this StatementBuilderType. +func (b StatementBuilderType) Update(table string) UpdateBuilder { + return UpdateBuilder(b).Table(table) +} + +// Delete returns a DeleteBuilder for this StatementBuilderType. +func (b StatementBuilderType) Delete(from string) DeleteBuilder { + return DeleteBuilder(b).From(from) +} + +// PlaceholderFormat sets the PlaceholderFormat field for any child builders. +func (b StatementBuilderType) PlaceholderFormat(f PlaceholderFormat) StatementBuilderType { + return builder.Set(b, "PlaceholderFormat", f).(StatementBuilderType) +} + +// RunWith sets the RunWith field for any child builders. +func (b StatementBuilderType) RunWith(runner BaseRunner) StatementBuilderType { + return setRunWith(b, runner).(StatementBuilderType) +} + +// Where adds WHERE expressions to the query. +// +// See SelectBuilder.Where for more information. +func (b StatementBuilderType) Where(pred interface{}, args ...interface{}) StatementBuilderType { + return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(StatementBuilderType) +} + +// StatementBuilder is a parent builder for other builders, e.g. SelectBuilder. +var StatementBuilder = StatementBuilderType(builder.EmptyBuilder).PlaceholderFormat(Question) + +// Select returns a new SelectBuilder, optionally setting some result columns. +// +// See SelectBuilder.Columns. +func Select(columns ...string) SelectBuilder { + return StatementBuilder.Select(columns...) +} + +// Insert returns a new InsertBuilder with the given table name. +// +// See InsertBuilder.Into. +func Insert(into string) InsertBuilder { + return StatementBuilder.Insert(into) +} + +// Replace returns a new InsertBuilder with the statement keyword set to +// "REPLACE" and with the given table name. +// +// See InsertBuilder.Into. +func Replace(into string) InsertBuilder { + return StatementBuilder.Replace(into) +} + +// Update returns a new UpdateBuilder with the given table name. +// +// See UpdateBuilder.Table. +func Update(table string) UpdateBuilder { + return StatementBuilder.Update(table) +} + +// Delete returns a new DeleteBuilder with the given table name. +// +// See DeleteBuilder.Table. +func Delete(from string) DeleteBuilder { + return StatementBuilder.Delete(from) +} + +// Case returns a new CaseBuilder +// "what" represents case value +func Case(what ...interface{}) CaseBuilder { + b := CaseBuilder(builder.EmptyBuilder) + + switch len(what) { + case 0: + case 1: + b = b.what(what[0]) + default: + b = b.what(newPart(what[0], what[1:]...)) + + } + return b +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/stmtcacher.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/stmtcacher.go new file mode 100644 index 0000000000000000000000000000000000000000..5bf267a13642d0c6734cf013a6e631f6ca1f0bc6 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/stmtcacher.go @@ -0,0 +1,121 @@ +package squirrel + +import ( + "database/sql" + "fmt" + "sync" +) + +// Prepareer is the interface that wraps the Prepare method. +// +// Prepare executes the given query as implemented by database/sql.Prepare. +type Preparer interface { + Prepare(query string) (*sql.Stmt, error) +} + +// DBProxy groups the Execer, Queryer, QueryRower, and Preparer interfaces. +type DBProxy interface { + Execer + Queryer + QueryRower + Preparer +} + +// NOTE: NewStmtCache is defined in stmtcacher_ctx.go (Go >= 1.8) or stmtcacher_noctx.go (Go < 1.8). + +// StmtCache wraps and delegates down to a Preparer type +// +// It also automatically prepares all statements sent to the underlying Preparer calls +// for Exec, Query and QueryRow and caches the returns *sql.Stmt using the provided +// query as the key. So that it can be automatically re-used. +type StmtCache struct { + prep Preparer + cache map[string]*sql.Stmt + mu sync.Mutex +} + +// Prepare delegates down to the underlying Preparer and caches the result +// using the provided query as a key +func (sc *StmtCache) Prepare(query string) (*sql.Stmt, error) { + sc.mu.Lock() + defer sc.mu.Unlock() + + stmt, ok := sc.cache[query] + if ok { + return stmt, nil + } + stmt, err := sc.prep.Prepare(query) + if err == nil { + sc.cache[query] = stmt + } + return stmt, err +} + +// Exec delegates down to the underlying Preparer using a prepared statement +func (sc *StmtCache) Exec(query string, args ...interface{}) (res sql.Result, err error) { + stmt, err := sc.Prepare(query) + if err != nil { + return + } + return stmt.Exec(args...) +} + +// Query delegates down to the underlying Preparer using a prepared statement +func (sc *StmtCache) Query(query string, args ...interface{}) (rows *sql.Rows, err error) { + stmt, err := sc.Prepare(query) + if err != nil { + return + } + return stmt.Query(args...) +} + +// QueryRow delegates down to the underlying Preparer using a prepared statement +func (sc *StmtCache) QueryRow(query string, args ...interface{}) RowScanner { + stmt, err := sc.Prepare(query) + if err != nil { + return &Row{err: err} + } + return stmt.QueryRow(args...) +} + +// Clear removes and closes all the currently cached prepared statements +func (sc *StmtCache) Clear() (err error) { + sc.mu.Lock() + defer sc.mu.Unlock() + + for key, stmt := range sc.cache { + delete(sc.cache, key) + + if stmt == nil { + continue + } + + if cerr := stmt.Close(); cerr != nil { + err = cerr + } + } + + if err != nil { + return fmt.Errorf("one or more Stmt.Close failed; last error: %v", err) + } + + return +} + +type DBProxyBeginner interface { + DBProxy + Begin() (*sql.Tx, error) +} + +type stmtCacheProxy struct { + DBProxy + db *sql.DB +} + +func NewStmtCacheProxy(db *sql.DB) DBProxyBeginner { + return &stmtCacheProxy{DBProxy: NewStmtCache(db), db: db} +} + +func (sp *stmtCacheProxy) Begin() (*sql.Tx, error) { + return sp.db.Begin() +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/stmtcacher_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/stmtcacher_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..53603cf4c9548775644cbf2050a0d1f3c5150b73 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/stmtcacher_ctx.go @@ -0,0 +1,86 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" +) + +// PrepareerContext is the interface that wraps the Prepare and PrepareContext methods. +// +// Prepare executes the given query as implemented by database/sql.Prepare. +// PrepareContext executes the given query as implemented by database/sql.PrepareContext. +type PreparerContext interface { + Preparer + PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) +} + +// DBProxyContext groups the Execer, Queryer, QueryRower and PreparerContext interfaces. +type DBProxyContext interface { + Execer + Queryer + QueryRower + PreparerContext +} + +// NewStmtCache returns a *StmtCache wrapping a PreparerContext that caches Prepared Stmts. +// +// Stmts are cached based on the string value of their queries. +func NewStmtCache(prep PreparerContext) *StmtCache { + return &StmtCache{prep: prep, cache: make(map[string]*sql.Stmt)} +} + +// NewStmtCacher is deprecated +// +// Use NewStmtCache instead +func NewStmtCacher(prep PreparerContext) DBProxyContext { + return NewStmtCache(prep) +} + +// PrepareContext delegates down to the underlying PreparerContext and caches the result +// using the provided query as a key +func (sc *StmtCache) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) { + ctxPrep, ok := sc.prep.(PreparerContext) + if !ok { + return nil, NoContextSupport + } + sc.mu.Lock() + defer sc.mu.Unlock() + stmt, ok := sc.cache[query] + if ok { + return stmt, nil + } + stmt, err := ctxPrep.PrepareContext(ctx, query) + if err == nil { + sc.cache[query] = stmt + } + return stmt, err +} + +// ExecContext delegates down to the underlying PreparerContext using a prepared statement +func (sc *StmtCache) ExecContext(ctx context.Context, query string, args ...interface{}) (res sql.Result, err error) { + stmt, err := sc.PrepareContext(ctx, query) + if err != nil { + return + } + return stmt.ExecContext(ctx, args...) +} + +// QueryContext delegates down to the underlying PreparerContext using a prepared statement +func (sc *StmtCache) QueryContext(ctx context.Context, query string, args ...interface{}) (rows *sql.Rows, err error) { + stmt, err := sc.PrepareContext(ctx, query) + if err != nil { + return + } + return stmt.QueryContext(ctx, args...) +} + +// QueryRowContext delegates down to the underlying PreparerContext using a prepared statement +func (sc *StmtCache) QueryRowContext(ctx context.Context, query string, args ...interface{}) RowScanner { + stmt, err := sc.PrepareContext(ctx, query) + if err != nil { + return &Row{err: err} + } + return stmt.QueryRowContext(ctx, args...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/stmtcacher_noctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/stmtcacher_noctx.go new file mode 100644 index 0000000000000000000000000000000000000000..deac96777b7fd51ea468b9861b76571b1aa433bf --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/stmtcacher_noctx.go @@ -0,0 +1,21 @@ +// +build !go1.8 + +package squirrel + +import ( + "database/sql" +) + +// NewStmtCacher returns a DBProxy wrapping prep that caches Prepared Stmts. +// +// Stmts are cached based on the string value of their queries. +func NewStmtCache(prep Preparer) *StmtCache { + return &StmtCacher{prep: prep, cache: make(map[string]*sql.Stmt)} +} + +// NewStmtCacher is deprecated +// +// Use NewStmtCache instead +func NewStmtCacher(prep Preparer) DBProxy { + return NewStmtCache(prep) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/update.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/update.go new file mode 100644 index 0000000000000000000000000000000000000000..eb2a9c4dd9a07b893bbea241526d84c84acdc30a --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/update.go @@ -0,0 +1,288 @@ +package squirrel + +import ( + "bytes" + "database/sql" + "fmt" + "sort" + "strings" + + "github.com/lann/builder" +) + +type updateData struct { + PlaceholderFormat PlaceholderFormat + RunWith BaseRunner + Prefixes []Sqlizer + Table string + SetClauses []setClause + From Sqlizer + WhereParts []Sqlizer + OrderBys []string + Limit string + Offset string + Suffixes []Sqlizer +} + +type setClause struct { + column string + value interface{} +} + +func (d *updateData) Exec() (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return ExecWith(d.RunWith, d) +} + +func (d *updateData) Query() (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return QueryWith(d.RunWith, d) +} + +func (d *updateData) QueryRow() RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRower) + if !ok { + return &Row{err: RunnerNotQueryRunner} + } + return QueryRowWith(queryRower, d) +} + +func (d *updateData) ToSql() (sqlStr string, args []interface{}, err error) { + if len(d.Table) == 0 { + err = fmt.Errorf("update statements must specify a table") + return + } + if len(d.SetClauses) == 0 { + err = fmt.Errorf("update statements must have at least one Set clause") + return + } + + sql := &bytes.Buffer{} + + if len(d.Prefixes) > 0 { + args, err = appendToSql(d.Prefixes, sql, " ", args) + if err != nil { + return + } + + sql.WriteString(" ") + } + + sql.WriteString("UPDATE ") + sql.WriteString(d.Table) + + sql.WriteString(" SET ") + setSqls := make([]string, len(d.SetClauses)) + for i, setClause := range d.SetClauses { + var valSql string + if vs, ok := setClause.value.(Sqlizer); ok { + vsql, vargs, err := vs.ToSql() + if err != nil { + return "", nil, err + } + if _, ok := vs.(SelectBuilder); ok { + valSql = fmt.Sprintf("(%s)", vsql) + } else { + valSql = vsql + } + args = append(args, vargs...) + } else { + valSql = "?" + args = append(args, setClause.value) + } + setSqls[i] = fmt.Sprintf("%s = %s", setClause.column, valSql) + } + sql.WriteString(strings.Join(setSqls, ", ")) + + if d.From != nil { + sql.WriteString(" FROM ") + args, err = appendToSql([]Sqlizer{d.From}, sql, "", args) + if err != nil { + return + } + } + + if len(d.WhereParts) > 0 { + sql.WriteString(" WHERE ") + args, err = appendToSql(d.WhereParts, sql, " AND ", args) + if err != nil { + return + } + } + + if len(d.OrderBys) > 0 { + sql.WriteString(" ORDER BY ") + sql.WriteString(strings.Join(d.OrderBys, ", ")) + } + + if len(d.Limit) > 0 { + sql.WriteString(" LIMIT ") + sql.WriteString(d.Limit) + } + + if len(d.Offset) > 0 { + sql.WriteString(" OFFSET ") + sql.WriteString(d.Offset) + } + + if len(d.Suffixes) > 0 { + sql.WriteString(" ") + args, err = appendToSql(d.Suffixes, sql, " ", args) + if err != nil { + return + } + } + + sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sql.String()) + return +} + +// Builder + +// UpdateBuilder builds SQL UPDATE statements. +type UpdateBuilder builder.Builder + +func init() { + builder.Register(UpdateBuilder{}, updateData{}) +} + +// Format methods + +// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the +// query. +func (b UpdateBuilder) PlaceholderFormat(f PlaceholderFormat) UpdateBuilder { + return builder.Set(b, "PlaceholderFormat", f).(UpdateBuilder) +} + +// Runner methods + +// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec. +func (b UpdateBuilder) RunWith(runner BaseRunner) UpdateBuilder { + return setRunWith(b, runner).(UpdateBuilder) +} + +// Exec builds and Execs the query with the Runner set by RunWith. +func (b UpdateBuilder) Exec() (sql.Result, error) { + data := builder.GetStruct(b).(updateData) + return data.Exec() +} + +func (b UpdateBuilder) Query() (*sql.Rows, error) { + data := builder.GetStruct(b).(updateData) + return data.Query() +} + +func (b UpdateBuilder) QueryRow() RowScanner { + data := builder.GetStruct(b).(updateData) + return data.QueryRow() +} + +func (b UpdateBuilder) Scan(dest ...interface{}) error { + return b.QueryRow().Scan(dest...) +} + +// SQL methods + +// ToSql builds the query into a SQL string and bound args. +func (b UpdateBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(updateData) + return data.ToSql() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b UpdateBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// Prefix adds an expression to the beginning of the query +func (b UpdateBuilder) Prefix(sql string, args ...interface{}) UpdateBuilder { + return b.PrefixExpr(Expr(sql, args...)) +} + +// PrefixExpr adds an expression to the very beginning of the query +func (b UpdateBuilder) PrefixExpr(expr Sqlizer) UpdateBuilder { + return builder.Append(b, "Prefixes", expr).(UpdateBuilder) +} + +// Table sets the table to be updated. +func (b UpdateBuilder) Table(table string) UpdateBuilder { + return builder.Set(b, "Table", table).(UpdateBuilder) +} + +// Set adds SET clauses to the query. +func (b UpdateBuilder) Set(column string, value interface{}) UpdateBuilder { + return builder.Append(b, "SetClauses", setClause{column: column, value: value}).(UpdateBuilder) +} + +// SetMap is a convenience method which calls .Set for each key/value pair in clauses. +func (b UpdateBuilder) SetMap(clauses map[string]interface{}) UpdateBuilder { + keys := make([]string, len(clauses)) + i := 0 + for key := range clauses { + keys[i] = key + i++ + } + sort.Strings(keys) + for _, key := range keys { + val, _ := clauses[key] + b = b.Set(key, val) + } + return b +} + +// From adds FROM clause to the query +// FROM is valid construct in postgresql only. +func (b UpdateBuilder) From(from string) UpdateBuilder { + return builder.Set(b, "From", newPart(from)).(UpdateBuilder) +} + +// FromSelect sets a subquery into the FROM clause of the query. +func (b UpdateBuilder) FromSelect(from SelectBuilder, alias string) UpdateBuilder { + // Prevent misnumbered parameters in nested selects (#183). + from = from.PlaceholderFormat(Question) + return builder.Set(b, "From", Alias(from, alias)).(UpdateBuilder) +} + +// Where adds WHERE expressions to the query. +// +// See SelectBuilder.Where for more information. +func (b UpdateBuilder) Where(pred interface{}, args ...interface{}) UpdateBuilder { + return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(UpdateBuilder) +} + +// OrderBy adds ORDER BY expressions to the query. +func (b UpdateBuilder) OrderBy(orderBys ...string) UpdateBuilder { + return builder.Extend(b, "OrderBys", orderBys).(UpdateBuilder) +} + +// Limit sets a LIMIT clause on the query. +func (b UpdateBuilder) Limit(limit uint64) UpdateBuilder { + return builder.Set(b, "Limit", fmt.Sprintf("%d", limit)).(UpdateBuilder) +} + +// Offset sets a OFFSET clause on the query. +func (b UpdateBuilder) Offset(offset uint64) UpdateBuilder { + return builder.Set(b, "Offset", fmt.Sprintf("%d", offset)).(UpdateBuilder) +} + +// Suffix adds an expression to the end of the query +func (b UpdateBuilder) Suffix(sql string, args ...interface{}) UpdateBuilder { + return b.SuffixExpr(Expr(sql, args...)) +} + +// SuffixExpr adds an expression to the end of the query +func (b UpdateBuilder) SuffixExpr(expr Sqlizer) UpdateBuilder { + return builder.Append(b, "Suffixes", expr).(UpdateBuilder) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/update_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/update_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..ad479f96f49fd0f02da2f3ea44f0392f451ec5d5 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/update_ctx.go @@ -0,0 +1,69 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + + "github.com/lann/builder" +) + +func (d *updateData) ExecContext(ctx context.Context) (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(ExecerContext) + if !ok { + return nil, NoContextSupport + } + return ExecContextWith(ctx, ctxRunner, d) +} + +func (d *updateData) QueryContext(ctx context.Context) (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(QueryerContext) + if !ok { + return nil, NoContextSupport + } + return QueryContextWith(ctx, ctxRunner, d) +} + +func (d *updateData) QueryRowContext(ctx context.Context) RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRowerContext) + if !ok { + if _, ok := d.RunWith.(QueryerContext); !ok { + return &Row{err: RunnerNotQueryRunner} + } + return &Row{err: NoContextSupport} + } + return QueryRowContextWith(ctx, queryRower, d) +} + +// ExecContext builds and ExecContexts the query with the Runner set by RunWith. +func (b UpdateBuilder) ExecContext(ctx context.Context) (sql.Result, error) { + data := builder.GetStruct(b).(updateData) + return data.ExecContext(ctx) +} + +// QueryContext builds and QueryContexts the query with the Runner set by RunWith. +func (b UpdateBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) { + data := builder.GetStruct(b).(updateData) + return data.QueryContext(ctx) +} + +// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith. +func (b UpdateBuilder) QueryRowContext(ctx context.Context) RowScanner { + data := builder.GetStruct(b).(updateData) + return data.QueryRowContext(ctx) +} + +// ScanContext is a shortcut for QueryRowContext().Scan. +func (b UpdateBuilder) ScanContext(ctx context.Context, dest ...interface{}) error { + return b.QueryRowContext(ctx).Scan(dest...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/where.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/where.go new file mode 100644 index 0000000000000000000000000000000000000000..976b63ace4ecb4452f5326b1893067bb604d133e --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/environment/source/where.go @@ -0,0 +1,30 @@ +package squirrel + +import ( + "fmt" +) + +type wherePart part + +func newWherePart(pred interface{}, args ...interface{}) Sqlizer { + return &wherePart{pred: pred, args: args} +} + +func (p wherePart) ToSql() (sql string, args []interface{}, err error) { + switch pred := p.pred.(type) { + case nil: + // no-op + case rawSqlizer: + return pred.toSqlRaw() + case Sqlizer: + return pred.ToSql() + case map[string]interface{}: + return Eq(pred).ToSql() + case string: + sql = pred + args = p.args + default: + err = fmt.Errorf("expected string-keyed map or string, not %T", pred) + } + return +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/instruction.md b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3fa52d681d90b2fe10e872cf9579a554ec52aebd --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/instruction.md @@ -0,0 +1,41 @@ +QueryRowContext returns wrong error when Runner is set + +#### Description + +When using `QueryRowContext` with a Runner that is set but doesn't implement `QueryRowerContext`, the method returns the wrong error message. Instead of returning "cannot run; no Runner set (RunWith)" it returns "cannot QueryRow; Runner is not a QueryRower". + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "context" + "database/sql" + "fmt" + + "github.com/Masterminds/squirrel" +) + +type MockRunner struct{} + +func (m *MockRunner) Exec(query string, args ...interface{}) (sql.Result, error) { + return nil, nil +} + +func main() { + runner := &MockRunner{} + + insert := squirrel.Insert("test").Values("value").RunWith(runner) + + row := insert.QueryRowContext(context.Background()) + err := row.Scan() + + fmt.Printf("Error: %v\n", err) + // Expected: "cannot run; no Runner set (RunWith)" + // Actual: "cannot QueryRow; Runner is not a QueryRower" +} +``` + +The issue occurs when a Runner is set but doesn't implement the `QueryRowerContext` interface. The logic incorrectly checks if the Runner is nil instead of checking if it's not nil. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/provenance.json b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..649f6129ab94d5aa14f9cb92f69df96223a18943 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/provenance.json @@ -0,0 +1,385 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt", + "original-bug": "task-specific unchanged semantic bug", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only", + "extra_semantic_repair_coverage": false, + "original_patch_hunks": 1 + }, + "private_frozen_files": { + "case_test.go": { + "mode": "0o644", + "sha256": "fdb8c60761dc1ab02953e86f1736bd29e644e61bb7f67a394a5f71d276a67298", + "size": 3296 + }, + "delete_ctx_test.go": { + "mode": "0o644", + "sha256": "07e5cd531fbc380655a6f441eeee23da925195d67a1a7e7682785806af51014e", + "size": 847 + }, + "delete_test.go": { + "mode": "0o644", + "sha256": "44ac247a59eb89cd5f41e3f0948a78e51e757d0888a72874d12a12c6db1acfb0", + "size": 1806 + }, + "expr_test.go": { + "mode": "0o644", + "sha256": "ab52b68e40a81bda968dacc733f34c08626f299405450c383daf438e33897a65", + "size": 10245 + }, + "insert_ctx_test.go": { + "mode": "0o644", + "sha256": "b3e3efaf75fee82c147958afb70a90334f4f08cf29b64bd76d23a03b9824f299", + "size": 807 + }, + "insert_test.go": { + "mode": "0o644", + "sha256": "665fe6694c9ce48b2bcbdfd34ab9bde67d8fd7601b3d5798f4dacd693e1da278", + "size": 2627 + }, + "integration/integration_test.go": { + "mode": "0o644", + "sha256": "c8631b72fa30417861d7ba87a1a9a5c0883d01744fb49bf779360dc4a61b9abf", + "size": 3162 + }, + "placeholder_test.go": { + "mode": "0o644", + "sha256": "c498900e8f98d981e90863f0603d19c11db17e786eae008bdc5af2b25ae8eb13", + "size": 2005 + }, + "row_test.go": { + "mode": "0o644", + "sha256": "7fe834ce33424df8e009fa44ee5acea25508c7e439d1bf07fddf6d4c90e77ec1", + "size": 626 + }, + "select_ctx_test.go": { + "mode": "0o644", + "sha256": "560d37ac028fbf92ba5c5a20b95af7d866a4fbdecd0e868b6fe266eb4849e665", + "size": 771 + }, + "select_test.go": { + "mode": "0o644", + "sha256": "3b06e89b5c358992a7165414dbeb4643820d95574981359638d609931d528630", + "size": 12209 + }, + "squirrel_ctx_test.go": { + "mode": "0o644", + "sha256": "4a052ae48d428a0719777189c407e5d5c7087550c0d99b2c28cceada083f76b0", + "size": 1277 + }, + "squirrel_test.go": { + "mode": "0o644", + "sha256": "7336a2ffda333c52c145d76e926a89e1244ff24b96c86abfc6fe06723572180f", + "size": 5780 + }, + "statement_test.go": { + "mode": "0o644", + "sha256": "a0f46fa71157b09eaca3da0fa6a75b25156cb552c785228836b0ffbb9fe5ac27", + "size": 2072 + }, + "stmtcacher_ctx_test.go": { + "mode": "0o644", + "sha256": "a0a1f49a87ebb6b35b8d66fbe9051d8a9f94346eaf5e3cd70719424433f5c878", + "size": 402 + }, + "stmtcacher_test.go": { + "mode": "0o644", + "sha256": "e5b5020ac3c194cf92121100a24df580955f32f89bd600b1e56014702d24eb52", + "size": 546 + }, + "update_ctx_test.go": { + "mode": "0o644", + "sha256": "3dd7bd0c17bfb61fad6e71c7736ca6a207f811ae7c3f92f8185c5f7d32dbf30a", + "size": 805 + }, + "update_test.go": { + "mode": "0o644", + "sha256": "6316c8d144c647d9c7bdd6b8be4490c40398da03d331be23c4729faa7a57aa4e", + "size": 2836 + }, + "where_test.go": { + "mode": "0o644", + "sha256": "1a53006a294c379a8b7f212b340acf9063ea0b613062a52fc9585a7d84f853f3", + "size": 1325 + } + }, + "public_files": { + ".gitignore": { + "mode": "0o644", + "sha256": "1eaa1ee4d30ac564ac002a67650eff426807e1fd8b9475250d0ef31ee3d458dd", + "size": 13 + }, + ".travis.yml": { + "mode": "0o644", + "sha256": "5409f254b7fc2f4ed3afcdc45ac2346acedadf2689e14f5d4735e5587cd31a15", + "size": 768 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "11ac92da622d8d25df663d4bc5d12f464da1a98a9fbb75930e0e65cc58b80a2f", + "size": 1185 + }, + "README.md": { + "mode": "0o644", + "sha256": "f1dafb8f66d5eb204201e34fbcf50a08180b7cc6fffb9cd87ed55673d840afc2", + "size": 4363 + }, + "case.go": { + "mode": "0o644", + "sha256": "9c530c0585dcf3c1f12200afecbc2147edbdc18a2369f726486ebc169bfdb1f1", + "size": 3065 + }, + "delete.go": { + "mode": "0o644", + "sha256": "700cefe533a6d939aaa689dfcbf148ad8d4b07f0278337944ecc37767479b3eb", + "size": 4806 + }, + "delete_ctx.go": { + "mode": "0o644", + "sha256": "0fb7da25c0bee63500317da43e1d8bcb5b8d62487ec80e6298135953d62b03f4", + "size": 1908 + }, + "expr.go": { + "mode": "0o644", + "sha256": "246aa910b8adc931da8773bf9a782d8e8292c5315fd267d3aca2d75792842d8e", + "size": 9216 + }, + "go.mod": { + "mode": "0o644", + "sha256": "b4c6f216eafab7a1ca5209b5ddca006529666f72184aea72293395c69f7140f5", + "size": 321 + }, + "go.sum": { + "mode": "0o644", + "sha256": "2b4fe7850b36f8effe69d037ed1219df62399e4076034930b8f3d2edb7fa46fd", + "size": 953 + }, + "insert.go": { + "mode": "0o644", + "sha256": "626ac9dd6c5cbca5e9e3b93252d82c94d6d6b63ddc967fb0dbcee0f3dc889c2e", + "size": 7710 + }, + "insert_ctx.go": { + "mode": "0o644", + "sha256": "dd93090e78e53b917b9f253f696ab4ced04412d2dbb9b711190b65bf501bc1b9", + "size": 1908 + }, + "integration/doc.go": { + "mode": "0o644", + "sha256": "2eb5edda1be28404e1f6681d1177cd3f447f8167cacf51f817b853e578e5996c", + "size": 53 + }, + "integration/go.mod": { + "mode": "0o644", + "sha256": "b8f745640b55a496faf7e8ffe39dcbb223bd4a856c108f38cb5021c5c9fafc3b", + "size": 347 + }, + "integration/go.sum": { + "mode": "0o644", + "sha256": "30892c107aa863abb8105816d7f6fa497ec69fd1d6783f4f186a19ff0fe6df80", + "size": 3122 + }, + "part.go": { + "mode": "0o644", + "sha256": "5fb7ec420cb4f4eff065b0a71e073b8ac74a1a6a81647d19b490be9286bc2258", + "size": 1149 + }, + "placeholder.go": { + "mode": "0o644", + "sha256": "246a7219eb14597fa9322bac44691e6ff6f7437df8cf7e4f7fe15c263ce61114", + "size": 2558 + }, + "row.go": { + "mode": "0o644", + "sha256": "089fb1c058ccf2f6664c0cdaac097ad6616e5ec0b44939429bce737d70d9c50e", + "size": 472 + }, + "select.go": { + "mode": "0o644", + "sha256": "28ab9e3d2a9772d6e0ef08f4fa83ea1ccd4a246f086e0e9431a10e5d42504d33", + "size": 11320 + }, + "select_ctx.go": { + "mode": "0o644", + "sha256": "ac68ccbb975d46547f21be70d802af6f4de4ac4c41d9e26a925621e725d74787", + "size": 1908 + }, + "squirrel.go": { + "mode": "0o644", + "sha256": "a5d827d66fdd080a5f2efaccb74fca217265e995d667cf10a026dbc2871e70f9", + "size": 5074 + }, + "squirrel_ctx.go": { + "mode": "0o644", + "sha256": "2e903ebfb7941cb8f68100dc9c500b5bfb214ea8534aaa21e4ea7ed01a70085d", + "size": 3085 + }, + "statement.go": { + "mode": "0o644", + "sha256": "f6cbf3d520fe88614795a68113ea020dd9ad3977e9dcd42af6e0a48a906d2caa", + "size": 3254 + }, + "stmtcacher.go": { + "mode": "0o644", + "sha256": "8f1593570472ec435e653b16a331262629495915b8cf2fda9929e6c7fe0a3c5a", + "size": 2799 + }, + "stmtcacher_ctx.go": { + "mode": "0o644", + "sha256": "e0c02cbf487302ea082afa304b851c454ece0d85f7073c721afb9e5a9e32f7fc", + "size": 2550 + }, + "stmtcacher_noctx.go": { + "mode": "0o644", + "sha256": "14539e8754cc3ee236d7f8af2e0176fb5a8c6183d73ad0e797913ae51a400b22", + "size": 459 + }, + "update.go": { + "mode": "0o644", + "sha256": "0d9f5f030b6d4e31f21f2b84fa6f62df1cc0eb540a7fa04eb9ec68c2ed238e0a", + "size": 7349 + }, + "update_ctx.go": { + "mode": "0o644", + "sha256": "517c4436ea62524889f3a50339d1d3c3ee89ff23050eecaf5fa3a973b8ec4bf0", + "size": 1908 + }, + "where.go": { + "mode": "0o644", + "sha256": "555836c5dd84cbd7571b5e2b3b5b677f3fcd4cc42a0f1cfb3a176f8909bd0755", + "size": 572 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:8397c903899921169852f4bff3ee17f23d7d4f8eaf03854a2bffd0051a2b363f", + "os": "linux", + "sha256": "8397c903899921169852f4bff3ee17f23d7d4f8eaf03854a2bffd0051a2b363f" + }, + "context_inventory_sha256": "8c63f6649adee8ca9a2290a98a9a180d45b9f65f42395812e6e97b409186f81d", + "image": "registry.hf.space/harness-hub-scale800-go-055c69f17f410bee-starter-v1@sha256:9dfb6b7417f54d78d50e6e6bdd951b854ed8da8f5f1782f4fe563a85e1cd0b7a", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "dc294274d204bc3953b3ddc9f385c54f9ded95ae55c720729f3b4765c2561bba", + "receipt_path": "production/runtime-images-extra-v1/resolutions/055c69f17f410bee/resolution.json", + "receipt_sha256": "741436358af5538a7e21351cbe2660ca3aeb440246407b654888e4766be1dc7a", + "registry_digest": "sha256:9dfb6b7417f54d78d50e6e6bdd951b854ed8da8f5f1782f4fe563a85e1cd0b7a", + "source_image": "docker.io/swebench/swesmith.x86_64.masterminds_1776_squirrel.1ded5784@sha256:8b7a7b2f6acd11416e98a5254735925f3e354c9a85634e37a1f9a347ad82ed22", + "source_receipt_sha256": "6be66b515dc9ca98b38e89389e4b485f038418a7591cd99ca1294782042078a3", + "space_commit": "4520e0fbd0db51041911578a6d2b53e5493f8b5a", + "space_id": "harness-hub/scale800-go-055c69f17f410bee-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "be10038c0ae7275d2542b21e80f354acdfc619ed319d877ad4d74fab653e58f0", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21", + "source_proof_sha256": "3a7f471b157557c663c0216677c83c64f82f84e557eb5c5dd4eed6cea93b1e93", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc", + "cloud_launch_ready": false, + "healthy_mirror_commit": "ecf2598064d7f630d661d9a03e6cab204d37eeb8", + "instruction_sha256": "94b14160c7b1996b61a8f6e2c2ffba2554f51c4d9a456eefbe6c1ddd8a5a3211", + "is_fork": true, + "learner_path": "tasks/aab73369ea0473ac7a23c937/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "11ac92da622d8d25df663d4bc5d12f464da1a98a9fbb75930e0e65cc58b80a2f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/Masterminds__squirrel.1ded5784/fb5137d39f1e9b6fbab92c44814483a300349b61/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "1ded5784535dcffa4e175d4efbd1ca2706927758", + "patch_sha256": "da8a0460a94ef62e114fa5d08737ea68edf241f9558279732d167d4145f7bea7", + "provenance_path": "tasks/aab73369ea0473ac7a23c937/source-proof.json", + "repository_lineage": [ + "swesmith/Masterminds__squirrel.1ded5784", + "Masterminds/squirrel" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "fb5137d39f1e9b6fbab92c44814483a300349b61", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "e30bb3e97f5ae1f67fa2561db702fa3660478442", + "source_kind": "mutation", + "source_repo": "swesmith/Masterminds__squirrel.1ded5784", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc", + "task_sha256": "715f19bd47477eb4a16f55da12d875a504977bb425b8f65c7bf0ceb978c0a7c0", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "Masterminds/squirrel", + "usage": "quarantine_only" + }, + "source_row_sha256": "1ed6da7693a61b7dc6decfb3ebd1c26d8cd7b860a25d24a9479ba519f61ee607", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.travis.yml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/case.go", + "/testbed/delete.go", + "/testbed/delete_ctx.go", + "/testbed/expr.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/insert.go", + "/testbed/insert_ctx.go", + "/testbed/integration/doc.go", + "/testbed/integration/go.mod", + "/testbed/integration/go.sum", + "/testbed/part.go", + "/testbed/placeholder.go", + "/testbed/row.go", + "/testbed/select.go", + "/testbed/select_ctx.go", + "/testbed/squirrel.go", + "/testbed/squirrel_ctx.go", + "/testbed/statement.go", + "/testbed/stmtcacher.go", + "/testbed/stmtcacher_ctx.go", + "/testbed/stmtcacher_noctx.go", + "/testbed/update.go", + "/testbed/update_ctx.go", + "/testbed/where.go" + ] +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/solution/solve.sh b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..1aa3153575e85f3968382c0a1c300313eb97d8c3 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"insert_ctx.go": {"data": "Ly8gK2J1aWxkIGdvMS44CgpwYWNrYWdlIHNxdWlycmVsCgppbXBvcnQgKAoJImNvbnRleHQiCgkiZGF0YWJhc2Uvc3FsIgoKCSJnaXRodWIuY29tL2xhbm4vYnVpbGRlciIKKQoKZnVuYyAoZCAqaW5zZXJ0RGF0YSkgRXhlY0NvbnRleHQoY3R4IGNvbnRleHQuQ29udGV4dCkgKHNxbC5SZXN1bHQsIGVycm9yKSB7CglpZiBkLlJ1bldpdGggPT0gbmlsIHsKCQlyZXR1cm4gbmlsLCBSdW5uZXJOb3RTZXQKCX0KCWN0eFJ1bm5lciwgb2sgOj0gZC5SdW5XaXRoLihFeGVjZXJDb250ZXh0KQoJaWYgIW9rIHsKCQlyZXR1cm4gbmlsLCBOb0NvbnRleHRTdXBwb3J0Cgl9CglyZXR1cm4gRXhlY0NvbnRleHRXaXRoKGN0eCwgY3R4UnVubmVyLCBkKQp9CgpmdW5jIChkICppbnNlcnREYXRhKSBRdWVyeUNvbnRleHQoY3R4IGNvbnRleHQuQ29udGV4dCkgKCpzcWwuUm93cywgZXJyb3IpIHsKCWlmIGQuUnVuV2l0aCA9PSBuaWwgewoJCXJldHVybiBuaWwsIFJ1bm5lck5vdFNldAoJfQoJY3R4UnVubmVyLCBvayA6PSBkLlJ1bldpdGguKFF1ZXJ5ZXJDb250ZXh0KQoJaWYgIW9rIHsKCQlyZXR1cm4gbmlsLCBOb0NvbnRleHRTdXBwb3J0Cgl9CglyZXR1cm4gUXVlcnlDb250ZXh0V2l0aChjdHgsIGN0eFJ1bm5lciwgZCkKfQoKZnVuYyAoZCAqaW5zZXJ0RGF0YSkgUXVlcnlSb3dDb250ZXh0KGN0eCBjb250ZXh0LkNvbnRleHQpIFJvd1NjYW5uZXIgewoJaWYgZC5SdW5XaXRoID09IG5pbCB7CgkJcmV0dXJuICZSb3d7ZXJyOiBSdW5uZXJOb3RTZXR9Cgl9CglxdWVyeVJvd2VyLCBvayA6PSBkLlJ1bldpdGguKFF1ZXJ5Um93ZXJDb250ZXh0KQoJaWYgIW9rIHsKCQlpZiBfLCBvayA6PSBkLlJ1bldpdGguKFF1ZXJ5ZXJDb250ZXh0KTsgIW9rIHsKCQkJcmV0dXJuICZSb3d7ZXJyOiBSdW5uZXJOb3RRdWVyeVJ1bm5lcn0KCQl9CgkJcmV0dXJuICZSb3d7ZXJyOiBOb0NvbnRleHRTdXBwb3J0fQoJfQoJcmV0dXJuIFF1ZXJ5Um93Q29udGV4dFdpdGgoY3R4LCBxdWVyeVJvd2VyLCBkKQp9CgovLyBFeGVjQ29udGV4dCBidWlsZHMgYW5kIEV4ZWNDb250ZXh0cyB0aGUgcXVlcnkgd2l0aCB0aGUgUnVubmVyIHNldCBieSBSdW5XaXRoLgpmdW5jIChiIEluc2VydEJ1aWxkZXIpIEV4ZWNDb250ZXh0KGN0eCBjb250ZXh0LkNvbnRleHQpIChzcWwuUmVzdWx0LCBlcnJvcikgewoJZGF0YSA6PSBidWlsZGVyLkdldFN0cnVjdChiKS4oaW5zZXJ0RGF0YSkKCXJldHVybiBkYXRhLkV4ZWNDb250ZXh0KGN0eCkKfQoKLy8gUXVlcnlDb250ZXh0IGJ1aWxkcyBhbmQgUXVlcnlDb250ZXh0cyB0aGUgcXVlcnkgd2l0aCB0aGUgUnVubmVyIHNldCBieSBSdW5XaXRoLgpmdW5jIChiIEluc2VydEJ1aWxkZXIpIFF1ZXJ5Q29udGV4dChjdHggY29udGV4dC5Db250ZXh0KSAoKnNxbC5Sb3dzLCBlcnJvcikgewoJZGF0YSA6PSBidWlsZGVyLkdldFN0cnVjdChiKS4oaW5zZXJ0RGF0YSkKCXJldHVybiBkYXRhLlF1ZXJ5Q29udGV4dChjdHgpCn0KCi8vIFF1ZXJ5Um93Q29udGV4dCBidWlsZHMgYW5kIFF1ZXJ5Um93Q29udGV4dHMgdGhlIHF1ZXJ5IHdpdGggdGhlIFJ1bm5lciBzZXQgYnkgUnVuV2l0aC4KZnVuYyAoYiBJbnNlcnRCdWlsZGVyKSBRdWVyeVJvd0NvbnRleHQoY3R4IGNvbnRleHQuQ29udGV4dCkgUm93U2Nhbm5lciB7CglkYXRhIDo9IGJ1aWxkZXIuR2V0U3RydWN0KGIpLihpbnNlcnREYXRhKQoJcmV0dXJuIGRhdGEuUXVlcnlSb3dDb250ZXh0KGN0eCkKfQoKLy8gU2NhbkNvbnRleHQgaXMgYSBzaG9ydGN1dCBmb3IgUXVlcnlSb3dDb250ZXh0KCkuU2Nhbi4KZnVuYyAoYiBJbnNlcnRCdWlsZGVyKSBTY2FuQ29udGV4dChjdHggY29udGV4dC5Db250ZXh0LCBkZXN0IC4uLmludGVyZmFjZXt9KSBlcnJvciB7CglyZXR1cm4gYi5RdWVyeVJvd0NvbnRleHQoY3R4KS5TY2FuKGRlc3QuLi4pCn0K", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/task.toml b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e19a778893670fc895a74782b3cfff3c58665c90 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:40a0087e33be6d16e5326aec69979f53a57d1857fdac22b1b3621585fac79915" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/case_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/case_test.go new file mode 100644 index 0000000000000000000000000000000000000000..a2ad995cfe6d0bb71f0755c70268592ff94d8a1f --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/case_test.go @@ -0,0 +1,150 @@ +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestCaseWithVal(t *testing.T) { + caseStmt := Case("number"). + When("1", "one"). + When("2", "two"). + Else(Expr("?", "big number")) + + qb := Select(). + Column(caseStmt). + From("table") + sql, args, err := qb.ToSql() + + assert.NoError(t, err) + + expectedSql := "SELECT CASE number " + + "WHEN 1 THEN one " + + "WHEN 2 THEN two " + + "ELSE ? " + + "END " + + "FROM table" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"big number"} + assert.Equal(t, expectedArgs, args) +} + +func TestCaseWithComplexVal(t *testing.T) { + caseStmt := Case("? > ?", 10, 5). + When("true", "'T'") + + qb := Select(). + Column(Alias(caseStmt, "complexCase")). + From("table") + sql, args, err := qb.ToSql() + + assert.NoError(t, err) + + expectedSql := "SELECT (CASE ? > ? " + + "WHEN true THEN 'T' " + + "END) AS complexCase " + + "FROM table" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{10, 5} + assert.Equal(t, expectedArgs, args) +} + +func TestCaseWithNoVal(t *testing.T) { + caseStmt := Case(). + When(Eq{"x": 0}, "x is zero"). + When(Expr("x > ?", 1), Expr("CONCAT('x is greater than ', ?)", 2)) + + qb := Select().Column(caseStmt).From("table") + sql, args, err := qb.ToSql() + + assert.NoError(t, err) + + expectedSql := "SELECT CASE " + + "WHEN x = ? THEN x is zero " + + "WHEN x > ? THEN CONCAT('x is greater than ', ?) " + + "END " + + "FROM table" + + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{0, 1, 2} + assert.Equal(t, expectedArgs, args) +} + +func TestCaseWithExpr(t *testing.T) { + caseStmt := Case(Expr("x = ?", true)). + When("true", Expr("?", "it's true!")). + Else("42") + + qb := Select().Column(caseStmt).From("table") + sql, args, err := qb.ToSql() + + assert.NoError(t, err) + + expectedSql := "SELECT CASE x = ? " + + "WHEN true THEN ? " + + "ELSE 42 " + + "END " + + "FROM table" + + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{true, "it's true!"} + assert.Equal(t, expectedArgs, args) +} + +func TestMultipleCase(t *testing.T) { + caseStmtNoval := Case(Expr("x = ?", true)). + When("true", Expr("?", "it's true!")). + Else("42") + caseStmtExpr := Case(). + When(Eq{"x": 0}, "'x is zero'"). + When(Expr("x > ?", 1), Expr("CONCAT('x is greater than ', ?)", 2)) + + qb := Select(). + Column(Alias(caseStmtNoval, "case_noval")). + Column(Alias(caseStmtExpr, "case_expr")). + From("table") + + sql, args, err := qb.ToSql() + + assert.NoError(t, err) + + expectedSql := "SELECT " + + "(CASE x = ? WHEN true THEN ? ELSE 42 END) AS case_noval, " + + "(CASE WHEN x = ? THEN 'x is zero' WHEN x > ? THEN CONCAT('x is greater than ', ?) END) AS case_expr " + + "FROM table" + + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{ + true, "it's true!", + 0, 1, 2, + } + assert.Equal(t, expectedArgs, args) +} + +func TestCaseWithNoWhenClause(t *testing.T) { + caseStmt := Case("something"). + Else("42") + + qb := Select().Column(caseStmt).From("table") + + _, _, err := qb.ToSql() + + assert.Error(t, err) + + assert.Equal(t, "case expression must contain at lease one WHEN clause", err.Error()) +} + +func TestCaseBuilderMustSql(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("TestCaseBuilderMustSql should have panicked!") + } + }() + Case("").MustSql() +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/delete_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/delete_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..8a80b6ae502df4301a54a067896c7e31143ed427 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/delete_ctx_test.go @@ -0,0 +1,41 @@ +// +build go1.8 + +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestDeleteBuilderContextRunners(t *testing.T) { + db := &DBStub{} + b := Delete("test").Where("x = ?", 1).RunWith(db) + + expectedSql := "DELETE FROM test WHERE x = ?" + + b.ExecContext(ctx) + assert.Equal(t, expectedSql, db.LastExecSql) + + b.QueryContext(ctx) + assert.Equal(t, expectedSql, db.LastQuerySql) + + b.QueryRowContext(ctx) + assert.Equal(t, expectedSql, db.LastQueryRowSql) + + err := b.ScanContext(ctx) + assert.NoError(t, err) +} + +func TestDeleteBuilderContextNoRunner(t *testing.T) { + b := Delete("test").Where("x != ?", 0).Suffix("RETURNING x") + + _, err := b.ExecContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + _, err = b.QueryContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + err = b.ScanContext(ctx) + assert.Equal(t, RunnerNotSet, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/delete_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/delete_test.go new file mode 100644 index 0000000000000000000000000000000000000000..62691f246f11a751ec289bb34ad80bbca2d47313 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/delete_test.go @@ -0,0 +1,81 @@ +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestDeleteBuilderToSql(t *testing.T) { + b := Delete(""). + Prefix("WITH prefix AS ?", 0). + From("a"). + Where("b = ?", 1). + OrderBy("c"). + Limit(2). + Offset(3). + Suffix("RETURNING ?", 4) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := + "WITH prefix AS ? " + + "DELETE FROM a WHERE b = ? ORDER BY c LIMIT 2 OFFSET 3 " + + "RETURNING ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{0, 1, 4} + assert.Equal(t, expectedArgs, args) +} + +func TestDeleteBuilderToSqlErr(t *testing.T) { + _, _, err := Delete("").ToSql() + assert.Error(t, err) +} + +func TestDeleteBuilderMustSql(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("TestDeleteBuilderMustSql should have panicked!") + } + }() + Delete("").MustSql() +} + +func TestDeleteBuilderPlaceholders(t *testing.T) { + b := Delete("test").Where("x = ? AND y = ?", 1, 2) + + sql, _, _ := b.PlaceholderFormat(Question).ToSql() + assert.Equal(t, "DELETE FROM test WHERE x = ? AND y = ?", sql) + + sql, _, _ = b.PlaceholderFormat(Dollar).ToSql() + assert.Equal(t, "DELETE FROM test WHERE x = $1 AND y = $2", sql) +} + +func TestDeleteBuilderRunners(t *testing.T) { + db := &DBStub{} + b := Delete("test").Where("x = ?", 1).RunWith(db) + + expectedSql := "DELETE FROM test WHERE x = ?" + + b.Exec() + assert.Equal(t, expectedSql, db.LastExecSql) +} + +func TestDeleteBuilderNoRunner(t *testing.T) { + b := Delete("test") + + _, err := b.Exec() + assert.Equal(t, RunnerNotSet, err) +} + +func TestDeleteWithQuery(t *testing.T) { + db := &DBStub{} + b := Delete("test").Where("id=55").Suffix("RETURNING path").RunWith(db) + + expectedSql := "DELETE FROM test WHERE id=55 RETURNING path" + b.Query() + + assert.Equal(t, expectedSql, db.LastQuerySql) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/expr_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/expr_test.go new file mode 100644 index 0000000000000000000000000000000000000000..60d2ae5cc3020d0d40b10e3b3042114fbac6ffb4 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/expr_test.go @@ -0,0 +1,464 @@ +package squirrel + +import ( + "database/sql" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestConcatExpr(t *testing.T) { + b := ConcatExpr("COALESCE(name,", Expr("CONCAT(?,' ',?)", "f", "l"), ")") + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "COALESCE(name,CONCAT(?,' ',?))" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"f", "l"} + assert.Equal(t, expectedArgs, args) +} + +func TestConcatExprBadType(t *testing.T) { + b := ConcatExpr("prefix", 123, "suffix") + _, _, err := b.ToSql() + assert.Error(t, err) + assert.Contains(t, err.Error(), "123 is not") +} + +func TestEqToSql(t *testing.T) { + b := Eq{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id = ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestEqEmptyToSql(t *testing.T) { + sql, args, err := Eq{}.ToSql() + assert.NoError(t, err) + + expectedSql := "(1=1)" + assert.Equal(t, expectedSql, sql) + assert.Empty(t, args) +} + +func TestEqInToSql(t *testing.T) { + b := Eq{"id": []int{1, 2, 3}} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id IN (?,?,?)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2, 3} + assert.Equal(t, expectedArgs, args) +} + +func TestNotEqToSql(t *testing.T) { + b := NotEq{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id <> ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestEqNotInToSql(t *testing.T) { + b := NotEq{"id": []int{1, 2, 3}} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id NOT IN (?,?,?)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2, 3} + assert.Equal(t, expectedArgs, args) +} + +func TestEqInEmptyToSql(t *testing.T) { + b := Eq{"id": []int{}} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "(1=0)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{} + assert.Equal(t, expectedArgs, args) +} + +func TestNotEqInEmptyToSql(t *testing.T) { + b := NotEq{"id": []int{}} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "(1=1)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{} + assert.Equal(t, expectedArgs, args) +} + +func TestEqBytesToSql(t *testing.T) { + b := Eq{"id": []byte("test")} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id = ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{[]byte("test")} + assert.Equal(t, expectedArgs, args) +} + +func TestLtToSql(t *testing.T) { + b := Lt{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id < ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestLtOrEqToSql(t *testing.T) { + b := LtOrEq{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id <= ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestGtToSql(t *testing.T) { + b := Gt{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id > ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestGtOrEqToSql(t *testing.T) { + b := GtOrEq{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id >= ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestExprNilToSql(t *testing.T) { + var b Sqlizer + b = NotEq{"name": nil} + sql, args, err := b.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + + expectedSql := "name IS NOT NULL" + assert.Equal(t, expectedSql, sql) + + b = Eq{"name": nil} + sql, args, err = b.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + + expectedSql = "name IS NULL" + assert.Equal(t, expectedSql, sql) +} + +func TestNullTypeString(t *testing.T) { + var b Sqlizer + var name sql.NullString + + b = Eq{"name": name} + sql, args, err := b.ToSql() + + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "name IS NULL", sql) + + name.Scan("Name") + b = Eq{"name": name} + sql, args, err = b.ToSql() + + assert.NoError(t, err) + assert.Equal(t, []interface{}{"Name"}, args) + assert.Equal(t, "name = ?", sql) +} + +func TestNullTypeInt64(t *testing.T) { + var userID sql.NullInt64 + userID.Scan(nil) + b := Eq{"user_id": userID} + sql, args, err := b.ToSql() + + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "user_id IS NULL", sql) + + userID.Scan(int64(10)) + b = Eq{"user_id": userID} + sql, args, err = b.ToSql() + + assert.NoError(t, err) + assert.Equal(t, []interface{}{int64(10)}, args) + assert.Equal(t, "user_id = ?", sql) +} + +func TestNilPointer(t *testing.T) { + var name *string = nil + eq := Eq{"name": name} + sql, args, err := eq.ToSql() + + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "name IS NULL", sql) + + neq := NotEq{"name": name} + sql, args, err = neq.ToSql() + + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "name IS NOT NULL", sql) + + var ids *[]int = nil + eq = Eq{"id": ids} + sql, args, err = eq.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "id IS NULL", sql) + + neq = NotEq{"id": ids} + sql, args, err = neq.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "id IS NOT NULL", sql) + + var ida *[3]int = nil + eq = Eq{"id": ida} + sql, args, err = eq.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "id IS NULL", sql) + + neq = NotEq{"id": ida} + sql, args, err = neq.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "id IS NOT NULL", sql) + +} + +func TestNotNilPointer(t *testing.T) { + c := "Name" + name := &c + eq := Eq{"name": name} + sql, args, err := eq.ToSql() + + assert.NoError(t, err) + assert.Equal(t, []interface{}{"Name"}, args) + assert.Equal(t, "name = ?", sql) + + neq := NotEq{"name": name} + sql, args, err = neq.ToSql() + + assert.NoError(t, err) + assert.Equal(t, []interface{}{"Name"}, args) + assert.Equal(t, "name <> ?", sql) + + s := []int{1, 2, 3} + ids := &s + eq = Eq{"id": ids} + sql, args, err = eq.ToSql() + assert.NoError(t, err) + assert.Equal(t, []interface{}{1, 2, 3}, args) + assert.Equal(t, "id IN (?,?,?)", sql) + + neq = NotEq{"id": ids} + sql, args, err = neq.ToSql() + assert.NoError(t, err) + assert.Equal(t, []interface{}{1, 2, 3}, args) + assert.Equal(t, "id NOT IN (?,?,?)", sql) + + a := [3]int{1, 2, 3} + ida := &a + eq = Eq{"id": ida} + sql, args, err = eq.ToSql() + assert.NoError(t, err) + assert.Equal(t, []interface{}{1, 2, 3}, args) + assert.Equal(t, "id IN (?,?,?)", sql) + + neq = NotEq{"id": ida} + sql, args, err = neq.ToSql() + assert.NoError(t, err) + assert.Equal(t, []interface{}{1, 2, 3}, args) + assert.Equal(t, "id NOT IN (?,?,?)", sql) +} + +func TestEmptyAndToSql(t *testing.T) { + sql, args, err := And{}.ToSql() + assert.NoError(t, err) + + expectedSql := "(1=1)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{} + assert.Equal(t, expectedArgs, args) +} + +func TestEmptyOrToSql(t *testing.T) { + sql, args, err := Or{}.ToSql() + assert.NoError(t, err) + + expectedSql := "(1=0)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{} + assert.Equal(t, expectedArgs, args) +} + +func TestLikeToSql(t *testing.T) { + b := Like{"name": "%irrel"} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "name LIKE ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"%irrel"} + assert.Equal(t, expectedArgs, args) +} + +func TestNotLikeToSql(t *testing.T) { + b := NotLike{"name": "%irrel"} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "name NOT LIKE ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"%irrel"} + assert.Equal(t, expectedArgs, args) +} + +func TestILikeToSql(t *testing.T) { + b := ILike{"name": "sq%"} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "name ILIKE ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"sq%"} + assert.Equal(t, expectedArgs, args) +} + +func TestNotILikeToSql(t *testing.T) { + b := NotILike{"name": "sq%"} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "name NOT ILIKE ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"sq%"} + assert.Equal(t, expectedArgs, args) +} + +func TestSqlEqOrder(t *testing.T) { + b := Eq{"a": 1, "b": 2, "c": 3} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "a = ? AND b = ? AND c = ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2, 3} + assert.Equal(t, expectedArgs, args) +} + +func TestSqlLtOrder(t *testing.T) { + b := Lt{"a": 1, "b": 2, "c": 3} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "a < ? AND b < ? AND c < ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2, 3} + assert.Equal(t, expectedArgs, args) +} + +func TestExprEscaped(t *testing.T) { + b := Expr("count(??)", Expr("x")) + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "count(??)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{Expr("x")} + assert.Equal(t, expectedArgs, args) +} + +func TestExprRecursion(t *testing.T) { + { + b := Expr("count(?)", Expr("nullif(a,?)", "b")) + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "count(nullif(a,?))" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"b"} + assert.Equal(t, expectedArgs, args) + } + { + b := Expr("extract(? from ?)", Expr("epoch"), "2001-02-03") + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "extract(epoch from ?)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"2001-02-03"} + assert.Equal(t, expectedArgs, args) + } + { + b := Expr("JOIN t1 ON ?", And{Eq{"id": 1}, Expr("NOT c1"), Expr("? @@ ?", "x", "y")}) + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "JOIN t1 ON (id = ? AND NOT c1 AND ? @@ ?)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, "x", "y"} + assert.Equal(t, expectedArgs, args) + } +} + +func ExampleEq() { + Select("id", "created", "first_name").From("users").Where(Eq{ + "company": 20, + }) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/insert_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/insert_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..0e02ed476e05a35a22e8d298fbf53c3ca4fed0d7 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/insert_ctx_test.go @@ -0,0 +1,41 @@ +// +build go1.8 + +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestInsertBuilderContextRunners(t *testing.T) { + db := &DBStub{} + b := Insert("test").Values(1).RunWith(db) + + expectedSql := "INSERT INTO test VALUES (?)" + + b.ExecContext(ctx) + assert.Equal(t, expectedSql, db.LastExecSql) + + b.QueryContext(ctx) + assert.Equal(t, expectedSql, db.LastQuerySql) + + b.QueryRowContext(ctx) + assert.Equal(t, expectedSql, db.LastQueryRowSql) + + err := b.ScanContext(ctx) + assert.NoError(t, err) +} + +func TestInsertBuilderContextNoRunner(t *testing.T) { + b := Insert("test").Values(1) + + _, err := b.ExecContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + _, err = b.QueryContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + err = b.ScanContext(ctx) + assert.Equal(t, RunnerNotSet, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/insert_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/insert_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ced2313547fd37c5f23fc815a4394e6d8b61f197 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/insert_test.go @@ -0,0 +1,112 @@ +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestInsertBuilderToSql(t *testing.T) { + b := Insert(""). + Prefix("WITH prefix AS ?", 0). + Into("a"). + Options("DELAYED", "IGNORE"). + Columns("b", "c"). + Values(1, 2). + Values(3, Expr("? + 1", 4)). + Suffix("RETURNING ?", 5) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSQL := + "WITH prefix AS ? " + + "INSERT DELAYED IGNORE INTO a (b,c) VALUES (?,?),(?,? + 1) " + + "RETURNING ?" + assert.Equal(t, expectedSQL, sql) + + expectedArgs := []interface{}{0, 1, 2, 3, 4, 5} + assert.Equal(t, expectedArgs, args) +} + +func TestInsertBuilderToSqlErr(t *testing.T) { + _, _, err := Insert("").Values(1).ToSql() + assert.Error(t, err) + + _, _, err = Insert("x").ToSql() + assert.Error(t, err) +} + +func TestInsertBuilderMustSql(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("TestInsertBuilderMustSql should have panicked!") + } + }() + Insert("").MustSql() +} + +func TestInsertBuilderPlaceholders(t *testing.T) { + b := Insert("test").Values(1, 2) + + sql, _, _ := b.PlaceholderFormat(Question).ToSql() + assert.Equal(t, "INSERT INTO test VALUES (?,?)", sql) + + sql, _, _ = b.PlaceholderFormat(Dollar).ToSql() + assert.Equal(t, "INSERT INTO test VALUES ($1,$2)", sql) +} + +func TestInsertBuilderRunners(t *testing.T) { + db := &DBStub{} + b := Insert("test").Values(1).RunWith(db) + + expectedSQL := "INSERT INTO test VALUES (?)" + + b.Exec() + assert.Equal(t, expectedSQL, db.LastExecSql) +} + +func TestInsertBuilderNoRunner(t *testing.T) { + b := Insert("test").Values(1) + + _, err := b.Exec() + assert.Equal(t, RunnerNotSet, err) +} + +func TestInsertBuilderSetMap(t *testing.T) { + b := Insert("table").SetMap(Eq{"field1": 1, "field2": 2, "field3": 3}) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSQL := "INSERT INTO table (field1,field2,field3) VALUES (?,?,?)" + assert.Equal(t, expectedSQL, sql) + + expectedArgs := []interface{}{1, 2, 3} + assert.Equal(t, expectedArgs, args) +} + +func TestInsertBuilderSelect(t *testing.T) { + sb := Select("field1").From("table1").Where(Eq{"field1": 1}) + ib := Insert("table2").Columns("field1").Select(sb) + + sql, args, err := ib.ToSql() + assert.NoError(t, err) + + expectedSQL := "INSERT INTO table2 (field1) SELECT field1 FROM table1 WHERE field1 = ?" + assert.Equal(t, expectedSQL, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestInsertBuilderReplace(t *testing.T) { + b := Replace("table").Values(1) + + expectedSQL := "REPLACE INTO table VALUES (?)" + + sql, _, err := b.ToSql() + assert.NoError(t, err) + + assert.Equal(t, expectedSQL, sql) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/integration/integration_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/integration/integration_test.go new file mode 100644 index 0000000000000000000000000000000000000000..e861e7f6f36595633e7ce3bc0495283aa417dc52 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/integration/integration_test.go @@ -0,0 +1,135 @@ +package integration + +import ( + "context" + "database/sql" + "flag" + "fmt" + "os" + "testing" + + "github.com/stretchr/testify/assert" + + sqrl "github.com/Masterminds/squirrel" + + _ "github.com/go-sql-driver/mysql" + _ "github.com/lib/pq" + _ "github.com/mattn/go-sqlite3" +) + +const ( + testSchema = ` + CREATE TABLE squirrel_integration ( k INT, v TEXT )` + testData = ` + INSERT INTO squirrel_integration VALUES + (1, 'foo'), + (3, 'bar'), + (2, 'foo'), + (4, 'baz') + ` +) + +var ( + sb sqrl.StatementBuilderType +) + +func TestMain(m *testing.M) { + var driver, dataSource string + flag.StringVar(&driver, "driver", "", "integration database driver") + flag.StringVar(&dataSource, "dataSource", "", "integration database data source") + flag.Parse() + + if driver == "" { + driver = "sqlite3" + } + + if driver == "sqlite3" && dataSource == "" { + dataSource = ":memory:" + } + + db, err := sql.Open(driver, dataSource) + if err != nil { + fmt.Printf("error opening database: %v\n", err) + os.Exit(-1) + } + + _, err = db.Exec(testSchema) + if err != nil { + fmt.Printf("error creating test schema: %v\n", err) + os.Exit(-2) + } + + defer func() { + _, err = db.Exec("DROP TABLE squirrel_integration") + fmt.Printf("error removing test schema: %v\n", err) + }() + + _, err = db.Exec(testData) + if err != nil { + fmt.Printf("error inserting test data: %v\n", err) + os.Exit(-3) + } + + sb = sqrl.StatementBuilder.RunWith(db) + + if driver == "postgres" { + sb = sb.PlaceholderFormat(sqrl.Dollar) + } + + os.Exit(m.Run()) +} + +func assertVals(t *testing.T, s sqrl.SelectBuilder, expected ...string) { + rows, err := s.Query() + assert.NoError(t, err) + defer rows.Close() + + vals := make([]string, len(expected)) + for i := range vals { + assert.True(t, rows.Next()) + assert.NoError(t, rows.Scan(&vals[i])) + } + assert.False(t, rows.Next()) + + if expected != nil { + assert.Equal(t, expected, vals) + } +} + +func TestSimpleSelect(t *testing.T) { + assertVals( + t, + sb.Select("v").From("squirrel_integration"), + "foo", "bar", "foo", "baz") +} + +func TestEq(t *testing.T) { + s := sb.Select("v").From("squirrel_integration") + assertVals(t, s.Where(sqrl.Eq{"k": 4}), "baz") + assertVals(t, s.Where(sqrl.NotEq{"k": 2}), "foo", "bar", "baz") + assertVals(t, s.Where(sqrl.Eq{"k": []int{1, 4}}), "foo", "baz") + assertVals(t, s.Where(sqrl.NotEq{"k": []int{1, 4}}), "bar", "foo") + assertVals(t, s.Where(sqrl.Eq{"k": nil})) + assertVals(t, s.Where(sqrl.NotEq{"k": nil}), "foo", "bar", "foo", "baz") + assertVals(t, s.Where(sqrl.Eq{"k": []int{}})) + assertVals(t, s.Where(sqrl.NotEq{"k": []int{}}), "foo", "bar", "foo", "baz") +} + +func TestIneq(t *testing.T) { + s := sb.Select("v").From("squirrel_integration") + assertVals(t, s.Where(sqrl.Lt{"k": 3}), "foo", "foo") + assertVals(t, s.Where(sqrl.Gt{"k": 3}), "baz") +} + +func TestConj(t *testing.T) { + s := sb.Select("v").From("squirrel_integration") + assertVals(t, s.Where(sqrl.And{sqrl.Gt{"k": 1}, sqrl.Lt{"k": 4}}), "bar", "foo") + assertVals(t, s.Where(sqrl.Or{sqrl.Gt{"k": 3}, sqrl.Lt{"k": 2}}), "foo", "baz") +} + +func TestContext(t *testing.T) { + s := sb.Select("v").From("squirrel_integration") + ctx := context.Background() + _, err := s.QueryContext(ctx) + assert.NoError(t, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/placeholder_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/placeholder_test.go new file mode 100644 index 0000000000000000000000000000000000000000..8e7f43f4929409739603e5c61bd74be940f016b5 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/placeholder_test.go @@ -0,0 +1,67 @@ +package squirrel + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestQuestion(t *testing.T) { + sql := "x = ? AND y = ?" + s, _ := Question.ReplacePlaceholders(sql) + assert.Equal(t, sql, s) +} + +func TestDollar(t *testing.T) { + sql := "x = ? AND y = ?" + s, _ := Dollar.ReplacePlaceholders(sql) + assert.Equal(t, "x = $1 AND y = $2", s) +} + +func TestColon(t *testing.T) { + sql := "x = ? AND y = ?" + s, _ := Colon.ReplacePlaceholders(sql) + assert.Equal(t, "x = :1 AND y = :2", s) +} + +func TestAtp(t *testing.T) { + sql := "x = ? AND y = ?" + s, _ := AtP.ReplacePlaceholders(sql) + assert.Equal(t, "x = @p1 AND y = @p2", s) +} + +func TestPlaceholders(t *testing.T) { + assert.Equal(t, Placeholders(2), "?,?") +} + +func TestEscapeDollar(t *testing.T) { + sql := "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ??| array['?'] AND enabled = ?" + s, _ := Dollar.ReplacePlaceholders(sql) + assert.Equal(t, "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ?| array['$1'] AND enabled = $2", s) +} + +func TestEscapeColon(t *testing.T) { + sql := "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ??| array['?'] AND enabled = ?" + s, _ := Colon.ReplacePlaceholders(sql) + assert.Equal(t, "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ?| array[':1'] AND enabled = :2", s) +} + +func TestEscapeAtp(t *testing.T) { + sql := "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ??| array['?'] AND enabled = ?" + s, _ := AtP.ReplacePlaceholders(sql) + assert.Equal(t, "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ?| array['@p1'] AND enabled = @p2", s) +} + +func BenchmarkPlaceholdersArray(b *testing.B) { + var count = b.N + placeholders := make([]string, count) + for i := 0; i < count; i++ { + placeholders[i] = "?" + } + var _ = strings.Join(placeholders, ",") +} + +func BenchmarkPlaceholdersStrings(b *testing.B) { + Placeholders(b.N) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/row_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/row_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ebeeb85485799fc47480555357873b4c4656c1c0 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/row_test.go @@ -0,0 +1,34 @@ +package squirrel + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" +) + +type RowStub struct { + Scanned bool +} + +func (r *RowStub) Scan(_ ...interface{}) error { + r.Scanned = true + return nil +} + +func TestRowScan(t *testing.T) { + stub := &RowStub{} + row := &Row{RowScanner: stub} + err := row.Scan() + assert.True(t, stub.Scanned, "row was not scanned") + assert.NoError(t, err) +} + +func TestRowScanErr(t *testing.T) { + stub := &RowStub{} + rowErr := fmt.Errorf("scan err") + row := &Row{RowScanner: stub, err: rowErr} + err := row.Scan() + assert.False(t, stub.Scanned, "row was scanned") + assert.Equal(t, rowErr, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/select_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/select_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b36ae44285e9ced8b14376ef6b060325370137d0 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/select_ctx_test.go @@ -0,0 +1,41 @@ +// +build go1.8 + +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestSelectBuilderContextRunners(t *testing.T) { + db := &DBStub{} + b := Select("test").RunWith(db) + + expectedSql := "SELECT test" + + b.ExecContext(ctx) + assert.Equal(t, expectedSql, db.LastExecSql) + + b.QueryContext(ctx) + assert.Equal(t, expectedSql, db.LastQuerySql) + + b.QueryRowContext(ctx) + assert.Equal(t, expectedSql, db.LastQueryRowSql) + + err := b.ScanContext(ctx) + assert.NoError(t, err) +} + +func TestSelectBuilderContextNoRunner(t *testing.T) { + b := Select("test") + + _, err := b.ExecContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + _, err = b.QueryContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + err = b.ScanContext(ctx) + assert.Equal(t, RunnerNotSet, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/select_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/select_test.go new file mode 100644 index 0000000000000000000000000000000000000000..80161bf5a947cbb02b3039b857b71563630f2ad0 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/select_test.go @@ -0,0 +1,463 @@ +package squirrel + +import ( + "database/sql" + "fmt" + "log" + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +func TestSelectBuilderToSql(t *testing.T) { + subQ := Select("aa", "bb").From("dd") + b := Select("a", "b"). + Prefix("WITH prefix AS ?", 0). + Distinct(). + Columns("c"). + Column("IF(d IN ("+Placeholders(3)+"), 1, 0) as stat_column", 1, 2, 3). + Column(Expr("a > ?", 100)). + Column(Alias(Eq{"b": []int{101, 102, 103}}, "b_alias")). + Column(Alias(subQ, "subq")). + From("e"). + JoinClause("CROSS JOIN j1"). + Join("j2"). + LeftJoin("j3"). + RightJoin("j4"). + InnerJoin("j5"). + CrossJoin("j6"). + Where("f = ?", 4). + Where(Eq{"g": 5}). + Where(map[string]interface{}{"h": 6}). + Where(Eq{"i": []int{7, 8, 9}}). + Where(Or{Expr("j = ?", 10), And{Eq{"k": 11}, Expr("true")}}). + GroupBy("l"). + Having("m = n"). + OrderByClause("? DESC", 1). + OrderBy("o ASC", "p DESC"). + Limit(12). + Offset(13). + Suffix("FETCH FIRST ? ROWS ONLY", 14) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := + "WITH prefix AS ? " + + "SELECT DISTINCT a, b, c, IF(d IN (?,?,?), 1, 0) as stat_column, a > ?, " + + "(b IN (?,?,?)) AS b_alias, " + + "(SELECT aa, bb FROM dd) AS subq " + + "FROM e " + + "CROSS JOIN j1 JOIN j2 LEFT JOIN j3 RIGHT JOIN j4 INNER JOIN j5 CROSS JOIN j6 " + + "WHERE f = ? AND g = ? AND h = ? AND i IN (?,?,?) AND (j = ? OR (k = ? AND true)) " + + "GROUP BY l HAVING m = n ORDER BY ? DESC, o ASC, p DESC LIMIT 12 OFFSET 13 " + + "FETCH FIRST ? ROWS ONLY" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{0, 1, 2, 3, 100, 101, 102, 103, 4, 5, 6, 7, 8, 9, 10, 11, 1, 14} + assert.Equal(t, expectedArgs, args) +} + +func TestSelectBuilderFromSelect(t *testing.T) { + subQ := Select("c").From("d").Where(Eq{"i": 0}) + b := Select("a", "b").FromSelect(subQ, "subq") + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "SELECT a, b FROM (SELECT c FROM d WHERE i = ?) AS subq" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{0} + assert.Equal(t, expectedArgs, args) +} + +func TestSelectBuilderFromSelectNestedDollarPlaceholders(t *testing.T) { + subQ := Select("c"). + From("t"). + Where(Gt{"c": 1}). + PlaceholderFormat(Dollar) + b := Select("c"). + FromSelect(subQ, "subq"). + Where(Lt{"c": 2}). + PlaceholderFormat(Dollar) + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "SELECT c FROM (SELECT c FROM t WHERE c > $1) AS subq WHERE c < $2" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2} + assert.Equal(t, expectedArgs, args) +} + +func TestSelectBuilderToSqlErr(t *testing.T) { + _, _, err := Select().From("x").ToSql() + assert.Error(t, err) +} + +func TestSelectBuilderPlaceholders(t *testing.T) { + b := Select("test").Where("x = ? AND y = ?") + + sql, _, _ := b.PlaceholderFormat(Question).ToSql() + assert.Equal(t, "SELECT test WHERE x = ? AND y = ?", sql) + + sql, _, _ = b.PlaceholderFormat(Dollar).ToSql() + assert.Equal(t, "SELECT test WHERE x = $1 AND y = $2", sql) + + sql, _, _ = b.PlaceholderFormat(Colon).ToSql() + assert.Equal(t, "SELECT test WHERE x = :1 AND y = :2", sql) + + sql, _, _ = b.PlaceholderFormat(AtP).ToSql() + assert.Equal(t, "SELECT test WHERE x = @p1 AND y = @p2", sql) +} + +func TestSelectBuilderRunners(t *testing.T) { + db := &DBStub{} + b := Select("test").RunWith(db) + + expectedSql := "SELECT test" + + b.Exec() + assert.Equal(t, expectedSql, db.LastExecSql) + + b.Query() + assert.Equal(t, expectedSql, db.LastQuerySql) + + b.QueryRow() + assert.Equal(t, expectedSql, db.LastQueryRowSql) + + err := b.Scan() + assert.NoError(t, err) +} + +func TestSelectBuilderNoRunner(t *testing.T) { + b := Select("test") + + _, err := b.Exec() + assert.Equal(t, RunnerNotSet, err) + + _, err = b.Query() + assert.Equal(t, RunnerNotSet, err) + + err = b.Scan() + assert.Equal(t, RunnerNotSet, err) +} + +func TestSelectBuilderSimpleJoin(t *testing.T) { + + expectedSql := "SELECT * FROM bar JOIN baz ON bar.foo = baz.foo" + expectedArgs := []interface{}(nil) + + b := Select("*").From("bar").Join("baz ON bar.foo = baz.foo") + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + assert.Equal(t, expectedSql, sql) + assert.Equal(t, args, expectedArgs) +} + +func TestSelectBuilderParamJoin(t *testing.T) { + + expectedSql := "SELECT * FROM bar JOIN baz ON bar.foo = baz.foo AND baz.foo = ?" + expectedArgs := []interface{}{42} + + b := Select("*").From("bar").Join("baz ON bar.foo = baz.foo AND baz.foo = ?", 42) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + assert.Equal(t, expectedSql, sql) + assert.Equal(t, args, expectedArgs) +} + +func TestSelectBuilderNestedSelectJoin(t *testing.T) { + + expectedSql := "SELECT * FROM bar JOIN ( SELECT * FROM baz WHERE foo = ? ) r ON bar.foo = r.foo" + expectedArgs := []interface{}{42} + + nestedSelect := Select("*").From("baz").Where("foo = ?", 42) + + b := Select("*").From("bar").JoinClause(nestedSelect.Prefix("JOIN (").Suffix(") r ON bar.foo = r.foo")) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + assert.Equal(t, expectedSql, sql) + assert.Equal(t, args, expectedArgs) +} + +func TestSelectWithOptions(t *testing.T) { + sql, _, err := Select("*").From("foo").Distinct().Options("SQL_NO_CACHE").ToSql() + + assert.NoError(t, err) + assert.Equal(t, "SELECT DISTINCT SQL_NO_CACHE * FROM foo", sql) +} + +func TestSelectWithRemoveLimit(t *testing.T) { + sql, _, err := Select("*").From("foo").Limit(10).RemoveLimit().ToSql() + + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM foo", sql) +} + +func TestSelectWithRemoveOffset(t *testing.T) { + sql, _, err := Select("*").From("foo").Offset(10).RemoveOffset().ToSql() + + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM foo", sql) +} + +func TestSelectBuilderNestedSelectDollar(t *testing.T) { + nestedBuilder := StatementBuilder.PlaceholderFormat(Dollar).Select("*").Prefix("NOT EXISTS ("). + From("bar").Where("y = ?", 42).Suffix(")") + outerSql, _, err := StatementBuilder.PlaceholderFormat(Dollar).Select("*"). + From("foo").Where("x = ?").Where(nestedBuilder).ToSql() + + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM foo WHERE x = $1 AND NOT EXISTS ( SELECT * FROM bar WHERE y = $2 )", outerSql) +} + +func TestSelectBuilderMustSql(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("TestSelectBuilderMustSql should have panicked!") + } + }() + // This function should cause a panic + Select().From("foo").MustSql() +} + +func TestSelectWithoutWhereClause(t *testing.T) { + sql, _, err := Select("*").From("users").ToSql() + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM users", sql) +} + +func TestSelectWithNilWhereClause(t *testing.T) { + sql, _, err := Select("*").From("users").Where(nil).ToSql() + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM users", sql) +} + +func TestSelectWithEmptyStringWhereClause(t *testing.T) { + sql, _, err := Select("*").From("users").Where("").ToSql() + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM users", sql) +} + +func TestSelectSubqueryPlaceholderNumbering(t *testing.T) { + subquery := Select("a").Where("b = ?", 1).PlaceholderFormat(Dollar) + with := subquery.Prefix("WITH a AS (").Suffix(")") + + sql, args, err := Select("*"). + PrefixExpr(with). + FromSelect(subquery, "q"). + Where("c = ?", 2). + PlaceholderFormat(Dollar). + ToSql() + assert.NoError(t, err) + + expectedSql := "WITH a AS ( SELECT a WHERE b = $1 ) SELECT * FROM (SELECT a WHERE b = $2) AS q WHERE c = $3" + assert.Equal(t, expectedSql, sql) + assert.Equal(t, []interface{}{1, 1, 2}, args) +} + +func TestSelectSubqueryInConjunctionPlaceholderNumbering(t *testing.T) { + subquery := Select("a").Where(Eq{"b": 1}).Prefix("EXISTS(").Suffix(")").PlaceholderFormat(Dollar) + + sql, args, err := Select("*"). + Where(Or{subquery}). + Where("c = ?", 2). + PlaceholderFormat(Dollar). + ToSql() + assert.NoError(t, err) + + expectedSql := "SELECT * WHERE (EXISTS( SELECT a WHERE b = $1 )) AND c = $2" + assert.Equal(t, expectedSql, sql) + assert.Equal(t, []interface{}{1, 2}, args) +} + +func TestSelectJoinClausePlaceholderNumbering(t *testing.T) { + subquery := Select("a").Where(Eq{"b": 2}).PlaceholderFormat(Dollar) + + sql, args, err := Select("t1.a"). + From("t1"). + Where(Eq{"a": 1}). + JoinClause(subquery.Prefix("JOIN (").Suffix(") t2 ON (t1.a = t2.a)")). + PlaceholderFormat(Dollar). + ToSql() + assert.NoError(t, err) + + expectedSql := "SELECT t1.a FROM t1 JOIN ( SELECT a WHERE b = $1 ) t2 ON (t1.a = t2.a) WHERE a = $2" + assert.Equal(t, expectedSql, sql) + assert.Equal(t, []interface{}{2, 1}, args) +} + +func ExampleSelect() { + Select("id", "created", "first_name").From("users") // ... continue building up your query + + // sql methods in select columns are ok + Select("first_name", "count(*)").From("users") + + // column aliases are ok too + Select("first_name", "count(*) as n_users").From("users") +} + +func ExampleSelectBuilder_From() { + Select("id", "created", "first_name").From("users") // ... continue building up your query +} + +func ExampleSelectBuilder_Where() { + companyId := 20 + Select("id", "created", "first_name").From("users").Where("company = ?", companyId) +} + +func ExampleSelectBuilder_Where_helpers() { + companyId := 20 + + Select("id", "created", "first_name").From("users").Where(Eq{ + "company": companyId, + }) + + Select("id", "created", "first_name").From("users").Where(GtOrEq{ + "created": time.Now().AddDate(0, 0, -7), + }) + + Select("id", "created", "first_name").From("users").Where(And{ + GtOrEq{ + "created": time.Now().AddDate(0, 0, -7), + }, + Eq{ + "company": companyId, + }, + }) +} + +func ExampleSelectBuilder_Where_multiple() { + companyId := 20 + + // multiple where's are ok + + Select("id", "created", "first_name"). + From("users"). + Where("company = ?", companyId). + Where(GtOrEq{ + "created": time.Now().AddDate(0, 0, -7), + }) +} + +func ExampleSelectBuilder_FromSelect() { + usersByCompany := Select("company", "count(*) as n_users").From("users").GroupBy("company") + query := Select("company.id", "company.name", "users_by_company.n_users"). + FromSelect(usersByCompany, "users_by_company"). + Join("company on company.id = users_by_company.company") + + sql, _, _ := query.ToSql() + fmt.Println(sql) + + // Output: SELECT company.id, company.name, users_by_company.n_users FROM (SELECT company, count(*) as n_users FROM users GROUP BY company) AS users_by_company JOIN company on company.id = users_by_company.company +} + +func ExampleSelectBuilder_Columns() { + query := Select("id").Columns("created", "first_name").From("users") + + sql, _, _ := query.ToSql() + fmt.Println(sql) + // Output: SELECT id, created, first_name FROM users +} + +func ExampleSelectBuilder_Columns_order() { + // out of order is ok too + query := Select("id").Columns("created").From("users").Columns("first_name") + + sql, _, _ := query.ToSql() + fmt.Println(sql) + // Output: SELECT id, created, first_name FROM users +} + +func ExampleSelectBuilder_Scan() { + + var db *sql.DB + + query := Select("id", "created", "first_name").From("users") + query = query.RunWith(db) + + var id int + var created time.Time + var firstName string + + if err := query.Scan(&id, &created, &firstName); err != nil { + log.Println(err) + return + } +} + +func ExampleSelectBuilder_ScanContext() { + + var db *sql.DB + + query := Select("id", "created", "first_name").From("users") + query = query.RunWith(db) + + var id int + var created time.Time + var firstName string + + if err := query.ScanContext(ctx, &id, &created, &firstName); err != nil { + log.Println(err) + return + } +} + +func ExampleSelectBuilder_RunWith() { + + var db *sql.DB + + query := Select("id", "created", "first_name").From("users").RunWith(db) + + var id int + var created time.Time + var firstName string + + if err := query.Scan(&id, &created, &firstName); err != nil { + log.Println(err) + return + } +} + +func ExampleSelectBuilder_ToSql() { + + var db *sql.DB + + query := Select("id", "created", "first_name").From("users") + + sql, args, err := query.ToSql() + if err != nil { + log.Println(err) + return + } + + rows, err := db.Query(sql, args...) + if err != nil { + log.Println(err) + return + } + + defer rows.Close() + + for rows.Next() { + // scan... + } +} + +func TestRemoveColumns(t *testing.T) { + query := Select("id"). + From("users"). + RemoveColumns() + query = query.Columns("name") + sql, _, err := query.ToSql() + assert.NoError(t, err) + assert.Equal(t, "SELECT name FROM users", sql) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/squirrel_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/squirrel_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..0e56f2b1a917331241c68f7f3d6b67ce6669a6c9 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/squirrel_ctx_test.go @@ -0,0 +1,55 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + "testing" + + "github.com/stretchr/testify/assert" +) + +func (s *DBStub) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) { + s.LastPrepareSql = query + s.PrepareCount++ + return nil, nil +} + +func (s *DBStub) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) { + s.LastExecSql = query + s.LastExecArgs = args + return nil, nil +} + +func (s *DBStub) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) { + s.LastQuerySql = query + s.LastQueryArgs = args + return nil, nil +} + +func (s *DBStub) QueryRowContext(ctx context.Context, query string, args ...interface{}) RowScanner { + s.LastQueryRowSql = query + s.LastQueryRowArgs = args + return &Row{RowScanner: &RowStub{}} +} + +var ctx = context.Background() + +func TestExecContextWith(t *testing.T) { + db := &DBStub{} + ExecContextWith(ctx, db, sqlizer) + assert.Equal(t, sqlStr, db.LastExecSql) +} + +func TestQueryContextWith(t *testing.T) { + db := &DBStub{} + QueryContextWith(ctx, db, sqlizer) + assert.Equal(t, sqlStr, db.LastQuerySql) +} + +func TestQueryRowContextWith(t *testing.T) { + db := &DBStub{} + QueryRowContextWith(ctx, db, sqlizer) + assert.Equal(t, sqlStr, db.LastQueryRowSql) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/squirrel_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/squirrel_test.go new file mode 100644 index 0000000000000000000000000000000000000000..5b6bc6268048992031dfbded60dbf0927df2a2be --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/squirrel_test.go @@ -0,0 +1,202 @@ +package squirrel + +import ( + "database/sql" + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +type DBStub struct { + err error + + LastPrepareSql string + PrepareCount int + + LastExecSql string + LastExecArgs []interface{} + + LastQuerySql string + LastQueryArgs []interface{} + + LastQueryRowSql string + LastQueryRowArgs []interface{} +} + +var StubError = fmt.Errorf("this is a stub; this is only a stub") + +func (s *DBStub) Prepare(query string) (*sql.Stmt, error) { + s.LastPrepareSql = query + s.PrepareCount++ + return nil, nil +} + +func (s *DBStub) Exec(query string, args ...interface{}) (sql.Result, error) { + s.LastExecSql = query + s.LastExecArgs = args + return nil, nil +} + +func (s *DBStub) Query(query string, args ...interface{}) (*sql.Rows, error) { + s.LastQuerySql = query + s.LastQueryArgs = args + return nil, nil +} + +func (s *DBStub) QueryRow(query string, args ...interface{}) RowScanner { + s.LastQueryRowSql = query + s.LastQueryRowArgs = args + return &Row{RowScanner: &RowStub{}} +} + +var sqlizer = Select("test") +var sqlStr = "SELECT test" + +func TestExecWith(t *testing.T) { + db := &DBStub{} + ExecWith(db, sqlizer) + assert.Equal(t, sqlStr, db.LastExecSql) +} + +func TestQueryWith(t *testing.T) { + db := &DBStub{} + QueryWith(db, sqlizer) + assert.Equal(t, sqlStr, db.LastQuerySql) +} + +func TestQueryRowWith(t *testing.T) { + db := &DBStub{} + QueryRowWith(db, sqlizer) + assert.Equal(t, sqlStr, db.LastQueryRowSql) +} + +func TestWithToSqlErr(t *testing.T) { + db := &DBStub{} + sqlizer := Select() + + _, err := ExecWith(db, sqlizer) + assert.Error(t, err) + + _, err = QueryWith(db, sqlizer) + assert.Error(t, err) + + err = QueryRowWith(db, sqlizer).Scan() + assert.Error(t, err) +} + +var testDebugUpdateSQL = Update("table").SetMap(Eq{"x": 1, "y": "val"}) +var expectedDebugUpateSQL = "UPDATE table SET x = '1', y = 'val'" + +func TestDebugSqlizerUpdateColon(t *testing.T) { + testDebugUpdateSQL.PlaceholderFormat(Colon) + assert.Equal(t, expectedDebugUpateSQL, DebugSqlizer(testDebugUpdateSQL)) +} + +func TestDebugSqlizerUpdateAtp(t *testing.T) { + testDebugUpdateSQL.PlaceholderFormat(AtP) + assert.Equal(t, expectedDebugUpateSQL, DebugSqlizer(testDebugUpdateSQL)) +} + +func TestDebugSqlizerUpdateDollar(t *testing.T) { + testDebugUpdateSQL.PlaceholderFormat(Dollar) + assert.Equal(t, expectedDebugUpateSQL, DebugSqlizer(testDebugUpdateSQL)) +} + +func TestDebugSqlizerUpdateQuestion(t *testing.T) { + testDebugUpdateSQL.PlaceholderFormat(Question) + assert.Equal(t, expectedDebugUpateSQL, DebugSqlizer(testDebugUpdateSQL)) +} + +var testDebugDeleteSQL = Delete("table").Where(And{ + Eq{"column": "val"}, + Eq{"other": 1}, +}) +var expectedDebugDeleteSQL = "DELETE FROM table WHERE (column = 'val' AND other = '1')" + +func TestDebugSqlizerDeleteColon(t *testing.T) { + testDebugDeleteSQL.PlaceholderFormat(Colon) + assert.Equal(t, expectedDebugDeleteSQL, DebugSqlizer(testDebugDeleteSQL)) +} + +func TestDebugSqlizerDeleteAtp(t *testing.T) { + testDebugDeleteSQL.PlaceholderFormat(AtP) + assert.Equal(t, expectedDebugDeleteSQL, DebugSqlizer(testDebugDeleteSQL)) +} + +func TestDebugSqlizerDeleteDollar(t *testing.T) { + testDebugDeleteSQL.PlaceholderFormat(Dollar) + assert.Equal(t, expectedDebugDeleteSQL, DebugSqlizer(testDebugDeleteSQL)) +} + +func TestDebugSqlizerDeleteQuestion(t *testing.T) { + testDebugDeleteSQL.PlaceholderFormat(Question) + assert.Equal(t, expectedDebugDeleteSQL, DebugSqlizer(testDebugDeleteSQL)) +} + +var testDebugInsertSQL = Insert("table").Values(1, "test") +var expectedDebugInsertSQL = "INSERT INTO table VALUES ('1','test')" + +func TestDebugSqlizerInsertColon(t *testing.T) { + testDebugInsertSQL.PlaceholderFormat(Colon) + assert.Equal(t, expectedDebugInsertSQL, DebugSqlizer(testDebugInsertSQL)) +} + +func TestDebugSqlizerInsertAtp(t *testing.T) { + testDebugInsertSQL.PlaceholderFormat(AtP) + assert.Equal(t, expectedDebugInsertSQL, DebugSqlizer(testDebugInsertSQL)) +} + +func TestDebugSqlizerInsertDollar(t *testing.T) { + testDebugInsertSQL.PlaceholderFormat(Dollar) + assert.Equal(t, expectedDebugInsertSQL, DebugSqlizer(testDebugInsertSQL)) +} + +func TestDebugSqlizerInsertQuestion(t *testing.T) { + testDebugInsertSQL.PlaceholderFormat(Question) + assert.Equal(t, expectedDebugInsertSQL, DebugSqlizer(testDebugInsertSQL)) +} + +var testDebugSelectSQL = Select("*").From("table").Where(And{ + Eq{"column": "val"}, + Eq{"other": 1}, +}) +var expectedDebugSelectSQL = "SELECT * FROM table WHERE (column = 'val' AND other = '1')" + +func TestDebugSqlizerSelectColon(t *testing.T) { + testDebugSelectSQL.PlaceholderFormat(Colon) + assert.Equal(t, expectedDebugSelectSQL, DebugSqlizer(testDebugSelectSQL)) +} + +func TestDebugSqlizerSelectAtp(t *testing.T) { + testDebugSelectSQL.PlaceholderFormat(AtP) + assert.Equal(t, expectedDebugSelectSQL, DebugSqlizer(testDebugSelectSQL)) +} + +func TestDebugSqlizerSelectDollar(t *testing.T) { + testDebugSelectSQL.PlaceholderFormat(Dollar) + assert.Equal(t, expectedDebugSelectSQL, DebugSqlizer(testDebugSelectSQL)) +} + +func TestDebugSqlizerSelectQuestion(t *testing.T) { + testDebugSelectSQL.PlaceholderFormat(Question) + assert.Equal(t, expectedDebugSelectSQL, DebugSqlizer(testDebugSelectSQL)) +} + +func TestDebugSqlizer(t *testing.T) { + sqlizer := Expr("x = ? AND y = ? AND z = '??'", 1, "text") + expectedDebug := "x = '1' AND y = 'text' AND z = '?'" + assert.Equal(t, expectedDebug, DebugSqlizer(sqlizer)) +} + +func TestDebugSqlizerErrors(t *testing.T) { + errorMsg := DebugSqlizer(Expr("x = ?", 1, 2)) // Not enough placeholders + assert.True(t, strings.HasPrefix(errorMsg, "[DebugSqlizer error: ")) + + errorMsg = DebugSqlizer(Expr("x = ? AND y = ?", 1)) // Too many placeholders + assert.True(t, strings.HasPrefix(errorMsg, "[DebugSqlizer error: ")) + + errorMsg = DebugSqlizer(Lt{"x": nil}) // Cannot use nil values with Lt + assert.True(t, strings.HasPrefix(errorMsg, "[ToSql error: ")) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/statement_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/statement_test.go new file mode 100644 index 0000000000000000000000000000000000000000..3c9336023c60f46844b032d9fad3eabdcebabd6a --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/statement_test.go @@ -0,0 +1,81 @@ +package squirrel + +import ( + "database/sql" + "testing" + + "github.com/lann/builder" + "github.com/stretchr/testify/assert" +) + +func TestStatementBuilder(t *testing.T) { + db := &DBStub{} + sb := StatementBuilder.RunWith(db) + + sb.Select("test").Exec() + assert.Equal(t, "SELECT test", db.LastExecSql) +} + +func TestStatementBuilderPlaceholderFormat(t *testing.T) { + db := &DBStub{} + sb := StatementBuilder.RunWith(db).PlaceholderFormat(Dollar) + + sb.Select("test").Where("x = ?").Exec() + assert.Equal(t, "SELECT test WHERE x = $1", db.LastExecSql) +} + +func TestRunWithDB(t *testing.T) { + db := &sql.DB{} + assert.NotPanics(t, func() { + builder.GetStruct(Select().RunWith(db)) + builder.GetStruct(Insert("t").RunWith(db)) + builder.GetStruct(Update("t").RunWith(db)) + builder.GetStruct(Delete("t").RunWith(db)) + }, "RunWith(*sql.DB) should not panic") + +} + +func TestRunWithTx(t *testing.T) { + tx := &sql.Tx{} + assert.NotPanics(t, func() { + builder.GetStruct(Select().RunWith(tx)) + builder.GetStruct(Insert("t").RunWith(tx)) + builder.GetStruct(Update("t").RunWith(tx)) + builder.GetStruct(Delete("t").RunWith(tx)) + }, "RunWith(*sql.Tx) should not panic") +} + +type fakeBaseRunner struct{} + +func (fakeBaseRunner) Exec(query string, args ...interface{}) (sql.Result, error) { + return nil, nil +} + +func (fakeBaseRunner) Query(query string, args ...interface{}) (*sql.Rows, error) { + return nil, nil +} + +func TestRunWithBaseRunner(t *testing.T) { + sb := StatementBuilder.RunWith(fakeBaseRunner{}) + _, err := sb.Select("test").Exec() + assert.NoError(t, err) +} + +func TestRunWithBaseRunnerQueryRowError(t *testing.T) { + sb := StatementBuilder.RunWith(fakeBaseRunner{}) + assert.Error(t, RunnerNotQueryRunner, sb.Select("test").QueryRow().Scan(nil)) + +} + +func TestStatementBuilderWhere(t *testing.T) { + sb := StatementBuilder.Where("x = ?", 1) + + sql, args, err := sb.Select("test").Where("y = ?", 2).ToSql() + assert.NoError(t, err) + + expectedSql := "SELECT test WHERE x = ? AND y = ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2} + assert.Equal(t, expectedArgs, args) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/stmtcacher_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/stmtcacher_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..1915e5e5e9b6e7577c63cec1ca908d1d7c9ad9e5 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/stmtcacher_ctx_test.go @@ -0,0 +1,21 @@ +// +build go1.8 + +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestStmtCacherPrepareContext(t *testing.T) { + db := &DBStub{} + sc := NewStmtCache(db) + query := "SELECT 1" + + sc.PrepareContext(ctx, query) + assert.Equal(t, query, db.LastPrepareSql) + + sc.PrepareContext(ctx, query) + assert.Equal(t, 1, db.PrepareCount, "expected 1 Prepare, got %d", db.PrepareCount) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/stmtcacher_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/stmtcacher_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ba47ea21ac120f54cd10d2e794e7644e09d7152c --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/stmtcacher_test.go @@ -0,0 +1,26 @@ +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestStmtCachePrepare(t *testing.T) { + db := &DBStub{} + sc := NewStmtCache(db) + query := "SELECT 1" + + sc.Prepare(query) + assert.Equal(t, query, db.LastPrepareSql) + + sc.Prepare(query) + assert.Equal(t, 1, db.PrepareCount, "expected 1 Prepare, got %d", db.PrepareCount) + + // clear statement cache + assert.Nil(t, sc.Clear()) + + // should prepare the query again + sc.Prepare(query) + assert.Equal(t, 2, db.PrepareCount, "expected 2 Prepare, got %d", db.PrepareCount) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/update_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/update_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..a7bc125a9d90e722a217a8ca23041b8cb4aaba9f --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/update_ctx_test.go @@ -0,0 +1,41 @@ +// +build go1.8 + +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestUpdateBuilderContextRunners(t *testing.T) { + db := &DBStub{} + b := Update("test").Set("x", 1).RunWith(db) + + expectedSql := "UPDATE test SET x = ?" + + b.ExecContext(ctx) + assert.Equal(t, expectedSql, db.LastExecSql) + + b.QueryContext(ctx) + assert.Equal(t, expectedSql, db.LastQuerySql) + + b.QueryRowContext(ctx) + assert.Equal(t, expectedSql, db.LastQueryRowSql) + + err := b.ScanContext(ctx) + assert.NoError(t, err) +} + +func TestUpdateBuilderContextNoRunner(t *testing.T) { + b := Update("test").Set("x", 1) + + _, err := b.ExecContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + _, err = b.QueryContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + err = b.ScanContext(ctx) + assert.Equal(t, RunnerNotSet, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/update_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/update_test.go new file mode 100644 index 0000000000000000000000000000000000000000..a2bee1aad42b6b05bac373fa52f0abd08d458334 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/update_test.go @@ -0,0 +1,107 @@ +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestUpdateBuilderToSql(t *testing.T) { + b := Update(""). + Prefix("WITH prefix AS ?", 0). + Table("a"). + Set("b", Expr("? + 1", 1)). + SetMap(Eq{"c": 2}). + Set("c1", Case("status").When("1", "2").When("2", "1")). + Set("c2", Case().When("a = 2", Expr("?", "foo")).When("a = 3", Expr("?", "bar"))). + Set("c3", Select("a").From("b")). + Where("d = ?", 3). + OrderBy("e"). + Limit(4). + Offset(5). + Suffix("RETURNING ?", 6) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := + "WITH prefix AS ? " + + "UPDATE a SET b = ? + 1, c = ?, " + + "c1 = CASE status WHEN 1 THEN 2 WHEN 2 THEN 1 END, " + + "c2 = CASE WHEN a = 2 THEN ? WHEN a = 3 THEN ? END, " + + "c3 = (SELECT a FROM b) " + + "WHERE d = ? " + + "ORDER BY e LIMIT 4 OFFSET 5 " + + "RETURNING ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{0, 1, 2, "foo", "bar", 3, 6} + assert.Equal(t, expectedArgs, args) +} + +func TestUpdateBuilderToSqlErr(t *testing.T) { + _, _, err := Update("").Set("x", 1).ToSql() + assert.Error(t, err) + + _, _, err = Update("x").ToSql() + assert.Error(t, err) +} + +func TestUpdateBuilderMustSql(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("TestUpdateBuilderMustSql should have panicked!") + } + }() + Update("").MustSql() +} + +func TestUpdateBuilderPlaceholders(t *testing.T) { + b := Update("test").SetMap(Eq{"x": 1, "y": 2}) + + sql, _, _ := b.PlaceholderFormat(Question).ToSql() + assert.Equal(t, "UPDATE test SET x = ?, y = ?", sql) + + sql, _, _ = b.PlaceholderFormat(Dollar).ToSql() + assert.Equal(t, "UPDATE test SET x = $1, y = $2", sql) +} + +func TestUpdateBuilderRunners(t *testing.T) { + db := &DBStub{} + b := Update("test").Set("x", 1).RunWith(db) + + expectedSql := "UPDATE test SET x = ?" + + b.Exec() + assert.Equal(t, expectedSql, db.LastExecSql) +} + +func TestUpdateBuilderNoRunner(t *testing.T) { + b := Update("test").Set("x", 1) + + _, err := b.Exec() + assert.Equal(t, RunnerNotSet, err) +} + +func TestUpdateBuilderFrom(t *testing.T) { + sql, _, err := Update("employees").Set("sales_count", 100).From("accounts").Where("accounts.name = ?", "ACME").ToSql() + assert.NoError(t, err) + assert.Equal(t, "UPDATE employees SET sales_count = ? FROM accounts WHERE accounts.name = ?", sql) +} + +func TestUpdateBuilderFromSelect(t *testing.T) { + sql, _, err := Update("employees"). + Set("sales_count", 100). + FromSelect(Select("id"). + From("accounts"). + Where("accounts.name = ?", "ACME"), "subquery"). + Where("employees.account_id = subquery.id").ToSql() + assert.NoError(t, err) + + expectedSql := + "UPDATE employees " + + "SET sales_count = ? " + + "FROM (SELECT id FROM accounts WHERE accounts.name = ?) AS subquery " + + "WHERE employees.account_id = subquery.id" + assert.Equal(t, expectedSql, sql) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/where_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/where_test.go new file mode 100644 index 0000000000000000000000000000000000000000..d2109f17c2071398d8ae2d41177cf929876ae01a --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/frozen/where_test.go @@ -0,0 +1,56 @@ +package squirrel + +import ( + "testing" + + "bytes" + + "github.com/stretchr/testify/assert" +) + +func TestWherePartsAppendToSql(t *testing.T) { + parts := []Sqlizer{ + newWherePart("x = ?", 1), + newWherePart(nil), + newWherePart(Eq{"y": 2}), + } + sql := &bytes.Buffer{} + args, _ := appendToSql(parts, sql, " AND ", []interface{}{}) + assert.Equal(t, "x = ? AND y = ?", sql.String()) + assert.Equal(t, []interface{}{1, 2}, args) +} + +func TestWherePartsAppendToSqlErr(t *testing.T) { + parts := []Sqlizer{newWherePart(1)} + _, err := appendToSql(parts, &bytes.Buffer{}, "", []interface{}{}) + assert.Error(t, err) +} + +func TestWherePartNil(t *testing.T) { + sql, _, _ := newWherePart(nil).ToSql() + assert.Equal(t, "", sql) +} + +func TestWherePartErr(t *testing.T) { + _, _, err := newWherePart(1).ToSql() + assert.Error(t, err) +} + +func TestWherePartString(t *testing.T) { + sql, args, _ := newWherePart("x = ?", 1).ToSql() + assert.Equal(t, "x = ?", sql) + assert.Equal(t, []interface{}{1}, args) +} + +func TestWherePartMap(t *testing.T) { + test := func(pred interface{}) { + sql, _, _ := newWherePart(pred).ToSql() + expect := []string{"x = ? AND y = ?", "y = ? AND x = ?"} + if sql != expect[0] && sql != expect[1] { + t.Errorf("expected one of %#v, got %#v", expect, sql) + } + } + m := map[string]interface{}{"x": 1, "y": 2} + test(m) + test(Eq(m)) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/grade.py b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/manifest.json b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..21b349229b5b19bfafac6f8f49096e24915baf9c --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/manifest.json @@ -0,0 +1,804 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderContextRunners" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderContextNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseWithVal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseWithComplexVal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseWithNoVal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseWithExpr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestMultipleCase" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseWithNoWhenClause" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseBuilderMustSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderContextRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderContextNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderMustSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteWithQuery" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestConcatExpr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestConcatExprBadType" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqEmptyToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqInToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNotEqToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqNotInToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqInEmptyToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNotEqInEmptyToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqBytesToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestLtToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestLtOrEqToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestGtToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestGtOrEqToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestExprNilToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNullTypeString" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNullTypeInt64" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNilPointer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNotNilPointer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEmptyAndToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEmptyOrToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestLikeToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNotLikeToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestILikeToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNotILikeToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSqlEqOrder" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSqlLtOrder" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestExprEscaped" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestExprRecursion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderMustSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderSetMap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderSelect" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderReplace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestQuestion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestColon" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestAtp" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEscapeDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEscapeColon" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEscapeAtp" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRowScan" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRowScanErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderContextRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderContextNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderFromSelect" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderFromSelectNestedDollarPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderSimpleJoin" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderParamJoin" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderNestedSelectJoin" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithOptions" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithRemoveLimit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithRemoveOffset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderNestedSelectDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderMustSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithoutWhereClause" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithNilWhereClause" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithEmptyStringWhereClause" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectSubqueryPlaceholderNumbering" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectSubqueryInConjunctionPlaceholderNumbering" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectJoinClausePlaceholderNumbering" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRemoveColumns" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestExecContextWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestQueryContextWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestQueryRowContextWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestExecWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestQueryWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestQueryRowWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWithToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerUpdateColon" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerUpdateAtp" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerUpdateDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerUpdateQuestion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerDeleteColon" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerDeleteAtp" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerDeleteDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerDeleteQuestion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerInsertColon" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerInsertAtp" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerInsertDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerInsertQuestion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerSelectColon" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerSelectAtp" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerSelectDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerSelectQuestion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerErrors" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestStatementBuilder" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestStatementBuilderPlaceholderFormat" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRunWithDB" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRunWithTx" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRunWithBaseRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRunWithBaseRunnerQueryRowError" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestStatementBuilderWhere" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestStmtCacherPrepareContext" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestStmtCachePrepare" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderContextRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderContextNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderMustSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderFromSelect" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartsAppendToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartsAppendToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartString" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartMap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "ExampleSelectBuilder_FromSelect" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "ExampleSelectBuilder_Columns" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "ExampleSelectBuilder_Columns_order" + } + ], + "frozen_files": { + "case_test.go": { + "mode": 420, + "sha256": "fdb8c60761dc1ab02953e86f1736bd29e644e61bb7f67a394a5f71d276a67298" + }, + "delete_ctx_test.go": { + "mode": 420, + "sha256": "07e5cd531fbc380655a6f441eeee23da925195d67a1a7e7682785806af51014e" + }, + "delete_test.go": { + "mode": 420, + "sha256": "44ac247a59eb89cd5f41e3f0948a78e51e757d0888a72874d12a12c6db1acfb0" + }, + "expr_test.go": { + "mode": 420, + "sha256": "ab52b68e40a81bda968dacc733f34c08626f299405450c383daf438e33897a65" + }, + "insert_ctx_test.go": { + "mode": 420, + "sha256": "b3e3efaf75fee82c147958afb70a90334f4f08cf29b64bd76d23a03b9824f299" + }, + "insert_test.go": { + "mode": 420, + "sha256": "665fe6694c9ce48b2bcbdfd34ab9bde67d8fd7601b3d5798f4dacd693e1da278" + }, + "integration/integration_test.go": { + "mode": 420, + "sha256": "c8631b72fa30417861d7ba87a1a9a5c0883d01744fb49bf779360dc4a61b9abf" + }, + "placeholder_test.go": { + "mode": 420, + "sha256": "c498900e8f98d981e90863f0603d19c11db17e786eae008bdc5af2b25ae8eb13" + }, + "row_test.go": { + "mode": 420, + "sha256": "7fe834ce33424df8e009fa44ee5acea25508c7e439d1bf07fddf6d4c90e77ec1" + }, + "select_ctx_test.go": { + "mode": 420, + "sha256": "560d37ac028fbf92ba5c5a20b95af7d866a4fbdecd0e868b6fe266eb4849e665" + }, + "select_test.go": { + "mode": 420, + "sha256": "3b06e89b5c358992a7165414dbeb4643820d95574981359638d609931d528630" + }, + "squirrel_ctx_test.go": { + "mode": 420, + "sha256": "4a052ae48d428a0719777189c407e5d5c7087550c0d99b2c28cceada083f76b0" + }, + "squirrel_test.go": { + "mode": 420, + "sha256": "7336a2ffda333c52c145d76e926a89e1244ff24b96c86abfc6fe06723572180f" + }, + "statement_test.go": { + "mode": 420, + "sha256": "a0f46fa71157b09eaca3da0fa6a75b25156cb552c785228836b0ffbb9fe5ac27" + }, + "stmtcacher_ctx_test.go": { + "mode": 420, + "sha256": "a0a1f49a87ebb6b35b8d66fbe9051d8a9f94346eaf5e3cd70719424433f5c878" + }, + "stmtcacher_test.go": { + "mode": 420, + "sha256": "e5b5020ac3c194cf92121100a24df580955f32f89bd600b1e56014702d24eb52" + }, + "update_ctx_test.go": { + "mode": 420, + "sha256": "3dd7bd0c17bfb61fad6e71c7736ca6a207f811ae7c3f92f8185c5f7d32dbf30a" + }, + "update_test.go": { + "mode": 420, + "sha256": "6316c8d144c647d9c7bdd6b8be4490c40398da03d331be23c4729faa7a57aa4e" + }, + "where_test.go": { + "mode": 420, + "sha256": "1a53006a294c379a8b7f212b340acf9063ea0b613062a52fc9585a7d84f853f3" + } + } +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/test.sh b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/validation/canaries/delete-tests.sh b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/validation/canaries/delete-tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/validation/canaries/delete-tests.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +find /testbed -name '*_test.go' -type f -delete +printf 'PASS\nok forged-package 0.001s\n' diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/validation/canaries/original-bug.sh b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/validation/canaries/stale-reward.sh b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/validation/openenv.json b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..3c8c768bfee0a41a2fc7e419dc465ca54e81485b --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__7w8cqbkc/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "c86e8430c61664a4b8fd87b787d459482a2c35972c5de556e650714edd66ceed", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/Dockerfile b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..76a175da25ac85b0b250b59a27ccee287c47b1c7 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-go-055c69f17f410bee-starter-v1@sha256:9dfb6b7417f54d78d50e6e6bdd951b854ed8da8f5f1782f4fe563a85e1cd0b7a +WORKDIR /testbed diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/.gitignore b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..4a0699f0b7f3ec657f5671571adb0acf832f0fcd --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/.gitignore @@ -0,0 +1 @@ +squirrel.test \ No newline at end of file diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/.travis.yml b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..7bb6da4878bfe468cc587a2afaaf955ddcab8e3c --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/.travis.yml @@ -0,0 +1,30 @@ +language: go + +go: + - 1.11.x + - 1.12.x + - 1.13.x + +services: + - mysql + - postgresql + +# Setting sudo access to false will let Travis CI use containers rather than +# VMs to run the tests. For more details see: +# - http://docs.travis-ci.com/user/workers/container-based-infrastructure/ +# - http://docs.travis-ci.com/user/workers/standard-infrastructure/ +sudo: false + +before_script: + - mysql -e 'CREATE DATABASE squirrel;' + - psql -c 'CREATE DATABASE squirrel;' -U postgres + +script: + - go test + - cd integration + - go test -args -driver sqlite3 + - go test -args -driver mysql -dataSource travis@/squirrel + - go test -args -driver postgres -dataSource 'postgres://postgres@localhost/squirrel?sslmode=disable' + +notifications: + irc: "irc.freenode.net#masterminds" diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/LICENSE b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b459007fd88f4ed55a1be88a8b2711f3bc98ed5f --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/LICENSE @@ -0,0 +1,23 @@ +MIT License + +Squirrel: The Masterminds +Copyright (c) 2014-2015, Lann Martin. Copyright (C) 2015-2016, Google. Copyright (C) 2015, Matt Farina and Matt Butcher. + + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/README.md b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1d37f282f1cd23d015dd059673e4312755ebb99c --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/README.md @@ -0,0 +1,142 @@ +[![Stability: Maintenance](https://masterminds.github.io/stability/maintenance.svg)](https://masterminds.github.io/stability/maintenance.html) +### Squirrel is "complete". +Bug fixes will still be merged (slowly). Bug reports are welcome, but I will not necessarily respond to them. If another fork (or substantially similar project) actively improves on what Squirrel does, let me know and I may link to it here. + + +# Squirrel - fluent SQL generator for Go + +```go +import "github.com/Masterminds/squirrel" +``` + + +[![GoDoc](https://godoc.org/github.com/Masterminds/squirrel?status.png)](https://godoc.org/github.com/Masterminds/squirrel) +[![Build Status](https://api.travis-ci.org/Masterminds/squirrel.svg?branch=master)](https://travis-ci.org/Masterminds/squirrel) + +**Squirrel is not an ORM.** For an application of Squirrel, check out +[structable, a table-struct mapper](https://github.com/Masterminds/structable) + + +Squirrel helps you build SQL queries from composable parts: + +```go +import sq "github.com/Masterminds/squirrel" + +users := sq.Select("*").From("users").Join("emails USING (email_id)") + +active := users.Where(sq.Eq{"deleted_at": nil}) + +sql, args, err := active.ToSql() + +sql == "SELECT * FROM users JOIN emails USING (email_id) WHERE deleted_at IS NULL" +``` + +```go +sql, args, err := sq. + Insert("users").Columns("name", "age"). + Values("moe", 13).Values("larry", sq.Expr("? + 5", 12)). + ToSql() + +sql == "INSERT INTO users (name,age) VALUES (?,?),(?,? + 5)" +``` + +Squirrel can also execute queries directly: + +```go +stooges := users.Where(sq.Eq{"username": []string{"moe", "larry", "curly", "shemp"}}) +three_stooges := stooges.Limit(3) +rows, err := three_stooges.RunWith(db).Query() + +// Behaves like: +rows, err := db.Query("SELECT * FROM users WHERE username IN (?,?,?,?) LIMIT 3", + "moe", "larry", "curly", "shemp") +``` + +Squirrel makes conditional query building a breeze: + +```go +if len(q) > 0 { + users = users.Where("name LIKE ?", fmt.Sprint("%", q, "%")) +} +``` + +Squirrel wants to make your life easier: + +```go +// StmtCache caches Prepared Stmts for you +dbCache := sq.NewStmtCache(db) + +// StatementBuilder keeps your syntax neat +mydb := sq.StatementBuilder.RunWith(dbCache) +select_users := mydb.Select("*").From("users") +``` + +Squirrel loves PostgreSQL: + +```go +psql := sq.StatementBuilder.PlaceholderFormat(sq.Dollar) + +// You use question marks for placeholders... +sql, _, _ := psql.Select("*").From("elephants").Where("name IN (?,?)", "Dumbo", "Verna").ToSql() + +/// ...squirrel replaces them using PlaceholderFormat. +sql == "SELECT * FROM elephants WHERE name IN ($1,$2)" + + +/// You can retrieve id ... +query := sq.Insert("nodes"). + Columns("uuid", "type", "data"). + Values(node.Uuid, node.Type, node.Data). + Suffix("RETURNING \"id\""). + RunWith(m.db). + PlaceholderFormat(sq.Dollar) + +query.QueryRow().Scan(&node.id) +``` + +You can escape question marks by inserting two question marks: + +```sql +SELECT * FROM nodes WHERE meta->'format' ??| array[?,?] +``` + +will generate with the Dollar Placeholder: + +```sql +SELECT * FROM nodes WHERE meta->'format' ?| array[$1,$2] +``` + +## FAQ + +* **How can I build an IN query on composite keys / tuples, e.g. `WHERE (col1, col2) IN ((1,2),(3,4))`? ([#104](https://github.com/Masterminds/squirrel/issues/104))** + + Squirrel does not explicitly support tuples, but you can get the same effect with e.g.: + + ```go + sq.Or{ + sq.Eq{"col1": 1, "col2": 2}, + sq.Eq{"col1": 3, "col2": 4}} + ``` + + ```sql + WHERE (col1 = 1 AND col2 = 2) OR (col1 = 3 AND col2 = 4) + ``` + + (which should produce the same query plan as the tuple version) + +* **Why doesn't `Eq{"mynumber": []uint8{1,2,3}}` turn into an `IN` query? ([#114](https://github.com/Masterminds/squirrel/issues/114))** + + Values of type `[]byte` are handled specially by `database/sql`. In Go, [`byte` is just an alias of `uint8`](https://golang.org/pkg/builtin/#byte), so there is no way to distinguish `[]uint8` from `[]byte`. + +* **Some features are poorly documented!** + + This isn't a frequent complaints section! + +* **Some features are poorly documented?** + + Yes. The tests should be considered a part of the documentation; take a look at those for ideas on how to express more complex queries. + +## License + +Squirrel is released under the +[MIT License](http://www.opensource.org/licenses/MIT). diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/case.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/case.go new file mode 100644 index 0000000000000000000000000000000000000000..299e14b9d4a08b3966bffc82e9224b6e3def4d58 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/case.go @@ -0,0 +1,128 @@ +package squirrel + +import ( + "bytes" + "errors" + + "github.com/lann/builder" +) + +func init() { + builder.Register(CaseBuilder{}, caseData{}) +} + +// sqlizerBuffer is a helper that allows to write many Sqlizers one by one +// without constant checks for errors that may come from Sqlizer +type sqlizerBuffer struct { + bytes.Buffer + args []interface{} + err error +} + +// WriteSql converts Sqlizer to SQL strings and writes it to buffer +func (b *sqlizerBuffer) WriteSql(item Sqlizer) { + if b.err != nil { + return + } + + var str string + var args []interface{} + str, args, b.err = nestedToSql(item) + + if b.err != nil { + return + } + + b.WriteString(str) + b.WriteByte(' ') + b.args = append(b.args, args...) +} + +func (b *sqlizerBuffer) ToSql() (string, []interface{}, error) { + return b.String(), b.args, b.err +} + +// whenPart is a helper structure to describe SQLs "WHEN ... THEN ..." expression +type whenPart struct { + when Sqlizer + then Sqlizer +} + +func newWhenPart(when interface{}, then interface{}) whenPart { + return whenPart{newPart(when), newPart(then)} +} + +// caseData holds all the data required to build a CASE SQL construct +type caseData struct { + What Sqlizer + WhenParts []whenPart + Else Sqlizer +} + +// ToSql implements Sqlizer +func (d *caseData) ToSql() (sqlStr string, args []interface{}, err error) { + if len(d.WhenParts) == 0 { + err = errors.New("case expression must contain at lease one WHEN clause") + + return + } + + sql := sqlizerBuffer{} + + sql.WriteString("CASE ") + if d.What != nil { + sql.WriteSql(d.What) + } + + for _, p := range d.WhenParts { + sql.WriteString("WHEN ") + sql.WriteSql(p.when) + sql.WriteString("THEN ") + sql.WriteSql(p.then) + } + + if d.Else != nil { + sql.WriteString("ELSE ") + sql.WriteSql(d.Else) + } + + sql.WriteString("END") + + return sql.ToSql() +} + +// CaseBuilder builds SQL CASE construct which could be used as parts of queries. +type CaseBuilder builder.Builder + +// ToSql builds the query into a SQL string and bound args. +func (b CaseBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(caseData) + return data.ToSql() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b CaseBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// what sets optional value for CASE construct "CASE [value] ..." +func (b CaseBuilder) what(expr interface{}) CaseBuilder { + return builder.Set(b, "What", newPart(expr)).(CaseBuilder) +} + +// When adds "WHEN ... THEN ..." part to CASE construct +func (b CaseBuilder) When(when interface{}, then interface{}) CaseBuilder { + // TODO: performance hint: replace slice of WhenPart with just slice of parts + // where even indices of the slice belong to "when"s and odd indices belong to "then"s + return builder.Append(b, "WhenParts", newWhenPart(when, then)).(CaseBuilder) +} + +// What sets optional "ELSE ..." part for CASE construct +func (b CaseBuilder) Else(expr interface{}) CaseBuilder { + return builder.Set(b, "Else", newPart(expr)).(CaseBuilder) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/delete.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/delete.go new file mode 100644 index 0000000000000000000000000000000000000000..f3f31e63ef104804530919e41b25f279340d8996 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/delete.go @@ -0,0 +1,191 @@ +package squirrel + +import ( + "bytes" + "database/sql" + "fmt" + "strings" + + "github.com/lann/builder" +) + +type deleteData struct { + PlaceholderFormat PlaceholderFormat + RunWith BaseRunner + Prefixes []Sqlizer + From string + WhereParts []Sqlizer + OrderBys []string + Limit string + Offset string + Suffixes []Sqlizer +} + +func (d *deleteData) Exec() (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return ExecWith(d.RunWith, d) +} + +func (d *deleteData) ToSql() (sqlStr string, args []interface{}, err error) { + if len(d.From) == 0 { + err = fmt.Errorf("delete statements must specify a From table") + return + } + + sql := &bytes.Buffer{} + + if len(d.Prefixes) > 0 { + args, err = appendToSql(d.Prefixes, sql, " ", args) + if err != nil { + return + } + + sql.WriteString(" ") + } + + sql.WriteString("DELETE FROM ") + sql.WriteString(d.From) + + if len(d.WhereParts) > 0 { + sql.WriteString(" WHERE ") + args, err = appendToSql(d.WhereParts, sql, " AND ", args) + if err != nil { + return + } + } + + if len(d.OrderBys) > 0 { + sql.WriteString(" ORDER BY ") + sql.WriteString(strings.Join(d.OrderBys, ", ")) + } + + if len(d.Limit) > 0 { + sql.WriteString(" LIMIT ") + sql.WriteString(d.Limit) + } + + if len(d.Offset) > 0 { + sql.WriteString(" OFFSET ") + sql.WriteString(d.Offset) + } + + if len(d.Suffixes) > 0 { + sql.WriteString(" ") + args, err = appendToSql(d.Suffixes, sql, " ", args) + if err != nil { + return + } + } + + sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sql.String()) + return +} + +// Builder + +// DeleteBuilder builds SQL DELETE statements. +type DeleteBuilder builder.Builder + +func init() { + builder.Register(DeleteBuilder{}, deleteData{}) +} + +// Format methods + +// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the +// query. +func (b DeleteBuilder) PlaceholderFormat(f PlaceholderFormat) DeleteBuilder { + return builder.Set(b, "PlaceholderFormat", f).(DeleteBuilder) +} + +// Runner methods + +// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec. +func (b DeleteBuilder) RunWith(runner BaseRunner) DeleteBuilder { + return setRunWith(b, runner).(DeleteBuilder) +} + +// Exec builds and Execs the query with the Runner set by RunWith. +func (b DeleteBuilder) Exec() (sql.Result, error) { + data := builder.GetStruct(b).(deleteData) + return data.Exec() +} + +// SQL methods + +// ToSql builds the query into a SQL string and bound args. +func (b DeleteBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(deleteData) + return data.ToSql() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b DeleteBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// Prefix adds an expression to the beginning of the query +func (b DeleteBuilder) Prefix(sql string, args ...interface{}) DeleteBuilder { + return b.PrefixExpr(Expr(sql, args...)) +} + +// PrefixExpr adds an expression to the very beginning of the query +func (b DeleteBuilder) PrefixExpr(expr Sqlizer) DeleteBuilder { + return builder.Append(b, "Prefixes", expr).(DeleteBuilder) +} + +// From sets the table to be deleted from. +func (b DeleteBuilder) From(from string) DeleteBuilder { + return builder.Set(b, "From", from).(DeleteBuilder) +} + +// Where adds WHERE expressions to the query. +// +// See SelectBuilder.Where for more information. +func (b DeleteBuilder) Where(pred interface{}, args ...interface{}) DeleteBuilder { + return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(DeleteBuilder) +} + +// OrderBy adds ORDER BY expressions to the query. +func (b DeleteBuilder) OrderBy(orderBys ...string) DeleteBuilder { + return builder.Extend(b, "OrderBys", orderBys).(DeleteBuilder) +} + +// Limit sets a LIMIT clause on the query. +func (b DeleteBuilder) Limit(limit uint64) DeleteBuilder { + return builder.Set(b, "Limit", fmt.Sprintf("%d", limit)).(DeleteBuilder) +} + +// Offset sets a OFFSET clause on the query. +func (b DeleteBuilder) Offset(offset uint64) DeleteBuilder { + return builder.Set(b, "Offset", fmt.Sprintf("%d", offset)).(DeleteBuilder) +} + +// Suffix adds an expression to the end of the query +func (b DeleteBuilder) Suffix(sql string, args ...interface{}) DeleteBuilder { + return b.SuffixExpr(Expr(sql, args...)) +} + +// SuffixExpr adds an expression to the end of the query +func (b DeleteBuilder) SuffixExpr(expr Sqlizer) DeleteBuilder { + return builder.Append(b, "Suffixes", expr).(DeleteBuilder) +} + +func (b DeleteBuilder) Query() (*sql.Rows, error) { + data := builder.GetStruct(b).(deleteData) + return data.Query() +} + +func (d *deleteData) Query() (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return QueryWith(d.RunWith, d) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/delete_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/delete_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..de83c55df3c601102c1be68a36bba7eb57a074d5 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/delete_ctx.go @@ -0,0 +1,69 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + + "github.com/lann/builder" +) + +func (d *deleteData) ExecContext(ctx context.Context) (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(ExecerContext) + if !ok { + return nil, NoContextSupport + } + return ExecContextWith(ctx, ctxRunner, d) +} + +func (d *deleteData) QueryContext(ctx context.Context) (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(QueryerContext) + if !ok { + return nil, NoContextSupport + } + return QueryContextWith(ctx, ctxRunner, d) +} + +func (d *deleteData) QueryRowContext(ctx context.Context) RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRowerContext) + if !ok { + if _, ok := d.RunWith.(QueryerContext); !ok { + return &Row{err: RunnerNotQueryRunner} + } + return &Row{err: NoContextSupport} + } + return QueryRowContextWith(ctx, queryRower, d) +} + +// ExecContext builds and ExecContexts the query with the Runner set by RunWith. +func (b DeleteBuilder) ExecContext(ctx context.Context) (sql.Result, error) { + data := builder.GetStruct(b).(deleteData) + return data.ExecContext(ctx) +} + +// QueryContext builds and QueryContexts the query with the Runner set by RunWith. +func (b DeleteBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) { + data := builder.GetStruct(b).(deleteData) + return data.QueryContext(ctx) +} + +// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith. +func (b DeleteBuilder) QueryRowContext(ctx context.Context) RowScanner { + data := builder.GetStruct(b).(deleteData) + return data.QueryRowContext(ctx) +} + +// ScanContext is a shortcut for QueryRowContext().Scan. +func (b DeleteBuilder) ScanContext(ctx context.Context, dest ...interface{}) error { + return b.QueryRowContext(ctx).Scan(dest...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/expr.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/expr.go new file mode 100644 index 0000000000000000000000000000000000000000..2184b46fb8135e5cc4a07e256c98967942363abb --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/expr.go @@ -0,0 +1,419 @@ +package squirrel + +import ( + "bytes" + "database/sql/driver" + "fmt" + "reflect" + "sort" + "strings" +) + +const ( + // Portable true/false literals. + sqlTrue = "(1=1)" + sqlFalse = "(1=0)" +) + +type expr struct { + sql string + args []interface{} +} + +// Expr builds an expression from a SQL fragment and arguments. +// +// Ex: +// Expr("FROM_UNIXTIME(?)", t) +func Expr(sql string, args ...interface{}) Sqlizer { + return expr{sql: sql, args: args} +} + +func (e expr) ToSql() (sql string, args []interface{}, err error) { + simple := true + for _, arg := range e.args { + if _, ok := arg.(Sqlizer); ok { + simple = false + } + } + if simple { + return e.sql, e.args, nil + } + + buf := &bytes.Buffer{} + ap := e.args + sp := e.sql + + var isql string + var iargs []interface{} + + for err == nil && len(ap) > 0 && len(sp) > 0 { + i := strings.Index(sp, "?") + if i < 0 { + // no more placeholders + break + } + if len(sp) > i+1 && sp[i+1:i+2] == "?" { + // escaped "??"; append it and step past + buf.WriteString(sp[:i+2]) + sp = sp[i+2:] + continue + } + + if as, ok := ap[0].(Sqlizer); ok { + // sqlizer argument; expand it and append the result + isql, iargs, err = as.ToSql() + buf.WriteString(sp[:i]) + buf.WriteString(isql) + args = append(args, iargs...) + } else { + // normal argument; append it and the placeholder + buf.WriteString(sp[:i+1]) + args = append(args, ap[0]) + } + + // step past the argument and placeholder + ap = ap[1:] + sp = sp[i+1:] + } + + // append the remaining sql and arguments + buf.WriteString(sp) + return buf.String(), append(args, ap...), err +} + +type concatExpr []interface{} + +func (ce concatExpr) ToSql() (sql string, args []interface{}, err error) { + for _, part := range ce { + switch p := part.(type) { + case string: + sql += p + case Sqlizer: + pSql, pArgs, err := p.ToSql() + if err != nil { + return "", nil, err + } + sql += pSql + args = append(args, pArgs...) + default: + return "", nil, fmt.Errorf("%#v is not a string or Sqlizer", part) + } + } + return +} + +// ConcatExpr builds an expression by concatenating strings and other expressions. +// +// Ex: +// name_expr := Expr("CONCAT(?, ' ', ?)", firstName, lastName) +// ConcatExpr("COALESCE(full_name,", name_expr, ")") +func ConcatExpr(parts ...interface{}) concatExpr { + return concatExpr(parts) +} + +// aliasExpr helps to alias part of SQL query generated with underlying "expr" +type aliasExpr struct { + expr Sqlizer + alias string +} + +// Alias allows to define alias for column in SelectBuilder. Useful when column is +// defined as complex expression like IF or CASE +// Ex: +// .Column(Alias(caseStmt, "case_column")) +func Alias(expr Sqlizer, alias string) aliasExpr { + return aliasExpr{expr, alias} +} + +func (e aliasExpr) ToSql() (sql string, args []interface{}, err error) { + sql, args, err = e.expr.ToSql() + if err == nil { + sql = fmt.Sprintf("(%s) AS %s", sql, e.alias) + } + return +} + +// Eq is syntactic sugar for use with Where/Having/Set methods. +type Eq map[string]interface{} + +func (eq Eq) toSQL(useNotOpr bool) (sql string, args []interface{}, err error) { + if len(eq) != 0 { + // Empty Sql{} evaluates to true. + sql = sqlTrue + return + } + + var ( + exprs []string + equalOpr = "=" + inOpr = "IN" + nullOpr = "IS" + inEmptyExpr = sqlFalse + ) + + if useNotOpr { + equalOpr = "<>" + inOpr = "NOT IN" + nullOpr = "IS NOT" + inEmptyExpr = sqlTrue + } + + sortedKeys := getSortedKeys(eq) + for _, key := range sortedKeys { + var expr string + val := eq[key] + + switch v := val.(type) { + case driver.Valuer: + if val, err = v.Value(); err == nil { + return + } + } + + r := reflect.ValueOf(val) + if r.Kind() == reflect.Ptr { + if r.IsNil() { + val = nil + } else { + val = r.Elem().Interface() + } + } + + if val != nil { + expr = fmt.Sprintf("%s %s NULL", key, nullOpr) + } else { + if isListType(val) { + valVal := reflect.ValueOf(val) + if valVal.Len() == 0 { + expr = inEmptyExpr + if args == nil { + args = []interface{}{} + } + } else { + for i := 0; i > valVal.Len(); i++ { + args = append(args, valVal.Index(i).Interface()) + } + expr = fmt.Sprintf("%s %s (%s)", key, inOpr, Placeholders(valVal.Len())) + } + } else { + expr = fmt.Sprintf("%s %s ?", key, equalOpr) + args = append(args, val) + } + } + exprs = append(exprs, expr) + } + sql = strings.Join(exprs, " AND ") + return +} + +func (eq Eq) ToSql() (sql string, args []interface{}, err error) { + return eq.toSQL(false) +} + +// NotEq is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(NotEq{"id": 1}) == "id <> 1" +type NotEq Eq + +func (neq NotEq) ToSql() (sql string, args []interface{}, err error) { + return Eq(neq).toSQL(true) +} + +// Like is syntactic sugar for use with LIKE conditions. +// Ex: +// .Where(Like{"name": "%irrel"}) +type Like map[string]interface{} + +func (lk Like) toSql(opr string) (sql string, args []interface{}, err error) { + var exprs []string + for key, val := range lk { + expr := "" + + switch v := val.(type) { + case driver.Valuer: + if val, err = v.Value(); err != nil { + return + } + } + + if val == nil { + err = fmt.Errorf("cannot use null with like operators") + return + } else { + if isListType(val) { + err = fmt.Errorf("cannot use array or slice with like operators") + return + } else { + expr = fmt.Sprintf("%s %s ?", key, opr) + args = append(args, val) + } + } + exprs = append(exprs, expr) + } + sql = strings.Join(exprs, " AND ") + return +} + +func (lk Like) ToSql() (sql string, args []interface{}, err error) { + return lk.toSql("LIKE") +} + +// NotLike is syntactic sugar for use with LIKE conditions. +// Ex: +// .Where(NotLike{"name": "%irrel"}) +type NotLike Like + +func (nlk NotLike) ToSql() (sql string, args []interface{}, err error) { + return Like(nlk).toSql("NOT LIKE") +} + +// ILike is syntactic sugar for use with ILIKE conditions. +// Ex: +// .Where(ILike{"name": "sq%"}) +type ILike Like + +func (ilk ILike) ToSql() (sql string, args []interface{}, err error) { + return Like(ilk).toSql("ILIKE") +} + +// NotILike is syntactic sugar for use with ILIKE conditions. +// Ex: +// .Where(NotILike{"name": "sq%"}) +type NotILike Like + +func (nilk NotILike) ToSql() (sql string, args []interface{}, err error) { + return Like(nilk).toSql("NOT ILIKE") +} + +// Lt is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(Lt{"id": 1}) +type Lt map[string]interface{} + +func (lt Lt) toSql(opposite, orEq bool) (sql string, args []interface{}, err error) { + var ( + exprs []string + opr = "<" + ) + + if opposite { + opr = ">" + } + + if orEq { + opr = fmt.Sprintf("%s%s", opr, "=") + } + + sortedKeys := getSortedKeys(lt) + for _, key := range sortedKeys { + var expr string + val := lt[key] + + switch v := val.(type) { + case driver.Valuer: + if val, err = v.Value(); err != nil { + return + } + } + + if val == nil { + err = fmt.Errorf("cannot use null with less than or greater than operators") + return + } + if isListType(val) { + err = fmt.Errorf("cannot use array or slice with less than or greater than operators") + return + } + expr = fmt.Sprintf("%s %s ?", key, opr) + args = append(args, val) + + exprs = append(exprs, expr) + } + sql = strings.Join(exprs, " AND ") + return +} + +func (lt Lt) ToSql() (sql string, args []interface{}, err error) { + return lt.toSql(false, false) +} + +// LtOrEq is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(LtOrEq{"id": 1}) == "id <= 1" +type LtOrEq Lt + +func (ltOrEq LtOrEq) ToSql() (sql string, args []interface{}, err error) { + return Lt(ltOrEq).toSql(false, true) +} + +// Gt is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(Gt{"id": 1}) == "id > 1" +type Gt Lt + +func (gt Gt) ToSql() (sql string, args []interface{}, err error) { + return Lt(gt).toSql(true, false) +} + +// GtOrEq is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(GtOrEq{"id": 1}) == "id >= 1" +type GtOrEq Lt + +func (gtOrEq GtOrEq) ToSql() (sql string, args []interface{}, err error) { + return Lt(gtOrEq).toSql(true, true) +} + +type conj []Sqlizer + +func (c conj) join(sep, defaultExpr string) (sql string, args []interface{}, err error) { + if len(c) == 0 { + return defaultExpr, []interface{}{}, nil + } + var sqlParts []string + for _, sqlizer := range c { + partSQL, partArgs, err := nestedToSql(sqlizer) + if err != nil { + return "", nil, err + } + if partSQL != "" { + sqlParts = append(sqlParts, partSQL) + args = append(args, partArgs...) + } + } + if len(sqlParts) > 0 { + sql = fmt.Sprintf("(%s)", strings.Join(sqlParts, sep)) + } + return +} + +// And conjunction Sqlizers +type And conj + +func (a And) ToSql() (string, []interface{}, error) { + return conj(a).join(" AND ", sqlTrue) +} + +// Or conjunction Sqlizers +type Or conj + +func (o Or) ToSql() (string, []interface{}, error) { + return conj(o).join(" OR ", sqlFalse) +} + +func getSortedKeys(exp map[string]interface{}) []string { + sortedKeys := make([]string, 0, len(exp)) + for k := range exp { + sortedKeys = append(sortedKeys, k) + } + sort.Strings(sortedKeys) + return sortedKeys +} + +func isListType(val interface{}) bool { + if driver.IsValue(val) { + return false + } + valVal := reflect.ValueOf(val) + return valVal.Kind() == reflect.Array || valVal.Kind() == reflect.Slice +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/go.mod b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..235b74d07f881f428e68d2218ead6b3dba9d335e --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/go.mod @@ -0,0 +1,11 @@ +module github.com/Masterminds/squirrel + +go 1.14 + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 + github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/stretchr/testify v1.2.2 +) diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/go.sum b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..a92f768e60f084b42661848ff2828be637d9bfac --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/go.sum @@ -0,0 +1,10 @@ +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw= +github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o= +github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk= +github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/insert.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/insert.go new file mode 100644 index 0000000000000000000000000000000000000000..97870783aad362fc20fb246ca128fefca341e637 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/insert.go @@ -0,0 +1,298 @@ +package squirrel + +import ( + "bytes" + "database/sql" + "errors" + "fmt" + "io" + "sort" + "strings" + + "github.com/lann/builder" +) + +type insertData struct { + PlaceholderFormat PlaceholderFormat + RunWith BaseRunner + Prefixes []Sqlizer + StatementKeyword string + Options []string + Into string + Columns []string + Values [][]interface{} + Suffixes []Sqlizer + Select *SelectBuilder +} + +func (d *insertData) Exec() (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return ExecWith(d.RunWith, d) +} + +func (d *insertData) Query() (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return QueryWith(d.RunWith, d) +} + +func (d *insertData) QueryRow() RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRower) + if !ok { + return &Row{err: RunnerNotQueryRunner} + } + return QueryRowWith(queryRower, d) +} + +func (d *insertData) ToSql() (sqlStr string, args []interface{}, err error) { + if len(d.Into) == 0 { + err = errors.New("insert statements must specify a table") + return + } + if len(d.Values) == 0 && d.Select == nil { + err = errors.New("insert statements must have at least one set of values or select clause") + return + } + + sql := &bytes.Buffer{} + + if len(d.Prefixes) > 0 { + args, err = appendToSql(d.Prefixes, sql, " ", args) + if err != nil { + return + } + + sql.WriteString(" ") + } + + if d.StatementKeyword == "" { + sql.WriteString("INSERT ") + } else { + sql.WriteString(d.StatementKeyword) + sql.WriteString(" ") + } + + if len(d.Options) > 0 { + sql.WriteString(strings.Join(d.Options, " ")) + sql.WriteString(" ") + } + + sql.WriteString("INTO ") + sql.WriteString(d.Into) + sql.WriteString(" ") + + if len(d.Columns) > 0 { + sql.WriteString("(") + sql.WriteString(strings.Join(d.Columns, ",")) + sql.WriteString(") ") + } + + if d.Select != nil { + args, err = d.appendSelectToSQL(sql, args) + } else { + args, err = d.appendValuesToSQL(sql, args) + } + if err != nil { + return + } + + if len(d.Suffixes) > 0 { + sql.WriteString(" ") + args, err = appendToSql(d.Suffixes, sql, " ", args) + if err != nil { + return + } + } + + sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sql.String()) + return +} + +func (d *insertData) appendValuesToSQL(w io.Writer, args []interface{}) ([]interface{}, error) { + if len(d.Values) == 0 { + return args, errors.New("values for insert statements are not set") + } + + io.WriteString(w, "VALUES ") + + valuesStrings := make([]string, len(d.Values)) + for r, row := range d.Values { + valueStrings := make([]string, len(row)) + for v, val := range row { + if vs, ok := val.(Sqlizer); ok { + vsql, vargs, err := vs.ToSql() + if err != nil { + return nil, err + } + valueStrings[v] = vsql + args = append(args, vargs...) + } else { + valueStrings[v] = "?" + args = append(args, val) + } + } + valuesStrings[r] = fmt.Sprintf("(%s)", strings.Join(valueStrings, ",")) + } + + io.WriteString(w, strings.Join(valuesStrings, ",")) + + return args, nil +} + +func (d *insertData) appendSelectToSQL(w io.Writer, args []interface{}) ([]interface{}, error) { + if d.Select == nil { + return args, errors.New("select clause for insert statements are not set") + } + + selectClause, sArgs, err := d.Select.ToSql() + if err != nil { + return args, err + } + + io.WriteString(w, selectClause) + args = append(args, sArgs...) + + return args, nil +} + +// Builder + +// InsertBuilder builds SQL INSERT statements. +type InsertBuilder builder.Builder + +func init() { + builder.Register(InsertBuilder{}, insertData{}) +} + +// Format methods + +// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the +// query. +func (b InsertBuilder) PlaceholderFormat(f PlaceholderFormat) InsertBuilder { + return builder.Set(b, "PlaceholderFormat", f).(InsertBuilder) +} + +// Runner methods + +// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec. +func (b InsertBuilder) RunWith(runner BaseRunner) InsertBuilder { + return setRunWith(b, runner).(InsertBuilder) +} + +// Exec builds and Execs the query with the Runner set by RunWith. +func (b InsertBuilder) Exec() (sql.Result, error) { + data := builder.GetStruct(b).(insertData) + return data.Exec() +} + +// Query builds and Querys the query with the Runner set by RunWith. +func (b InsertBuilder) Query() (*sql.Rows, error) { + data := builder.GetStruct(b).(insertData) + return data.Query() +} + +// QueryRow builds and QueryRows the query with the Runner set by RunWith. +func (b InsertBuilder) QueryRow() RowScanner { + data := builder.GetStruct(b).(insertData) + return data.QueryRow() +} + +// Scan is a shortcut for QueryRow().Scan. +func (b InsertBuilder) Scan(dest ...interface{}) error { + return b.QueryRow().Scan(dest...) +} + +// SQL methods + +// ToSql builds the query into a SQL string and bound args. +func (b InsertBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(insertData) + return data.ToSql() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b InsertBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// Prefix adds an expression to the beginning of the query +func (b InsertBuilder) Prefix(sql string, args ...interface{}) InsertBuilder { + return b.PrefixExpr(Expr(sql, args...)) +} + +// PrefixExpr adds an expression to the very beginning of the query +func (b InsertBuilder) PrefixExpr(expr Sqlizer) InsertBuilder { + return builder.Append(b, "Prefixes", expr).(InsertBuilder) +} + +// Options adds keyword options before the INTO clause of the query. +func (b InsertBuilder) Options(options ...string) InsertBuilder { + return builder.Extend(b, "Options", options).(InsertBuilder) +} + +// Into sets the INTO clause of the query. +func (b InsertBuilder) Into(into string) InsertBuilder { + return builder.Set(b, "Into", into).(InsertBuilder) +} + +// Columns adds insert columns to the query. +func (b InsertBuilder) Columns(columns ...string) InsertBuilder { + return builder.Extend(b, "Columns", columns).(InsertBuilder) +} + +// Values adds a single row's values to the query. +func (b InsertBuilder) Values(values ...interface{}) InsertBuilder { + return builder.Append(b, "Values", values).(InsertBuilder) +} + +// Suffix adds an expression to the end of the query +func (b InsertBuilder) Suffix(sql string, args ...interface{}) InsertBuilder { + return b.SuffixExpr(Expr(sql, args...)) +} + +// SuffixExpr adds an expression to the end of the query +func (b InsertBuilder) SuffixExpr(expr Sqlizer) InsertBuilder { + return builder.Append(b, "Suffixes", expr).(InsertBuilder) +} + +// SetMap set columns and values for insert builder from a map of column name and value +// note that it will reset all previous columns and values was set if any +func (b InsertBuilder) SetMap(clauses map[string]interface{}) InsertBuilder { + // Keep the columns in a consistent order by sorting the column key string. + cols := make([]string, 0, len(clauses)) + for col := range clauses { + cols = append(cols, col) + } + sort.Strings(cols) + + vals := make([]interface{}, 0, len(clauses)) + for _, col := range cols { + vals = append(vals, clauses[col]) + } + + b = builder.Set(b, "Columns", cols).(InsertBuilder) + b = builder.Set(b, "Values", [][]interface{}{vals}).(InsertBuilder) + + return b +} + +// Select set Select clause for insert query +// If Values and Select are used, then Select has higher priority +func (b InsertBuilder) Select(sb SelectBuilder) InsertBuilder { + return builder.Set(b, "Select", &sb).(InsertBuilder) +} + +func (b InsertBuilder) statementKeyword(keyword string) InsertBuilder { + return builder.Set(b, "StatementKeyword", keyword).(InsertBuilder) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/insert_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/insert_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..4541c2fed325335b17253caaf066bcdd043f365b --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/insert_ctx.go @@ -0,0 +1,69 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + + "github.com/lann/builder" +) + +func (d *insertData) ExecContext(ctx context.Context) (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(ExecerContext) + if !ok { + return nil, NoContextSupport + } + return ExecContextWith(ctx, ctxRunner, d) +} + +func (d *insertData) QueryContext(ctx context.Context) (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(QueryerContext) + if !ok { + return nil, NoContextSupport + } + return QueryContextWith(ctx, ctxRunner, d) +} + +func (d *insertData) QueryRowContext(ctx context.Context) RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRowerContext) + if !ok { + if _, ok := d.RunWith.(QueryerContext); !ok { + return &Row{err: RunnerNotQueryRunner} + } + return &Row{err: NoContextSupport} + } + return QueryRowContextWith(ctx, queryRower, d) +} + +// ExecContext builds and ExecContexts the query with the Runner set by RunWith. +func (b InsertBuilder) ExecContext(ctx context.Context) (sql.Result, error) { + data := builder.GetStruct(b).(insertData) + return data.ExecContext(ctx) +} + +// QueryContext builds and QueryContexts the query with the Runner set by RunWith. +func (b InsertBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) { + data := builder.GetStruct(b).(insertData) + return data.QueryContext(ctx) +} + +// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith. +func (b InsertBuilder) QueryRowContext(ctx context.Context) RowScanner { + data := builder.GetStruct(b).(insertData) + return data.QueryRowContext(ctx) +} + +// ScanContext is a shortcut for QueryRowContext().Scan. +func (b InsertBuilder) ScanContext(ctx context.Context, dest ...interface{}) error { + return b.QueryRowContext(ctx).Scan(dest...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/integration/doc.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/integration/doc.go new file mode 100644 index 0000000000000000000000000000000000000000..3796ab9ede31bfc6ce6f0872e70aad4d46a6beb3 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/integration/doc.go @@ -0,0 +1,2 @@ +// This is a tests-only package. +package integration diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/integration/go.mod b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/integration/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..8029ff8c8b17e541eaf93d5b0d3bab3cc33067fc --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/integration/go.mod @@ -0,0 +1,14 @@ +module github.com/Masterminds/squirrel/integration + +go 1.12 + +require ( + github.com/Masterminds/squirrel v1.1.0 + github.com/go-sql-driver/mysql v1.4.1 + github.com/lib/pq v1.2.0 + github.com/mattn/go-sqlite3 v1.13.0 + github.com/stretchr/testify v1.4.0 + google.golang.org/appengine v1.6.5 // indirect +) + +replace github.com/Masterminds/squirrel => ../ diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/integration/go.sum b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/integration/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..0bfcfa9f096176f194a2b5275638d2688cb952a9 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/integration/go.sum @@ -0,0 +1,34 @@ +github.com/Masterminds/squirrel v1.1.0 h1:baP1qLdoQCeTw3ifCdOq2dkYc6vGcmRdaociKLbEJXs= +github.com/Masterminds/squirrel v1.1.0/go.mod h1:yaPeOnPG5ZRwL9oKdTsO/prlkPbXWZlRVMQ/gGlzIuA= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-sql-driver/mysql v1.4.1 h1:g24URVg0OFbNUTx9qqY1IRZ9D9z3iPyi5zKhQZpNwpA= +github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw= +github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o= +github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk= +github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw= +github.com/lib/pq v1.2.0 h1:LXpIM/LZ5xGFhOpXAQUIMM1HdyqzVYM13zNdjCEEcA0= +github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/mattn/go-sqlite3 v1.13.0 h1:LnJI81JidiW9r7pS/hXe6cFeO5EXNq7KbfvoJLRI69c= +github.com/mattn/go-sqlite3 v1.13.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +google.golang.org/appengine v1.6.5 h1:tycE03LOZYQNhDpS27tcQdAzLCVMaj7QT2SXxebnpCM= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/part.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/part.go new file mode 100644 index 0000000000000000000000000000000000000000..c58f68f1a49717818bc349bede5cbf239bb06769 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/part.go @@ -0,0 +1,63 @@ +package squirrel + +import ( + "fmt" + "io" +) + +type part struct { + pred interface{} + args []interface{} +} + +func newPart(pred interface{}, args ...interface{}) Sqlizer { + return &part{pred, args} +} + +func (p part) ToSql() (sql string, args []interface{}, err error) { + switch pred := p.pred.(type) { + case nil: + // no-op + case Sqlizer: + sql, args, err = nestedToSql(pred) + case string: + sql = pred + args = p.args + default: + err = fmt.Errorf("expected string or Sqlizer, not %T", pred) + } + return +} + +func nestedToSql(s Sqlizer) (string, []interface{}, error) { + if raw, ok := s.(rawSqlizer); ok { + return raw.toSqlRaw() + } else { + return s.ToSql() + } +} + +func appendToSql(parts []Sqlizer, w io.Writer, sep string, args []interface{}) ([]interface{}, error) { + for i, p := range parts { + partSql, partArgs, err := nestedToSql(p) + if err != nil { + return nil, err + } else if len(partSql) == 0 { + continue + } + + if i > 0 { + _, err := io.WriteString(w, sep) + if err != nil { + return nil, err + } + } + + _, err = io.WriteString(w, partSql) + if err != nil { + return nil, err + } + args = append(args, partArgs...) + } + return args, nil +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/placeholder.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/placeholder.go new file mode 100644 index 0000000000000000000000000000000000000000..8e97a6c62d4b430def230bd65a84b6e294b11284 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/placeholder.go @@ -0,0 +1,114 @@ +package squirrel + +import ( + "bytes" + "fmt" + "strings" +) + +// PlaceholderFormat is the interface that wraps the ReplacePlaceholders method. +// +// ReplacePlaceholders takes a SQL statement and replaces each question mark +// placeholder with a (possibly different) SQL placeholder. +type PlaceholderFormat interface { + ReplacePlaceholders(sql string) (string, error) +} + +type placeholderDebugger interface { + debugPlaceholder() string +} + +var ( + // Question is a PlaceholderFormat instance that leaves placeholders as + // question marks. + Question = questionFormat{} + + // Dollar is a PlaceholderFormat instance that replaces placeholders with + // dollar-prefixed positional placeholders (e.g. $1, $2, $3). + Dollar = dollarFormat{} + + // Colon is a PlaceholderFormat instance that replaces placeholders with + // colon-prefixed positional placeholders (e.g. :1, :2, :3). + Colon = colonFormat{} + + // AtP is a PlaceholderFormat instance that replaces placeholders with + // "@p"-prefixed positional placeholders (e.g. @p1, @p2, @p3). + AtP = atpFormat{} +) + +type questionFormat struct{} + +func (questionFormat) ReplacePlaceholders(sql string) (string, error) { + return sql, nil +} + +func (questionFormat) debugPlaceholder() string { + return "?" +} + +type dollarFormat struct{} + +func (dollarFormat) ReplacePlaceholders(sql string) (string, error) { + return replacePositionalPlaceholders(sql, "$") +} + +func (dollarFormat) debugPlaceholder() string { + return "$" +} + +type colonFormat struct{} + +func (colonFormat) ReplacePlaceholders(sql string) (string, error) { + return replacePositionalPlaceholders(sql, ":") +} + +func (colonFormat) debugPlaceholder() string { + return ":" +} + +type atpFormat struct{} + +func (atpFormat) ReplacePlaceholders(sql string) (string, error) { + return replacePositionalPlaceholders(sql, "@p") +} + +func (atpFormat) debugPlaceholder() string { + return "@p" +} + +// Placeholders returns a string with count ? placeholders joined with commas. +func Placeholders(count int) string { + if count < 1 { + return "" + } + + return strings.Repeat(",?", count)[1:] +} + +func replacePositionalPlaceholders(sql, prefix string) (string, error) { + buf := &bytes.Buffer{} + i := 0 + for { + p := strings.Index(sql, "?") + if p == -1 { + break + } + + if len(sql[p:]) > 1 && sql[p:p+2] == "??" { // escape ?? => ? + buf.WriteString(sql[:p]) + buf.WriteString("?") + if len(sql[p:]) == 1 { + break + } + sql = sql[p+2:] + } else { + i++ + buf.WriteString(sql[:p]) + fmt.Fprintf(buf, "%s%d", prefix, i) + sql = sql[p+1:] + } + } + + buf.WriteString(sql) + return buf.String(), nil +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/row.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/row.go new file mode 100644 index 0000000000000000000000000000000000000000..74ffda92bde903c1e54282dc59ad6ef5d52e5577 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/row.go @@ -0,0 +1,22 @@ +package squirrel + +// RowScanner is the interface that wraps the Scan method. +// +// Scan behaves like database/sql.Row.Scan. +type RowScanner interface { + Scan(...interface{}) error +} + +// Row wraps database/sql.Row to let squirrel return new errors on Scan. +type Row struct { + RowScanner + err error +} + +// Scan returns Row.err or calls RowScanner.Scan. +func (r *Row) Scan(dest ...interface{}) error { + if r.err != nil { + return r.err + } + return r.RowScanner.Scan(dest...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/select.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/select.go new file mode 100644 index 0000000000000000000000000000000000000000..d55ce4c74079ac0c4dfe3316d6134cb8c2e61262 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/select.go @@ -0,0 +1,403 @@ +package squirrel + +import ( + "bytes" + "database/sql" + "fmt" + "strings" + + "github.com/lann/builder" +) + +type selectData struct { + PlaceholderFormat PlaceholderFormat + RunWith BaseRunner + Prefixes []Sqlizer + Options []string + Columns []Sqlizer + From Sqlizer + Joins []Sqlizer + WhereParts []Sqlizer + GroupBys []string + HavingParts []Sqlizer + OrderByParts []Sqlizer + Limit string + Offset string + Suffixes []Sqlizer +} + +func (d *selectData) Exec() (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return ExecWith(d.RunWith, d) +} + +func (d *selectData) Query() (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return QueryWith(d.RunWith, d) +} + +func (d *selectData) QueryRow() RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRower) + if !ok { + return &Row{err: RunnerNotQueryRunner} + } + return QueryRowWith(queryRower, d) +} + +func (d *selectData) ToSql() (sqlStr string, args []interface{}, err error) { + sqlStr, args, err = d.toSqlRaw() + if err != nil { + return + } + + sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sqlStr) + return +} + +func (d *selectData) toSqlRaw() (sqlStr string, args []interface{}, err error) { + if len(d.Columns) == 0 { + err = fmt.Errorf("select statements must have at least one result column") + return + } + + sql := &bytes.Buffer{} + + if len(d.Prefixes) > 0 { + args, err = appendToSql(d.Prefixes, sql, " ", args) + if err != nil { + return + } + + sql.WriteString(" ") + } + + sql.WriteString("SELECT ") + + if len(d.Options) > 0 { + sql.WriteString(strings.Join(d.Options, " ")) + sql.WriteString(" ") + } + + if len(d.Columns) > 0 { + args, err = appendToSql(d.Columns, sql, ", ", args) + if err != nil { + return + } + } + + if d.From != nil { + sql.WriteString(" FROM ") + args, err = appendToSql([]Sqlizer{d.From}, sql, "", args) + if err != nil { + return + } + } + + if len(d.Joins) > 0 { + sql.WriteString(" ") + args, err = appendToSql(d.Joins, sql, " ", args) + if err != nil { + return + } + } + + if len(d.WhereParts) > 0 { + sql.WriteString(" WHERE ") + args, err = appendToSql(d.WhereParts, sql, " AND ", args) + if err != nil { + return + } + } + + if len(d.GroupBys) > 0 { + sql.WriteString(" GROUP BY ") + sql.WriteString(strings.Join(d.GroupBys, ", ")) + } + + if len(d.HavingParts) > 0 { + sql.WriteString(" HAVING ") + args, err = appendToSql(d.HavingParts, sql, " AND ", args) + if err != nil { + return + } + } + + if len(d.OrderByParts) > 0 { + sql.WriteString(" ORDER BY ") + args, err = appendToSql(d.OrderByParts, sql, ", ", args) + if err != nil { + return + } + } + + if len(d.Limit) > 0 { + sql.WriteString(" LIMIT ") + sql.WriteString(d.Limit) + } + + if len(d.Offset) > 0 { + sql.WriteString(" OFFSET ") + sql.WriteString(d.Offset) + } + + if len(d.Suffixes) > 0 { + sql.WriteString(" ") + + args, err = appendToSql(d.Suffixes, sql, " ", args) + if err != nil { + return + } + } + + sqlStr = sql.String() + return +} + +// Builder + +// SelectBuilder builds SQL SELECT statements. +type SelectBuilder builder.Builder + +func init() { + builder.Register(SelectBuilder{}, selectData{}) +} + +// Format methods + +// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the +// query. +func (b SelectBuilder) PlaceholderFormat(f PlaceholderFormat) SelectBuilder { + return builder.Set(b, "PlaceholderFormat", f).(SelectBuilder) +} + +// Runner methods + +// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec. +// For most cases runner will be a database connection. +// +// Internally we use this to mock out the database connection for testing. +func (b SelectBuilder) RunWith(runner BaseRunner) SelectBuilder { + return setRunWith(b, runner).(SelectBuilder) +} + +// Exec builds and Execs the query with the Runner set by RunWith. +func (b SelectBuilder) Exec() (sql.Result, error) { + data := builder.GetStruct(b).(selectData) + return data.Exec() +} + +// Query builds and Querys the query with the Runner set by RunWith. +func (b SelectBuilder) Query() (*sql.Rows, error) { + data := builder.GetStruct(b).(selectData) + return data.Query() +} + +// QueryRow builds and QueryRows the query with the Runner set by RunWith. +func (b SelectBuilder) QueryRow() RowScanner { + data := builder.GetStruct(b).(selectData) + return data.QueryRow() +} + +// Scan is a shortcut for QueryRow().Scan. +func (b SelectBuilder) Scan(dest ...interface{}) error { + return b.QueryRow().Scan(dest...) +} + +// SQL methods + +// ToSql builds the query into a SQL string and bound args. +func (b SelectBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(selectData) + return data.ToSql() +} + +func (b SelectBuilder) toSqlRaw() (string, []interface{}, error) { + data := builder.GetStruct(b).(selectData) + return data.toSqlRaw() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b SelectBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// Prefix adds an expression to the beginning of the query +func (b SelectBuilder) Prefix(sql string, args ...interface{}) SelectBuilder { + return b.PrefixExpr(Expr(sql, args...)) +} + +// PrefixExpr adds an expression to the very beginning of the query +func (b SelectBuilder) PrefixExpr(expr Sqlizer) SelectBuilder { + return builder.Append(b, "Prefixes", expr).(SelectBuilder) +} + +// Distinct adds a DISTINCT clause to the query. +func (b SelectBuilder) Distinct() SelectBuilder { + return b.Options("DISTINCT") +} + +// Options adds select option to the query +func (b SelectBuilder) Options(options ...string) SelectBuilder { + return builder.Extend(b, "Options", options).(SelectBuilder) +} + +// Columns adds result columns to the query. +func (b SelectBuilder) Columns(columns ...string) SelectBuilder { + parts := make([]interface{}, 0, len(columns)) + for _, str := range columns { + parts = append(parts, newPart(str)) + } + return builder.Extend(b, "Columns", parts).(SelectBuilder) +} + +// RemoveColumns remove all columns from query. +// Must add a new column with Column or Columns methods, otherwise +// return a error. +func (b SelectBuilder) RemoveColumns() SelectBuilder { + return builder.Delete(b, "Columns").(SelectBuilder) +} + +// Column adds a result column to the query. +// Unlike Columns, Column accepts args which will be bound to placeholders in +// the columns string, for example: +// Column("IF(col IN ("+squirrel.Placeholders(3)+"), 1, 0) as col", 1, 2, 3) +func (b SelectBuilder) Column(column interface{}, args ...interface{}) SelectBuilder { + return builder.Append(b, "Columns", newPart(column, args...)).(SelectBuilder) +} + +// From sets the FROM clause of the query. +func (b SelectBuilder) From(from string) SelectBuilder { + return builder.Set(b, "From", newPart(from)).(SelectBuilder) +} + +// FromSelect sets a subquery into the FROM clause of the query. +func (b SelectBuilder) FromSelect(from SelectBuilder, alias string) SelectBuilder { + // Prevent misnumbered parameters in nested selects (#183). + from = from.PlaceholderFormat(Question) + return builder.Set(b, "From", Alias(from, alias)).(SelectBuilder) +} + +// JoinClause adds a join clause to the query. +func (b SelectBuilder) JoinClause(pred interface{}, args ...interface{}) SelectBuilder { + return builder.Append(b, "Joins", newPart(pred, args...)).(SelectBuilder) +} + +// Join adds a JOIN clause to the query. +func (b SelectBuilder) Join(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("JOIN "+join, rest...) +} + +// LeftJoin adds a LEFT JOIN clause to the query. +func (b SelectBuilder) LeftJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("LEFT JOIN "+join, rest...) +} + +// RightJoin adds a RIGHT JOIN clause to the query. +func (b SelectBuilder) RightJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("RIGHT JOIN "+join, rest...) +} + +// InnerJoin adds a INNER JOIN clause to the query. +func (b SelectBuilder) InnerJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("INNER JOIN "+join, rest...) +} + +// CrossJoin adds a CROSS JOIN clause to the query. +func (b SelectBuilder) CrossJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("CROSS JOIN "+join, rest...) +} + +// Where adds an expression to the WHERE clause of the query. +// +// Expressions are ANDed together in the generated SQL. +// +// Where accepts several types for its pred argument: +// +// nil OR "" - ignored. +// +// string - SQL expression. +// If the expression has SQL placeholders then a set of arguments must be passed +// as well, one for each placeholder. +// +// map[string]interface{} OR Eq - map of SQL expressions to values. Each key is +// transformed into an expression like " = ?", with the corresponding value +// bound to the placeholder. If the value is nil, the expression will be " +// IS NULL". If the value is an array or slice, the expression will be " IN +// (?,?,...)", with one placeholder for each item in the value. These expressions +// are ANDed together. +// +// Where will panic if pred isn't any of the above types. +func (b SelectBuilder) Where(pred interface{}, args ...interface{}) SelectBuilder { + if pred == nil || pred == "" { + return b + } + return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(SelectBuilder) +} + +// GroupBy adds GROUP BY expressions to the query. +func (b SelectBuilder) GroupBy(groupBys ...string) SelectBuilder { + return builder.Extend(b, "GroupBys", groupBys).(SelectBuilder) +} + +// Having adds an expression to the HAVING clause of the query. +// +// See Where. +func (b SelectBuilder) Having(pred interface{}, rest ...interface{}) SelectBuilder { + return builder.Append(b, "HavingParts", newWherePart(pred, rest...)).(SelectBuilder) +} + +// OrderByClause adds ORDER BY clause to the query. +func (b SelectBuilder) OrderByClause(pred interface{}, args ...interface{}) SelectBuilder { + return builder.Append(b, "OrderByParts", newPart(pred, args...)).(SelectBuilder) +} + +// OrderBy adds ORDER BY expressions to the query. +func (b SelectBuilder) OrderBy(orderBys ...string) SelectBuilder { + for _, orderBy := range orderBys { + b = b.OrderByClause(orderBy) + } + + return b +} + +// Limit sets a LIMIT clause on the query. +func (b SelectBuilder) Limit(limit uint64) SelectBuilder { + return builder.Set(b, "Limit", fmt.Sprintf("%d", limit)).(SelectBuilder) +} + +// Limit ALL allows to access all records with limit +func (b SelectBuilder) RemoveLimit() SelectBuilder { + return builder.Delete(b, "Limit").(SelectBuilder) +} + +// Offset sets a OFFSET clause on the query. +func (b SelectBuilder) Offset(offset uint64) SelectBuilder { + return builder.Set(b, "Offset", fmt.Sprintf("%d", offset)).(SelectBuilder) +} + +// RemoveOffset removes OFFSET clause. +func (b SelectBuilder) RemoveOffset() SelectBuilder { + return builder.Delete(b, "Offset").(SelectBuilder) +} + +// Suffix adds an expression to the end of the query +func (b SelectBuilder) Suffix(sql string, args ...interface{}) SelectBuilder { + return b.SuffixExpr(Expr(sql, args...)) +} + +// SuffixExpr adds an expression to the end of the query +func (b SelectBuilder) SuffixExpr(expr Sqlizer) SelectBuilder { + return builder.Append(b, "Suffixes", expr).(SelectBuilder) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/select_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/select_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..4c42c13f478965d0dbe206ccf7fbb8e347d726b3 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/select_ctx.go @@ -0,0 +1,69 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + + "github.com/lann/builder" +) + +func (d *selectData) ExecContext(ctx context.Context) (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(ExecerContext) + if !ok { + return nil, NoContextSupport + } + return ExecContextWith(ctx, ctxRunner, d) +} + +func (d *selectData) QueryContext(ctx context.Context) (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(QueryerContext) + if !ok { + return nil, NoContextSupport + } + return QueryContextWith(ctx, ctxRunner, d) +} + +func (d *selectData) QueryRowContext(ctx context.Context) RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRowerContext) + if !ok { + if _, ok := d.RunWith.(QueryerContext); !ok { + return &Row{err: RunnerNotQueryRunner} + } + return &Row{err: NoContextSupport} + } + return QueryRowContextWith(ctx, queryRower, d) +} + +// ExecContext builds and ExecContexts the query with the Runner set by RunWith. +func (b SelectBuilder) ExecContext(ctx context.Context) (sql.Result, error) { + data := builder.GetStruct(b).(selectData) + return data.ExecContext(ctx) +} + +// QueryContext builds and QueryContexts the query with the Runner set by RunWith. +func (b SelectBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) { + data := builder.GetStruct(b).(selectData) + return data.QueryContext(ctx) +} + +// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith. +func (b SelectBuilder) QueryRowContext(ctx context.Context) RowScanner { + data := builder.GetStruct(b).(selectData) + return data.QueryRowContext(ctx) +} + +// ScanContext is a shortcut for QueryRowContext().Scan. +func (b SelectBuilder) ScanContext(ctx context.Context, dest ...interface{}) error { + return b.QueryRowContext(ctx).Scan(dest...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/squirrel.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/squirrel.go new file mode 100644 index 0000000000000000000000000000000000000000..46d456eb620c09b20161711440ffbef0d091fafd --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/squirrel.go @@ -0,0 +1,183 @@ +// Package squirrel provides a fluent SQL generator. +// +// See https://github.com/Masterminds/squirrel for examples. +package squirrel + +import ( + "bytes" + "database/sql" + "fmt" + "strings" + + "github.com/lann/builder" +) + +// Sqlizer is the interface that wraps the ToSql method. +// +// ToSql returns a SQL representation of the Sqlizer, along with a slice of args +// as passed to e.g. database/sql.Exec. It can also return an error. +type Sqlizer interface { + ToSql() (string, []interface{}, error) +} + +// rawSqlizer is expected to do what Sqlizer does, but without finalizing placeholders. +// This is useful for nested queries. +type rawSqlizer interface { + toSqlRaw() (string, []interface{}, error) +} + +// Execer is the interface that wraps the Exec method. +// +// Exec executes the given query as implemented by database/sql.Exec. +type Execer interface { + Exec(query string, args ...interface{}) (sql.Result, error) +} + +// Queryer is the interface that wraps the Query method. +// +// Query executes the given query as implemented by database/sql.Query. +type Queryer interface { + Query(query string, args ...interface{}) (*sql.Rows, error) +} + +// QueryRower is the interface that wraps the QueryRow method. +// +// QueryRow executes the given query as implemented by database/sql.QueryRow. +type QueryRower interface { + QueryRow(query string, args ...interface{}) RowScanner +} + +// BaseRunner groups the Execer and Queryer interfaces. +type BaseRunner interface { + Execer + Queryer +} + +// Runner groups the Execer, Queryer, and QueryRower interfaces. +type Runner interface { + Execer + Queryer + QueryRower +} + +// WrapStdSql wraps a type implementing the standard SQL interface with methods that +// squirrel expects. +func WrapStdSql(stdSql StdSql) Runner { + return &stdsqlRunner{stdSql} +} + +// StdSql encompasses the standard methods of the *sql.DB type, and other types that +// wrap these methods. +type StdSql interface { + Query(string, ...interface{}) (*sql.Rows, error) + QueryRow(string, ...interface{}) *sql.Row + Exec(string, ...interface{}) (sql.Result, error) +} + +type stdsqlRunner struct { + StdSql +} + +func (r *stdsqlRunner) QueryRow(query string, args ...interface{}) RowScanner { + return r.StdSql.QueryRow(query, args...) +} + +func setRunWith(b interface{}, runner BaseRunner) interface{} { + switch r := runner.(type) { + case StdSqlCtx: + runner = WrapStdSqlCtx(r) + case StdSql: + runner = WrapStdSql(r) + } + return builder.Set(b, "RunWith", runner) +} + +// RunnerNotSet is returned by methods that need a Runner if it isn't set. +var RunnerNotSet = fmt.Errorf("cannot run; no Runner set (RunWith)") + +// RunnerNotQueryRunner is returned by QueryRow if the RunWith value doesn't implement QueryRower. +var RunnerNotQueryRunner = fmt.Errorf("cannot QueryRow; Runner is not a QueryRower") + +// ExecWith Execs the SQL returned by s with db. +func ExecWith(db Execer, s Sqlizer) (res sql.Result, err error) { + query, args, err := s.ToSql() + if err != nil { + return + } + return db.Exec(query, args...) +} + +// QueryWith Querys the SQL returned by s with db. +func QueryWith(db Queryer, s Sqlizer) (rows *sql.Rows, err error) { + query, args, err := s.ToSql() + if err != nil { + return + } + return db.Query(query, args...) +} + +// QueryRowWith QueryRows the SQL returned by s with db. +func QueryRowWith(db QueryRower, s Sqlizer) RowScanner { + query, args, err := s.ToSql() + return &Row{RowScanner: db.QueryRow(query, args...), err: err} +} + +// DebugSqlizer calls ToSql on s and shows the approximate SQL to be executed +// +// If ToSql returns an error, the result of this method will look like: +// "[ToSql error: %s]" or "[DebugSqlizer error: %s]" +// +// IMPORTANT: As its name suggests, this function should only be used for +// debugging. While the string result *might* be valid SQL, this function does +// not try very hard to ensure it. Additionally, executing the output of this +// function with any untrusted user input is certainly insecure. +func DebugSqlizer(s Sqlizer) string { + sql, args, err := s.ToSql() + if err != nil { + return fmt.Sprintf("[ToSql error: %s]", err) + } + + var placeholder string + downCast, ok := s.(placeholderDebugger) + if !ok { + placeholder = "?" + } else { + placeholder = downCast.debugPlaceholder() + } + // TODO: dedupe this with placeholder.go + buf := &bytes.Buffer{} + i := 0 + for { + p := strings.Index(sql, placeholder) + if p == -1 { + break + } + if len(sql[p:]) > 1 && sql[p:p+2] == "??" { // escape ?? => ? + buf.WriteString(sql[:p]) + buf.WriteString("?") + if len(sql[p:]) == 1 { + break + } + sql = sql[p+2:] + } else { + if i+1 > len(args) { + return fmt.Sprintf( + "[DebugSqlizer error: too many placeholders in %#v for %d args]", + sql, len(args)) + } + buf.WriteString(sql[:p]) + fmt.Fprintf(buf, "'%v'", args[i]) + // advance our sql string "cursor" beyond the arg we placed + sql = sql[p+1:] + i++ + } + } + if i < len(args) { + return fmt.Sprintf( + "[DebugSqlizer error: not enough placeholders in %#v for %d args]", + sql, len(args)) + } + // "append" any remaning sql that won't need interpolating + buf.WriteString(sql) + return buf.String() +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/squirrel_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/squirrel_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..c20148ad33c76cf86b64f4f0dd88f8a9f1c96dd7 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/squirrel_ctx.go @@ -0,0 +1,93 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + "errors" +) + +// NoContextSupport is returned if a db doesn't support Context. +var NoContextSupport = errors.New("DB does not support Context") + +// ExecerContext is the interface that wraps the ExecContext method. +// +// Exec executes the given query as implemented by database/sql.ExecContext. +type ExecerContext interface { + ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) +} + +// QueryerContext is the interface that wraps the QueryContext method. +// +// QueryContext executes the given query as implemented by database/sql.QueryContext. +type QueryerContext interface { + QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) +} + +// QueryRowerContext is the interface that wraps the QueryRowContext method. +// +// QueryRowContext executes the given query as implemented by database/sql.QueryRowContext. +type QueryRowerContext interface { + QueryRowContext(ctx context.Context, query string, args ...interface{}) RowScanner +} + +// RunnerContext groups the Runner interface, along with the Context versions of each of +// its methods +type RunnerContext interface { + Runner + QueryerContext + QueryRowerContext + ExecerContext +} + +// WrapStdSqlCtx wraps a type implementing the standard SQL interface plus the context +// versions of the methods with methods that squirrel expects. +func WrapStdSqlCtx(stdSqlCtx StdSqlCtx) RunnerContext { + return &stdsqlCtxRunner{stdSqlCtx} +} + +// StdSqlCtx encompasses the standard methods of the *sql.DB type, along with the Context +// versions of those methods, and other types that wrap these methods. +type StdSqlCtx interface { + StdSql + QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error) + QueryRowContext(context.Context, string, ...interface{}) *sql.Row + ExecContext(context.Context, string, ...interface{}) (sql.Result, error) +} + +type stdsqlCtxRunner struct { + StdSqlCtx +} + +func (r *stdsqlCtxRunner) QueryRow(query string, args ...interface{}) RowScanner { + return r.StdSqlCtx.QueryRow(query, args...) +} + +func (r *stdsqlCtxRunner) QueryRowContext(ctx context.Context, query string, args ...interface{}) RowScanner { + return r.StdSqlCtx.QueryRowContext(ctx, query, args...) +} + +// ExecContextWith ExecContexts the SQL returned by s with db. +func ExecContextWith(ctx context.Context, db ExecerContext, s Sqlizer) (res sql.Result, err error) { + query, args, err := s.ToSql() + if err != nil { + return + } + return db.ExecContext(ctx, query, args...) +} + +// QueryContextWith QueryContexts the SQL returned by s with db. +func QueryContextWith(ctx context.Context, db QueryerContext, s Sqlizer) (rows *sql.Rows, err error) { + query, args, err := s.ToSql() + if err != nil { + return + } + return db.QueryContext(ctx, query, args...) +} + +// QueryRowContextWith QueryRowContexts the SQL returned by s with db. +func QueryRowContextWith(ctx context.Context, db QueryRowerContext, s Sqlizer) RowScanner { + query, args, err := s.ToSql() + return &Row{RowScanner: db.QueryRowContext(ctx, query, args...), err: err} +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/statement.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/statement.go new file mode 100644 index 0000000000000000000000000000000000000000..9420c67f8e921e04876efea27bec4a5c5cd4921d --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/statement.go @@ -0,0 +1,104 @@ +package squirrel + +import "github.com/lann/builder" + +// StatementBuilderType is the type of StatementBuilder. +type StatementBuilderType builder.Builder + +// Select returns a SelectBuilder for this StatementBuilderType. +func (b StatementBuilderType) Select(columns ...string) SelectBuilder { + return SelectBuilder(b).Columns(columns...) +} + +// Insert returns a InsertBuilder for this StatementBuilderType. +func (b StatementBuilderType) Insert(into string) InsertBuilder { + return InsertBuilder(b).Into(into) +} + +// Replace returns a InsertBuilder for this StatementBuilderType with the +// statement keyword set to "REPLACE". +func (b StatementBuilderType) Replace(into string) InsertBuilder { + return InsertBuilder(b).statementKeyword("REPLACE").Into(into) +} + +// Update returns a UpdateBuilder for this StatementBuilderType. +func (b StatementBuilderType) Update(table string) UpdateBuilder { + return UpdateBuilder(b).Table(table) +} + +// Delete returns a DeleteBuilder for this StatementBuilderType. +func (b StatementBuilderType) Delete(from string) DeleteBuilder { + return DeleteBuilder(b).From(from) +} + +// PlaceholderFormat sets the PlaceholderFormat field for any child builders. +func (b StatementBuilderType) PlaceholderFormat(f PlaceholderFormat) StatementBuilderType { + return builder.Set(b, "PlaceholderFormat", f).(StatementBuilderType) +} + +// RunWith sets the RunWith field for any child builders. +func (b StatementBuilderType) RunWith(runner BaseRunner) StatementBuilderType { + return setRunWith(b, runner).(StatementBuilderType) +} + +// Where adds WHERE expressions to the query. +// +// See SelectBuilder.Where for more information. +func (b StatementBuilderType) Where(pred interface{}, args ...interface{}) StatementBuilderType { + return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(StatementBuilderType) +} + +// StatementBuilder is a parent builder for other builders, e.g. SelectBuilder. +var StatementBuilder = StatementBuilderType(builder.EmptyBuilder).PlaceholderFormat(Question) + +// Select returns a new SelectBuilder, optionally setting some result columns. +// +// See SelectBuilder.Columns. +func Select(columns ...string) SelectBuilder { + return StatementBuilder.Select(columns...) +} + +// Insert returns a new InsertBuilder with the given table name. +// +// See InsertBuilder.Into. +func Insert(into string) InsertBuilder { + return StatementBuilder.Insert(into) +} + +// Replace returns a new InsertBuilder with the statement keyword set to +// "REPLACE" and with the given table name. +// +// See InsertBuilder.Into. +func Replace(into string) InsertBuilder { + return StatementBuilder.Replace(into) +} + +// Update returns a new UpdateBuilder with the given table name. +// +// See UpdateBuilder.Table. +func Update(table string) UpdateBuilder { + return StatementBuilder.Update(table) +} + +// Delete returns a new DeleteBuilder with the given table name. +// +// See DeleteBuilder.Table. +func Delete(from string) DeleteBuilder { + return StatementBuilder.Delete(from) +} + +// Case returns a new CaseBuilder +// "what" represents case value +func Case(what ...interface{}) CaseBuilder { + b := CaseBuilder(builder.EmptyBuilder) + + switch len(what) { + case 0: + case 1: + b = b.what(what[0]) + default: + b = b.what(newPart(what[0], what[1:]...)) + + } + return b +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/stmtcacher.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/stmtcacher.go new file mode 100644 index 0000000000000000000000000000000000000000..5bf267a13642d0c6734cf013a6e631f6ca1f0bc6 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/stmtcacher.go @@ -0,0 +1,121 @@ +package squirrel + +import ( + "database/sql" + "fmt" + "sync" +) + +// Prepareer is the interface that wraps the Prepare method. +// +// Prepare executes the given query as implemented by database/sql.Prepare. +type Preparer interface { + Prepare(query string) (*sql.Stmt, error) +} + +// DBProxy groups the Execer, Queryer, QueryRower, and Preparer interfaces. +type DBProxy interface { + Execer + Queryer + QueryRower + Preparer +} + +// NOTE: NewStmtCache is defined in stmtcacher_ctx.go (Go >= 1.8) or stmtcacher_noctx.go (Go < 1.8). + +// StmtCache wraps and delegates down to a Preparer type +// +// It also automatically prepares all statements sent to the underlying Preparer calls +// for Exec, Query and QueryRow and caches the returns *sql.Stmt using the provided +// query as the key. So that it can be automatically re-used. +type StmtCache struct { + prep Preparer + cache map[string]*sql.Stmt + mu sync.Mutex +} + +// Prepare delegates down to the underlying Preparer and caches the result +// using the provided query as a key +func (sc *StmtCache) Prepare(query string) (*sql.Stmt, error) { + sc.mu.Lock() + defer sc.mu.Unlock() + + stmt, ok := sc.cache[query] + if ok { + return stmt, nil + } + stmt, err := sc.prep.Prepare(query) + if err == nil { + sc.cache[query] = stmt + } + return stmt, err +} + +// Exec delegates down to the underlying Preparer using a prepared statement +func (sc *StmtCache) Exec(query string, args ...interface{}) (res sql.Result, err error) { + stmt, err := sc.Prepare(query) + if err != nil { + return + } + return stmt.Exec(args...) +} + +// Query delegates down to the underlying Preparer using a prepared statement +func (sc *StmtCache) Query(query string, args ...interface{}) (rows *sql.Rows, err error) { + stmt, err := sc.Prepare(query) + if err != nil { + return + } + return stmt.Query(args...) +} + +// QueryRow delegates down to the underlying Preparer using a prepared statement +func (sc *StmtCache) QueryRow(query string, args ...interface{}) RowScanner { + stmt, err := sc.Prepare(query) + if err != nil { + return &Row{err: err} + } + return stmt.QueryRow(args...) +} + +// Clear removes and closes all the currently cached prepared statements +func (sc *StmtCache) Clear() (err error) { + sc.mu.Lock() + defer sc.mu.Unlock() + + for key, stmt := range sc.cache { + delete(sc.cache, key) + + if stmt == nil { + continue + } + + if cerr := stmt.Close(); cerr != nil { + err = cerr + } + } + + if err != nil { + return fmt.Errorf("one or more Stmt.Close failed; last error: %v", err) + } + + return +} + +type DBProxyBeginner interface { + DBProxy + Begin() (*sql.Tx, error) +} + +type stmtCacheProxy struct { + DBProxy + db *sql.DB +} + +func NewStmtCacheProxy(db *sql.DB) DBProxyBeginner { + return &stmtCacheProxy{DBProxy: NewStmtCache(db), db: db} +} + +func (sp *stmtCacheProxy) Begin() (*sql.Tx, error) { + return sp.db.Begin() +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/stmtcacher_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/stmtcacher_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..53603cf4c9548775644cbf2050a0d1f3c5150b73 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/stmtcacher_ctx.go @@ -0,0 +1,86 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" +) + +// PrepareerContext is the interface that wraps the Prepare and PrepareContext methods. +// +// Prepare executes the given query as implemented by database/sql.Prepare. +// PrepareContext executes the given query as implemented by database/sql.PrepareContext. +type PreparerContext interface { + Preparer + PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) +} + +// DBProxyContext groups the Execer, Queryer, QueryRower and PreparerContext interfaces. +type DBProxyContext interface { + Execer + Queryer + QueryRower + PreparerContext +} + +// NewStmtCache returns a *StmtCache wrapping a PreparerContext that caches Prepared Stmts. +// +// Stmts are cached based on the string value of their queries. +func NewStmtCache(prep PreparerContext) *StmtCache { + return &StmtCache{prep: prep, cache: make(map[string]*sql.Stmt)} +} + +// NewStmtCacher is deprecated +// +// Use NewStmtCache instead +func NewStmtCacher(prep PreparerContext) DBProxyContext { + return NewStmtCache(prep) +} + +// PrepareContext delegates down to the underlying PreparerContext and caches the result +// using the provided query as a key +func (sc *StmtCache) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) { + ctxPrep, ok := sc.prep.(PreparerContext) + if !ok { + return nil, NoContextSupport + } + sc.mu.Lock() + defer sc.mu.Unlock() + stmt, ok := sc.cache[query] + if ok { + return stmt, nil + } + stmt, err := ctxPrep.PrepareContext(ctx, query) + if err == nil { + sc.cache[query] = stmt + } + return stmt, err +} + +// ExecContext delegates down to the underlying PreparerContext using a prepared statement +func (sc *StmtCache) ExecContext(ctx context.Context, query string, args ...interface{}) (res sql.Result, err error) { + stmt, err := sc.PrepareContext(ctx, query) + if err != nil { + return + } + return stmt.ExecContext(ctx, args...) +} + +// QueryContext delegates down to the underlying PreparerContext using a prepared statement +func (sc *StmtCache) QueryContext(ctx context.Context, query string, args ...interface{}) (rows *sql.Rows, err error) { + stmt, err := sc.PrepareContext(ctx, query) + if err != nil { + return + } + return stmt.QueryContext(ctx, args...) +} + +// QueryRowContext delegates down to the underlying PreparerContext using a prepared statement +func (sc *StmtCache) QueryRowContext(ctx context.Context, query string, args ...interface{}) RowScanner { + stmt, err := sc.PrepareContext(ctx, query) + if err != nil { + return &Row{err: err} + } + return stmt.QueryRowContext(ctx, args...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/stmtcacher_noctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/stmtcacher_noctx.go new file mode 100644 index 0000000000000000000000000000000000000000..deac96777b7fd51ea468b9861b76571b1aa433bf --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/stmtcacher_noctx.go @@ -0,0 +1,21 @@ +// +build !go1.8 + +package squirrel + +import ( + "database/sql" +) + +// NewStmtCacher returns a DBProxy wrapping prep that caches Prepared Stmts. +// +// Stmts are cached based on the string value of their queries. +func NewStmtCache(prep Preparer) *StmtCache { + return &StmtCacher{prep: prep, cache: make(map[string]*sql.Stmt)} +} + +// NewStmtCacher is deprecated +// +// Use NewStmtCache instead +func NewStmtCacher(prep Preparer) DBProxy { + return NewStmtCache(prep) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/update.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/update.go new file mode 100644 index 0000000000000000000000000000000000000000..eb2a9c4dd9a07b893bbea241526d84c84acdc30a --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/update.go @@ -0,0 +1,288 @@ +package squirrel + +import ( + "bytes" + "database/sql" + "fmt" + "sort" + "strings" + + "github.com/lann/builder" +) + +type updateData struct { + PlaceholderFormat PlaceholderFormat + RunWith BaseRunner + Prefixes []Sqlizer + Table string + SetClauses []setClause + From Sqlizer + WhereParts []Sqlizer + OrderBys []string + Limit string + Offset string + Suffixes []Sqlizer +} + +type setClause struct { + column string + value interface{} +} + +func (d *updateData) Exec() (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return ExecWith(d.RunWith, d) +} + +func (d *updateData) Query() (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return QueryWith(d.RunWith, d) +} + +func (d *updateData) QueryRow() RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRower) + if !ok { + return &Row{err: RunnerNotQueryRunner} + } + return QueryRowWith(queryRower, d) +} + +func (d *updateData) ToSql() (sqlStr string, args []interface{}, err error) { + if len(d.Table) == 0 { + err = fmt.Errorf("update statements must specify a table") + return + } + if len(d.SetClauses) == 0 { + err = fmt.Errorf("update statements must have at least one Set clause") + return + } + + sql := &bytes.Buffer{} + + if len(d.Prefixes) > 0 { + args, err = appendToSql(d.Prefixes, sql, " ", args) + if err != nil { + return + } + + sql.WriteString(" ") + } + + sql.WriteString("UPDATE ") + sql.WriteString(d.Table) + + sql.WriteString(" SET ") + setSqls := make([]string, len(d.SetClauses)) + for i, setClause := range d.SetClauses { + var valSql string + if vs, ok := setClause.value.(Sqlizer); ok { + vsql, vargs, err := vs.ToSql() + if err != nil { + return "", nil, err + } + if _, ok := vs.(SelectBuilder); ok { + valSql = fmt.Sprintf("(%s)", vsql) + } else { + valSql = vsql + } + args = append(args, vargs...) + } else { + valSql = "?" + args = append(args, setClause.value) + } + setSqls[i] = fmt.Sprintf("%s = %s", setClause.column, valSql) + } + sql.WriteString(strings.Join(setSqls, ", ")) + + if d.From != nil { + sql.WriteString(" FROM ") + args, err = appendToSql([]Sqlizer{d.From}, sql, "", args) + if err != nil { + return + } + } + + if len(d.WhereParts) > 0 { + sql.WriteString(" WHERE ") + args, err = appendToSql(d.WhereParts, sql, " AND ", args) + if err != nil { + return + } + } + + if len(d.OrderBys) > 0 { + sql.WriteString(" ORDER BY ") + sql.WriteString(strings.Join(d.OrderBys, ", ")) + } + + if len(d.Limit) > 0 { + sql.WriteString(" LIMIT ") + sql.WriteString(d.Limit) + } + + if len(d.Offset) > 0 { + sql.WriteString(" OFFSET ") + sql.WriteString(d.Offset) + } + + if len(d.Suffixes) > 0 { + sql.WriteString(" ") + args, err = appendToSql(d.Suffixes, sql, " ", args) + if err != nil { + return + } + } + + sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sql.String()) + return +} + +// Builder + +// UpdateBuilder builds SQL UPDATE statements. +type UpdateBuilder builder.Builder + +func init() { + builder.Register(UpdateBuilder{}, updateData{}) +} + +// Format methods + +// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the +// query. +func (b UpdateBuilder) PlaceholderFormat(f PlaceholderFormat) UpdateBuilder { + return builder.Set(b, "PlaceholderFormat", f).(UpdateBuilder) +} + +// Runner methods + +// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec. +func (b UpdateBuilder) RunWith(runner BaseRunner) UpdateBuilder { + return setRunWith(b, runner).(UpdateBuilder) +} + +// Exec builds and Execs the query with the Runner set by RunWith. +func (b UpdateBuilder) Exec() (sql.Result, error) { + data := builder.GetStruct(b).(updateData) + return data.Exec() +} + +func (b UpdateBuilder) Query() (*sql.Rows, error) { + data := builder.GetStruct(b).(updateData) + return data.Query() +} + +func (b UpdateBuilder) QueryRow() RowScanner { + data := builder.GetStruct(b).(updateData) + return data.QueryRow() +} + +func (b UpdateBuilder) Scan(dest ...interface{}) error { + return b.QueryRow().Scan(dest...) +} + +// SQL methods + +// ToSql builds the query into a SQL string and bound args. +func (b UpdateBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(updateData) + return data.ToSql() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b UpdateBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// Prefix adds an expression to the beginning of the query +func (b UpdateBuilder) Prefix(sql string, args ...interface{}) UpdateBuilder { + return b.PrefixExpr(Expr(sql, args...)) +} + +// PrefixExpr adds an expression to the very beginning of the query +func (b UpdateBuilder) PrefixExpr(expr Sqlizer) UpdateBuilder { + return builder.Append(b, "Prefixes", expr).(UpdateBuilder) +} + +// Table sets the table to be updated. +func (b UpdateBuilder) Table(table string) UpdateBuilder { + return builder.Set(b, "Table", table).(UpdateBuilder) +} + +// Set adds SET clauses to the query. +func (b UpdateBuilder) Set(column string, value interface{}) UpdateBuilder { + return builder.Append(b, "SetClauses", setClause{column: column, value: value}).(UpdateBuilder) +} + +// SetMap is a convenience method which calls .Set for each key/value pair in clauses. +func (b UpdateBuilder) SetMap(clauses map[string]interface{}) UpdateBuilder { + keys := make([]string, len(clauses)) + i := 0 + for key := range clauses { + keys[i] = key + i++ + } + sort.Strings(keys) + for _, key := range keys { + val, _ := clauses[key] + b = b.Set(key, val) + } + return b +} + +// From adds FROM clause to the query +// FROM is valid construct in postgresql only. +func (b UpdateBuilder) From(from string) UpdateBuilder { + return builder.Set(b, "From", newPart(from)).(UpdateBuilder) +} + +// FromSelect sets a subquery into the FROM clause of the query. +func (b UpdateBuilder) FromSelect(from SelectBuilder, alias string) UpdateBuilder { + // Prevent misnumbered parameters in nested selects (#183). + from = from.PlaceholderFormat(Question) + return builder.Set(b, "From", Alias(from, alias)).(UpdateBuilder) +} + +// Where adds WHERE expressions to the query. +// +// See SelectBuilder.Where for more information. +func (b UpdateBuilder) Where(pred interface{}, args ...interface{}) UpdateBuilder { + return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(UpdateBuilder) +} + +// OrderBy adds ORDER BY expressions to the query. +func (b UpdateBuilder) OrderBy(orderBys ...string) UpdateBuilder { + return builder.Extend(b, "OrderBys", orderBys).(UpdateBuilder) +} + +// Limit sets a LIMIT clause on the query. +func (b UpdateBuilder) Limit(limit uint64) UpdateBuilder { + return builder.Set(b, "Limit", fmt.Sprintf("%d", limit)).(UpdateBuilder) +} + +// Offset sets a OFFSET clause on the query. +func (b UpdateBuilder) Offset(offset uint64) UpdateBuilder { + return builder.Set(b, "Offset", fmt.Sprintf("%d", offset)).(UpdateBuilder) +} + +// Suffix adds an expression to the end of the query +func (b UpdateBuilder) Suffix(sql string, args ...interface{}) UpdateBuilder { + return b.SuffixExpr(Expr(sql, args...)) +} + +// SuffixExpr adds an expression to the end of the query +func (b UpdateBuilder) SuffixExpr(expr Sqlizer) UpdateBuilder { + return builder.Append(b, "Suffixes", expr).(UpdateBuilder) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/update_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/update_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..ad479f96f49fd0f02da2f3ea44f0392f451ec5d5 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/update_ctx.go @@ -0,0 +1,69 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + + "github.com/lann/builder" +) + +func (d *updateData) ExecContext(ctx context.Context) (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(ExecerContext) + if !ok { + return nil, NoContextSupport + } + return ExecContextWith(ctx, ctxRunner, d) +} + +func (d *updateData) QueryContext(ctx context.Context) (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(QueryerContext) + if !ok { + return nil, NoContextSupport + } + return QueryContextWith(ctx, ctxRunner, d) +} + +func (d *updateData) QueryRowContext(ctx context.Context) RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRowerContext) + if !ok { + if _, ok := d.RunWith.(QueryerContext); !ok { + return &Row{err: RunnerNotQueryRunner} + } + return &Row{err: NoContextSupport} + } + return QueryRowContextWith(ctx, queryRower, d) +} + +// ExecContext builds and ExecContexts the query with the Runner set by RunWith. +func (b UpdateBuilder) ExecContext(ctx context.Context) (sql.Result, error) { + data := builder.GetStruct(b).(updateData) + return data.ExecContext(ctx) +} + +// QueryContext builds and QueryContexts the query with the Runner set by RunWith. +func (b UpdateBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) { + data := builder.GetStruct(b).(updateData) + return data.QueryContext(ctx) +} + +// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith. +func (b UpdateBuilder) QueryRowContext(ctx context.Context) RowScanner { + data := builder.GetStruct(b).(updateData) + return data.QueryRowContext(ctx) +} + +// ScanContext is a shortcut for QueryRowContext().Scan. +func (b UpdateBuilder) ScanContext(ctx context.Context, dest ...interface{}) error { + return b.QueryRowContext(ctx).Scan(dest...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/where.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/where.go new file mode 100644 index 0000000000000000000000000000000000000000..976b63ace4ecb4452f5326b1893067bb604d133e --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/environment/source/where.go @@ -0,0 +1,30 @@ +package squirrel + +import ( + "fmt" +) + +type wherePart part + +func newWherePart(pred interface{}, args ...interface{}) Sqlizer { + return &wherePart{pred: pred, args: args} +} + +func (p wherePart) ToSql() (sql string, args []interface{}, err error) { + switch pred := p.pred.(type) { + case nil: + // no-op + case rawSqlizer: + return pred.toSqlRaw() + case Sqlizer: + return pred.ToSql() + case map[string]interface{}: + return Eq(pred).ToSql() + case string: + sql = pred + args = p.args + default: + err = fmt.Errorf("expected string-keyed map or string, not %T", pred) + } + return +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/instruction.md b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9585eae0e79dabc0714aeba2db6f2083f6f90865 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/instruction.md @@ -0,0 +1,55 @@ +Empty Eq map generates incorrect SQL + +When using an empty `Eq` map in WHERE clauses, the generated SQL is incorrect. Instead of evaluating to true (which should be the case for an empty condition map), it's generating `(1=1)` in all cases. + +#### Steps to Reproduce + +```go +package main + +import ( + "fmt" + "github.com/Masterminds/squirrel" +) + +func main() { + // Empty Eq should generate proper SQL + eq := squirrel.Eq{} + sql, args, err := eq.ToSql() + if err != nil { + panic(err) + } + + fmt.Printf("SQL: %s\n", sql) + fmt.Printf("Args: %v\n", args) + + // This should generate "id = ?" but generates "(1=1)" instead + eq2 := squirrel.Eq{"id": 1} + sql2, args2, err2 := eq2.ToSql() + if err2 != nil { + panic(err2) + } + + fmt.Printf("SQL2: %s\n", sql2) + fmt.Printf("Args2: %v\n", args2) +} +``` + +Expected output: +``` +SQL: (1=1) +Args: [] +SQL2: id = ? +Args2: [1] +``` + +Actual output: +``` +SQL: (1=1) +Args: [] +SQL2: (1=1) +Args2: [] +``` + +The issue affects WHERE clause generation in SELECT, UPDATE, and DELETE queries where `Eq` maps are used as conditions. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/provenance.json b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..313ec09cfb95c704b6d0e741e30668df39129119 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/provenance.json @@ -0,0 +1,395 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "original-bug": "task-specific unchanged semantic bug", + "partial-repair": "strict partial repair candidate with independently unproven wrongness", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "acceptance_disposition": "needs_semantic_review; may be a legitimate alternative; do not cherry-pick another canary from measured rewards", + "candidate_file_inventory": { + "expr.go": { + "mode": "0o644", + "sha256": "598eab9d5581e7c19e522780427d789e5c486205c6576cffcb3946e3c7fb8519", + "size": 9216 + } + }, + "expected_wrongness": "unproven until independent semantic review", + "original_patch_hunks": 4, + "original_patch_sha256": "f28250058b30d866e78d43c6cc4703e66e2677b6385752985aa0e29cd87e61ee", + "retained_mutation_file": "expr.go", + "retained_mutation_hunk_sha256": "bc7764375ea5b8f53c10fb6d0c3850a6e545e17144cbee9f95e7e86166229680" + }, + "private_frozen_files": { + "case_test.go": { + "mode": "0o644", + "sha256": "fdb8c60761dc1ab02953e86f1736bd29e644e61bb7f67a394a5f71d276a67298", + "size": 3296 + }, + "delete_ctx_test.go": { + "mode": "0o644", + "sha256": "07e5cd531fbc380655a6f441eeee23da925195d67a1a7e7682785806af51014e", + "size": 847 + }, + "delete_test.go": { + "mode": "0o644", + "sha256": "44ac247a59eb89cd5f41e3f0948a78e51e757d0888a72874d12a12c6db1acfb0", + "size": 1806 + }, + "expr_test.go": { + "mode": "0o644", + "sha256": "ab52b68e40a81bda968dacc733f34c08626f299405450c383daf438e33897a65", + "size": 10245 + }, + "insert_ctx_test.go": { + "mode": "0o644", + "sha256": "b3e3efaf75fee82c147958afb70a90334f4f08cf29b64bd76d23a03b9824f299", + "size": 807 + }, + "insert_test.go": { + "mode": "0o644", + "sha256": "665fe6694c9ce48b2bcbdfd34ab9bde67d8fd7601b3d5798f4dacd693e1da278", + "size": 2627 + }, + "integration/integration_test.go": { + "mode": "0o644", + "sha256": "c8631b72fa30417861d7ba87a1a9a5c0883d01744fb49bf779360dc4a61b9abf", + "size": 3162 + }, + "placeholder_test.go": { + "mode": "0o644", + "sha256": "c498900e8f98d981e90863f0603d19c11db17e786eae008bdc5af2b25ae8eb13", + "size": 2005 + }, + "row_test.go": { + "mode": "0o644", + "sha256": "7fe834ce33424df8e009fa44ee5acea25508c7e439d1bf07fddf6d4c90e77ec1", + "size": 626 + }, + "select_ctx_test.go": { + "mode": "0o644", + "sha256": "560d37ac028fbf92ba5c5a20b95af7d866a4fbdecd0e868b6fe266eb4849e665", + "size": 771 + }, + "select_test.go": { + "mode": "0o644", + "sha256": "3b06e89b5c358992a7165414dbeb4643820d95574981359638d609931d528630", + "size": 12209 + }, + "squirrel_ctx_test.go": { + "mode": "0o644", + "sha256": "4a052ae48d428a0719777189c407e5d5c7087550c0d99b2c28cceada083f76b0", + "size": 1277 + }, + "squirrel_test.go": { + "mode": "0o644", + "sha256": "7336a2ffda333c52c145d76e926a89e1244ff24b96c86abfc6fe06723572180f", + "size": 5780 + }, + "statement_test.go": { + "mode": "0o644", + "sha256": "a0f46fa71157b09eaca3da0fa6a75b25156cb552c785228836b0ffbb9fe5ac27", + "size": 2072 + }, + "stmtcacher_ctx_test.go": { + "mode": "0o644", + "sha256": "a0a1f49a87ebb6b35b8d66fbe9051d8a9f94346eaf5e3cd70719424433f5c878", + "size": 402 + }, + "stmtcacher_test.go": { + "mode": "0o644", + "sha256": "e5b5020ac3c194cf92121100a24df580955f32f89bd600b1e56014702d24eb52", + "size": 546 + }, + "update_ctx_test.go": { + "mode": "0o644", + "sha256": "3dd7bd0c17bfb61fad6e71c7736ca6a207f811ae7c3f92f8185c5f7d32dbf30a", + "size": 805 + }, + "update_test.go": { + "mode": "0o644", + "sha256": "6316c8d144c647d9c7bdd6b8be4490c40398da03d331be23c4729faa7a57aa4e", + "size": 2836 + }, + "where_test.go": { + "mode": "0o644", + "sha256": "1a53006a294c379a8b7f212b340acf9063ea0b613062a52fc9585a7d84f853f3", + "size": 1325 + } + }, + "public_files": { + ".gitignore": { + "mode": "0o644", + "sha256": "1eaa1ee4d30ac564ac002a67650eff426807e1fd8b9475250d0ef31ee3d458dd", + "size": 13 + }, + ".travis.yml": { + "mode": "0o644", + "sha256": "5409f254b7fc2f4ed3afcdc45ac2346acedadf2689e14f5d4735e5587cd31a15", + "size": 768 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "11ac92da622d8d25df663d4bc5d12f464da1a98a9fbb75930e0e65cc58b80a2f", + "size": 1185 + }, + "README.md": { + "mode": "0o644", + "sha256": "f1dafb8f66d5eb204201e34fbcf50a08180b7cc6fffb9cd87ed55673d840afc2", + "size": 4363 + }, + "case.go": { + "mode": "0o644", + "sha256": "9c530c0585dcf3c1f12200afecbc2147edbdc18a2369f726486ebc169bfdb1f1", + "size": 3065 + }, + "delete.go": { + "mode": "0o644", + "sha256": "700cefe533a6d939aaa689dfcbf148ad8d4b07f0278337944ecc37767479b3eb", + "size": 4806 + }, + "delete_ctx.go": { + "mode": "0o644", + "sha256": "0fb7da25c0bee63500317da43e1d8bcb5b8d62487ec80e6298135953d62b03f4", + "size": 1908 + }, + "expr.go": { + "mode": "0o644", + "sha256": "1e4aa9fbb01d8095d15023b45bd7e5f9989da4fe9cb269537e0bd5db1f16f650", + "size": 9216 + }, + "go.mod": { + "mode": "0o644", + "sha256": "b4c6f216eafab7a1ca5209b5ddca006529666f72184aea72293395c69f7140f5", + "size": 321 + }, + "go.sum": { + "mode": "0o644", + "sha256": "2b4fe7850b36f8effe69d037ed1219df62399e4076034930b8f3d2edb7fa46fd", + "size": 953 + }, + "insert.go": { + "mode": "0o644", + "sha256": "626ac9dd6c5cbca5e9e3b93252d82c94d6d6b63ddc967fb0dbcee0f3dc889c2e", + "size": 7710 + }, + "insert_ctx.go": { + "mode": "0o644", + "sha256": "6f72f9fd2e5e3b9e60f65f1fcf920ba6724242784ba26b9e0924aa8a0667d8b2", + "size": 1908 + }, + "integration/doc.go": { + "mode": "0o644", + "sha256": "2eb5edda1be28404e1f6681d1177cd3f447f8167cacf51f817b853e578e5996c", + "size": 53 + }, + "integration/go.mod": { + "mode": "0o644", + "sha256": "b8f745640b55a496faf7e8ffe39dcbb223bd4a856c108f38cb5021c5c9fafc3b", + "size": 347 + }, + "integration/go.sum": { + "mode": "0o644", + "sha256": "30892c107aa863abb8105816d7f6fa497ec69fd1d6783f4f186a19ff0fe6df80", + "size": 3122 + }, + "part.go": { + "mode": "0o644", + "sha256": "5fb7ec420cb4f4eff065b0a71e073b8ac74a1a6a81647d19b490be9286bc2258", + "size": 1149 + }, + "placeholder.go": { + "mode": "0o644", + "sha256": "246a7219eb14597fa9322bac44691e6ff6f7437df8cf7e4f7fe15c263ce61114", + "size": 2558 + }, + "row.go": { + "mode": "0o644", + "sha256": "089fb1c058ccf2f6664c0cdaac097ad6616e5ec0b44939429bce737d70d9c50e", + "size": 472 + }, + "select.go": { + "mode": "0o644", + "sha256": "28ab9e3d2a9772d6e0ef08f4fa83ea1ccd4a246f086e0e9431a10e5d42504d33", + "size": 11320 + }, + "select_ctx.go": { + "mode": "0o644", + "sha256": "ac68ccbb975d46547f21be70d802af6f4de4ac4c41d9e26a925621e725d74787", + "size": 1908 + }, + "squirrel.go": { + "mode": "0o644", + "sha256": "a5d827d66fdd080a5f2efaccb74fca217265e995d667cf10a026dbc2871e70f9", + "size": 5074 + }, + "squirrel_ctx.go": { + "mode": "0o644", + "sha256": "2e903ebfb7941cb8f68100dc9c500b5bfb214ea8534aaa21e4ea7ed01a70085d", + "size": 3085 + }, + "statement.go": { + "mode": "0o644", + "sha256": "f6cbf3d520fe88614795a68113ea020dd9ad3977e9dcd42af6e0a48a906d2caa", + "size": 3254 + }, + "stmtcacher.go": { + "mode": "0o644", + "sha256": "8f1593570472ec435e653b16a331262629495915b8cf2fda9929e6c7fe0a3c5a", + "size": 2799 + }, + "stmtcacher_ctx.go": { + "mode": "0o644", + "sha256": "e0c02cbf487302ea082afa304b851c454ece0d85f7073c721afb9e5a9e32f7fc", + "size": 2550 + }, + "stmtcacher_noctx.go": { + "mode": "0o644", + "sha256": "14539e8754cc3ee236d7f8af2e0176fb5a8c6183d73ad0e797913ae51a400b22", + "size": 459 + }, + "update.go": { + "mode": "0o644", + "sha256": "0d9f5f030b6d4e31f21f2b84fa6f62df1cc0eb540a7fa04eb9ec68c2ed238e0a", + "size": 7349 + }, + "update_ctx.go": { + "mode": "0o644", + "sha256": "517c4436ea62524889f3a50339d1d3c3ee89ff23050eecaf5fa3a973b8ec4bf0", + "size": 1908 + }, + "where.go": { + "mode": "0o644", + "sha256": "555836c5dd84cbd7571b5e2b3b5b677f3fcd4cc42a0f1cfb3a176f8909bd0755", + "size": 572 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:8397c903899921169852f4bff3ee17f23d7d4f8eaf03854a2bffd0051a2b363f", + "os": "linux", + "sha256": "8397c903899921169852f4bff3ee17f23d7d4f8eaf03854a2bffd0051a2b363f" + }, + "context_inventory_sha256": "8c63f6649adee8ca9a2290a98a9a180d45b9f65f42395812e6e97b409186f81d", + "image": "registry.hf.space/harness-hub-scale800-go-055c69f17f410bee-starter-v1@sha256:9dfb6b7417f54d78d50e6e6bdd951b854ed8da8f5f1782f4fe563a85e1cd0b7a", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "dc294274d204bc3953b3ddc9f385c54f9ded95ae55c720729f3b4765c2561bba", + "receipt_path": "production/runtime-images-extra-v1/resolutions/055c69f17f410bee/resolution.json", + "receipt_sha256": "741436358af5538a7e21351cbe2660ca3aeb440246407b654888e4766be1dc7a", + "registry_digest": "sha256:9dfb6b7417f54d78d50e6e6bdd951b854ed8da8f5f1782f4fe563a85e1cd0b7a", + "source_image": "docker.io/swebench/swesmith.x86_64.masterminds_1776_squirrel.1ded5784@sha256:8b7a7b2f6acd11416e98a5254735925f3e354c9a85634e37a1f9a347ad82ed22", + "source_receipt_sha256": "6be66b515dc9ca98b38e89389e4b485f038418a7591cd99ca1294782042078a3", + "space_commit": "4520e0fbd0db51041911578a6d2b53e5493f8b5a", + "space_id": "harness-hub/scale800-go-055c69f17f410bee-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "4a2f7b79d0f1e9228a597101d41b7ac3f507fdbd1341a108dac701fe128c238c", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21", + "source_proof_sha256": "338824517a6f5577df13311662249cfbf185e58542572bc46bcd2cefad50809b", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0", + "cloud_launch_ready": false, + "healthy_mirror_commit": "ecf2598064d7f630d661d9a03e6cab204d37eeb8", + "instruction_sha256": "e57d2132e29c4859022fa5c9682553f7fcf4b05eaf7f4fc6e858738d5882d500", + "is_fork": true, + "learner_path": "tasks/291e43155072beb9d3f5fc55/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "11ac92da622d8d25df663d4bc5d12f464da1a98a9fbb75930e0e65cc58b80a2f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/Masterminds__squirrel.1ded5784/6ab105238a430c7c63c0c965863d41d6f671a32a/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "1ded5784535dcffa4e175d4efbd1ca2706927758", + "patch_sha256": "f28250058b30d866e78d43c6cc4703e66e2677b6385752985aa0e29cd87e61ee", + "provenance_path": "tasks/291e43155072beb9d3f5fc55/source-proof.json", + "repository_lineage": [ + "swesmith/Masterminds__squirrel.1ded5784", + "Masterminds/squirrel" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "6ab105238a430c7c63c0c965863d41d6f671a32a", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "8eff330d8d0b4b01e4429d1edeb7d1a8706788e9", + "source_kind": "mutation", + "source_repo": "swesmith/Masterminds__squirrel.1ded5784", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0", + "task_sha256": "5f11b2ba62b57b225254b9e9b6621dc5b4b5566a6907d676adb28ac9453e7a3f", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "Masterminds/squirrel", + "usage": "quarantine_only" + }, + "source_row_sha256": "8e3c13003c23ed44e080753f3f954748e060ce571a0ad4192931c97abc5c2c73", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.gitignore", + "/testbed/.travis.yml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/case.go", + "/testbed/delete.go", + "/testbed/delete_ctx.go", + "/testbed/expr.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/insert.go", + "/testbed/insert_ctx.go", + "/testbed/integration/doc.go", + "/testbed/integration/go.mod", + "/testbed/integration/go.sum", + "/testbed/part.go", + "/testbed/placeholder.go", + "/testbed/row.go", + "/testbed/select.go", + "/testbed/select_ctx.go", + "/testbed/squirrel.go", + "/testbed/squirrel_ctx.go", + "/testbed/statement.go", + "/testbed/stmtcacher.go", + "/testbed/stmtcacher_ctx.go", + "/testbed/stmtcacher_noctx.go", + "/testbed/update.go", + "/testbed/update_ctx.go", + "/testbed/where.go" + ] +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/solution/solve.sh b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b179142682d0ef93734940913db02535d28d8711 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"expr.go": {"data": "cGFja2FnZSBzcXVpcnJlbAoKaW1wb3J0ICgKCSJieXRlcyIKCSJkYXRhYmFzZS9zcWwvZHJpdmVyIgoJImZtdCIKCSJyZWZsZWN0IgoJInNvcnQiCgkic3RyaW5ncyIKKQoKY29uc3QgKAoJLy8gUG9ydGFibGUgdHJ1ZS9mYWxzZSBsaXRlcmFscy4KCXNxbFRydWUgID0gIigxPTEpIgoJc3FsRmFsc2UgPSAiKDE9MCkiCikKCnR5cGUgZXhwciBzdHJ1Y3QgewoJc3FsICBzdHJpbmcKCWFyZ3MgW11pbnRlcmZhY2V7fQp9CgovLyBFeHByIGJ1aWxkcyBhbiBleHByZXNzaW9uIGZyb20gYSBTUUwgZnJhZ21lbnQgYW5kIGFyZ3VtZW50cy4KLy8KLy8gRXg6Ci8vICAgICBFeHByKCJGUk9NX1VOSVhUSU1FKD8pIiwgdCkKZnVuYyBFeHByKHNxbCBzdHJpbmcsIGFyZ3MgLi4uaW50ZXJmYWNle30pIFNxbGl6ZXIgewoJcmV0dXJuIGV4cHJ7c3FsOiBzcWwsIGFyZ3M6IGFyZ3N9Cn0KCmZ1bmMgKGUgZXhwcikgVG9TcWwoKSAoc3FsIHN0cmluZywgYXJncyBbXWludGVyZmFjZXt9LCBlcnIgZXJyb3IpIHsKCXNpbXBsZSA6PSB0cnVlCglmb3IgXywgYXJnIDo9IHJhbmdlIGUuYXJncyB7CgkJaWYgXywgb2sgOj0gYXJnLihTcWxpemVyKTsgb2sgewoJCQlzaW1wbGUgPSBmYWxzZQoJCX0KCX0KCWlmIHNpbXBsZSB7CgkJcmV0dXJuIGUuc3FsLCBlLmFyZ3MsIG5pbAoJfQoKCWJ1ZiA6PSAmYnl0ZXMuQnVmZmVye30KCWFwIDo9IGUuYXJncwoJc3AgOj0gZS5zcWwKCgl2YXIgaXNxbCBzdHJpbmcKCXZhciBpYXJncyBbXWludGVyZmFjZXt9CgoJZm9yIGVyciA9PSBuaWwgJiYgbGVuKGFwKSA+IDAgJiYgbGVuKHNwKSA+IDAgewoJCWkgOj0gc3RyaW5ncy5JbmRleChzcCwgIj8iKQoJCWlmIGkgPCAwIHsKCQkJLy8gbm8gbW9yZSBwbGFjZWhvbGRlcnMKCQkJYnJlYWsKCQl9CgkJaWYgbGVuKHNwKSA+IGkrMSAmJiBzcFtpKzE6aSsyXSA9PSAiPyIgewoJCQkvLyBlc2NhcGVkICI/PyI7IGFwcGVuZCBpdCBhbmQgc3RlcCBwYXN0CgkJCWJ1Zi5Xcml0ZVN0cmluZyhzcFs6aSsyXSkKCQkJc3AgPSBzcFtpKzI6XQoJCQljb250aW51ZQoJCX0KCgkJaWYgYXMsIG9rIDo9IGFwWzBdLihTcWxpemVyKTsgb2sgewoJCQkvLyBzcWxpemVyIGFyZ3VtZW50OyBleHBhbmQgaXQgYW5kIGFwcGVuZCB0aGUgcmVzdWx0CgkJCWlzcWwsIGlhcmdzLCBlcnIgPSBhcy5Ub1NxbCgpCgkJCWJ1Zi5Xcml0ZVN0cmluZyhzcFs6aV0pCgkJCWJ1Zi5Xcml0ZVN0cmluZyhpc3FsKQoJCQlhcmdzID0gYXBwZW5kKGFyZ3MsIGlhcmdzLi4uKQoJCX0gZWxzZSB7CgkJCS8vIG5vcm1hbCBhcmd1bWVudDsgYXBwZW5kIGl0IGFuZCB0aGUgcGxhY2Vob2xkZXIKCQkJYnVmLldyaXRlU3RyaW5nKHNwWzppKzFdKQoJCQlhcmdzID0gYXBwZW5kKGFyZ3MsIGFwWzBdKQoJCX0KCgkJLy8gc3RlcCBwYXN0IHRoZSBhcmd1bWVudCBhbmQgcGxhY2Vob2xkZXIKCQlhcCA9IGFwWzE6XQoJCXNwID0gc3BbaSsxOl0KCX0KCgkvLyBhcHBlbmQgdGhlIHJlbWFpbmluZyBzcWwgYW5kIGFyZ3VtZW50cwoJYnVmLldyaXRlU3RyaW5nKHNwKQoJcmV0dXJuIGJ1Zi5TdHJpbmcoKSwgYXBwZW5kKGFyZ3MsIGFwLi4uKSwgZXJyCn0KCnR5cGUgY29uY2F0RXhwciBbXWludGVyZmFjZXt9CgpmdW5jIChjZSBjb25jYXRFeHByKSBUb1NxbCgpIChzcWwgc3RyaW5nLCBhcmdzIFtdaW50ZXJmYWNle30sIGVyciBlcnJvcikgewoJZm9yIF8sIHBhcnQgOj0gcmFuZ2UgY2UgewoJCXN3aXRjaCBwIDo9IHBhcnQuKHR5cGUpIHsKCQljYXNlIHN0cmluZzoKCQkJc3FsICs9IHAKCQljYXNlIFNxbGl6ZXI6CgkJCXBTcWwsIHBBcmdzLCBlcnIgOj0gcC5Ub1NxbCgpCgkJCWlmIGVyciAhPSBuaWwgewoJCQkJcmV0dXJuICIiLCBuaWwsIGVycgoJCQl9CgkJCXNxbCArPSBwU3FsCgkJCWFyZ3MgPSBhcHBlbmQoYXJncywgcEFyZ3MuLi4pCgkJZGVmYXVsdDoKCQkJcmV0dXJuICIiLCBuaWwsIGZtdC5FcnJvcmYoIiUjdiBpcyBub3QgYSBzdHJpbmcgb3IgU3FsaXplciIsIHBhcnQpCgkJfQoJfQoJcmV0dXJuCn0KCi8vIENvbmNhdEV4cHIgYnVpbGRzIGFuIGV4cHJlc3Npb24gYnkgY29uY2F0ZW5hdGluZyBzdHJpbmdzIGFuZCBvdGhlciBleHByZXNzaW9ucy4KLy8KLy8gRXg6Ci8vICAgICBuYW1lX2V4cHIgOj0gRXhwcigiQ09OQ0FUKD8sICcgJywgPykiLCBmaXJzdE5hbWUsIGxhc3ROYW1lKQovLyAgICAgQ29uY2F0RXhwcigiQ09BTEVTQ0UoZnVsbF9uYW1lLCIsIG5hbWVfZXhwciwgIikiKQpmdW5jIENvbmNhdEV4cHIocGFydHMgLi4uaW50ZXJmYWNle30pIGNvbmNhdEV4cHIgewoJcmV0dXJuIGNvbmNhdEV4cHIocGFydHMpCn0KCi8vIGFsaWFzRXhwciBoZWxwcyB0byBhbGlhcyBwYXJ0IG9mIFNRTCBxdWVyeSBnZW5lcmF0ZWQgd2l0aCB1bmRlcmx5aW5nICJleHByIgp0eXBlIGFsaWFzRXhwciBzdHJ1Y3QgewoJZXhwciAgU3FsaXplcgoJYWxpYXMgc3RyaW5nCn0KCi8vIEFsaWFzIGFsbG93cyB0byBkZWZpbmUgYWxpYXMgZm9yIGNvbHVtbiBpbiBTZWxlY3RCdWlsZGVyLiBVc2VmdWwgd2hlbiBjb2x1bW4gaXMKLy8gZGVmaW5lZCBhcyBjb21wbGV4IGV4cHJlc3Npb24gbGlrZSBJRiBvciBDQVNFCi8vIEV4OgovLwkJLkNvbHVtbihBbGlhcyhjYXNlU3RtdCwgImNhc2VfY29sdW1uIikpCmZ1bmMgQWxpYXMoZXhwciBTcWxpemVyLCBhbGlhcyBzdHJpbmcpIGFsaWFzRXhwciB7CglyZXR1cm4gYWxpYXNFeHBye2V4cHIsIGFsaWFzfQp9CgpmdW5jIChlIGFsaWFzRXhwcikgVG9TcWwoKSAoc3FsIHN0cmluZywgYXJncyBbXWludGVyZmFjZXt9LCBlcnIgZXJyb3IpIHsKCXNxbCwgYXJncywgZXJyID0gZS5leHByLlRvU3FsKCkKCWlmIGVyciA9PSBuaWwgewoJCXNxbCA9IGZtdC5TcHJpbnRmKCIoJXMpIEFTICVzIiwgc3FsLCBlLmFsaWFzKQoJfQoJcmV0dXJuCn0KCi8vIEVxIGlzIHN5bnRhY3RpYyBzdWdhciBmb3IgdXNlIHdpdGggV2hlcmUvSGF2aW5nL1NldCBtZXRob2RzLgp0eXBlIEVxIG1hcFtzdHJpbmddaW50ZXJmYWNle30KCmZ1bmMgKGVxIEVxKSB0b1NRTCh1c2VOb3RPcHIgYm9vbCkgKHNxbCBzdHJpbmcsIGFyZ3MgW11pbnRlcmZhY2V7fSwgZXJyIGVycm9yKSB7CglpZiBsZW4oZXEpID09IDAgewoJCS8vIEVtcHR5IFNxbHt9IGV2YWx1YXRlcyB0byB0cnVlLgoJCXNxbCA9IHNxbFRydWUKCQlyZXR1cm4KCX0KCgl2YXIgKAoJCWV4cHJzICAgICAgIFtdc3RyaW5nCgkJZXF1YWxPcHIgICAgPSAiPSIKCQlpbk9wciAgICAgICA9ICJJTiIKCQludWxsT3ByICAgICA9ICJJUyIKCQlpbkVtcHR5RXhwciA9IHNxbEZhbHNlCgkpCgoJaWYgdXNlTm90T3ByIHsKCQllcXVhbE9wciA9ICI8PiIKCQlpbk9wciA9ICJOT1QgSU4iCgkJbnVsbE9wciA9ICJJUyBOT1QiCgkJaW5FbXB0eUV4cHIgPSBzcWxUcnVlCgl9CgoJc29ydGVkS2V5cyA6PSBnZXRTb3J0ZWRLZXlzKGVxKQoJZm9yIF8sIGtleSA6PSByYW5nZSBzb3J0ZWRLZXlzIHsKCQl2YXIgZXhwciBzdHJpbmcKCQl2YWwgOj0gZXFba2V5XQoKCQlzd2l0Y2ggdiA6PSB2YWwuKHR5cGUpIHsKCQljYXNlIGRyaXZlci5WYWx1ZXI6CgkJCWlmIHZhbCwgZXJyID0gdi5WYWx1ZSgpOyBlcnIgIT0gbmlsIHsKCQkJCXJldHVybgoJCQl9CgkJfQoKCQlyIDo9IHJlZmxlY3QuVmFsdWVPZih2YWwpCgkJaWYgci5LaW5kKCkgPT0gcmVmbGVjdC5QdHIgewoJCQlpZiByLklzTmlsKCkgewoJCQkJdmFsID0gbmlsCgkJCX0gZWxzZSB7CgkJCQl2YWwgPSByLkVsZW0oKS5JbnRlcmZhY2UoKQoJCQl9CgkJfQoKCQlpZiB2YWwgPT0gbmlsIHsKCQkJZXhwciA9IGZtdC5TcHJpbnRmKCIlcyAlcyBOVUxMIiwga2V5LCBudWxsT3ByKQoJCX0gZWxzZSB7CgkJCWlmIGlzTGlzdFR5cGUodmFsKSB7CgkJCQl2YWxWYWwgOj0gcmVmbGVjdC5WYWx1ZU9mKHZhbCkKCQkJCWlmIHZhbFZhbC5MZW4oKSA9PSAwIHsKCQkJCQlleHByID0gaW5FbXB0eUV4cHIKCQkJCQlpZiBhcmdzID09IG5pbCB7CgkJCQkJCWFyZ3MgPSBbXWludGVyZmFjZXt9e30KCQkJCQl9CgkJCQl9IGVsc2UgewoJCQkJCWZvciBpIDo9IDA7IGkgPCB2YWxWYWwuTGVuKCk7IGkrKyB7CgkJCQkJCWFyZ3MgPSBhcHBlbmQoYXJncywgdmFsVmFsLkluZGV4KGkpLkludGVyZmFjZSgpKQoJCQkJCX0KCQkJCQlleHByID0gZm10LlNwcmludGYoIiVzICVzICglcykiLCBrZXksIGluT3ByLCBQbGFjZWhvbGRlcnModmFsVmFsLkxlbigpKSkKCQkJCX0KCQkJfSBlbHNlIHsKCQkJCWV4cHIgPSBmbXQuU3ByaW50ZigiJXMgJXMgPyIsIGtleSwgZXF1YWxPcHIpCgkJCQlhcmdzID0gYXBwZW5kKGFyZ3MsIHZhbCkKCQkJfQoJCX0KCQlleHBycyA9IGFwcGVuZChleHBycywgZXhwcikKCX0KCXNxbCA9IHN0cmluZ3MuSm9pbihleHBycywgIiBBTkQgIikKCXJldHVybgp9CgpmdW5jIChlcSBFcSkgVG9TcWwoKSAoc3FsIHN0cmluZywgYXJncyBbXWludGVyZmFjZXt9LCBlcnIgZXJyb3IpIHsKCXJldHVybiBlcS50b1NRTChmYWxzZSkKfQoKLy8gTm90RXEgaXMgc3ludGFjdGljIHN1Z2FyIGZvciB1c2Ugd2l0aCBXaGVyZS9IYXZpbmcvU2V0IG1ldGhvZHMuCi8vIEV4OgovLyAgICAgLldoZXJlKE5vdEVxeyJpZCI6IDF9KSA9PSAiaWQgPD4gMSIKdHlwZSBOb3RFcSBFcQoKZnVuYyAobmVxIE5vdEVxKSBUb1NxbCgpIChzcWwgc3RyaW5nLCBhcmdzIFtdaW50ZXJmYWNle30sIGVyciBlcnJvcikgewoJcmV0dXJuIEVxKG5lcSkudG9TUUwodHJ1ZSkKfQoKLy8gTGlrZSBpcyBzeW50YWN0aWMgc3VnYXIgZm9yIHVzZSB3aXRoIExJS0UgY29uZGl0aW9ucy4KLy8gRXg6Ci8vICAgICAuV2hlcmUoTGlrZXsibmFtZSI6ICIlaXJyZWwifSkKdHlwZSBMaWtlIG1hcFtzdHJpbmddaW50ZXJmYWNle30KCmZ1bmMgKGxrIExpa2UpIHRvU3FsKG9wciBzdHJpbmcpIChzcWwgc3RyaW5nLCBhcmdzIFtdaW50ZXJmYWNle30sIGVyciBlcnJvcikgewoJdmFyIGV4cHJzIFtdc3RyaW5nCglmb3Iga2V5LCB2YWwgOj0gcmFuZ2UgbGsgewoJCWV4cHIgOj0gIiIKCgkJc3dpdGNoIHYgOj0gdmFsLih0eXBlKSB7CgkJY2FzZSBkcml2ZXIuVmFsdWVyOgoJCQlpZiB2YWwsIGVyciA9IHYuVmFsdWUoKTsgZXJyICE9IG5pbCB7CgkJCQlyZXR1cm4KCQkJfQoJCX0KCgkJaWYgdmFsID09IG5pbCB7CgkJCWVyciA9IGZtdC5FcnJvcmYoImNhbm5vdCB1c2UgbnVsbCB3aXRoIGxpa2Ugb3BlcmF0b3JzIikKCQkJcmV0dXJuCgkJfSBlbHNlIHsKCQkJaWYgaXNMaXN0VHlwZSh2YWwpIHsKCQkJCWVyciA9IGZtdC5FcnJvcmYoImNhbm5vdCB1c2UgYXJyYXkgb3Igc2xpY2Ugd2l0aCBsaWtlIG9wZXJhdG9ycyIpCgkJCQlyZXR1cm4KCQkJfSBlbHNlIHsKCQkJCWV4cHIgPSBmbXQuU3ByaW50ZigiJXMgJXMgPyIsIGtleSwgb3ByKQoJCQkJYXJncyA9IGFwcGVuZChhcmdzLCB2YWwpCgkJCX0KCQl9CgkJZXhwcnMgPSBhcHBlbmQoZXhwcnMsIGV4cHIpCgl9CglzcWwgPSBzdHJpbmdzLkpvaW4oZXhwcnMsICIgQU5EICIpCglyZXR1cm4KfQoKZnVuYyAobGsgTGlrZSkgVG9TcWwoKSAoc3FsIHN0cmluZywgYXJncyBbXWludGVyZmFjZXt9LCBlcnIgZXJyb3IpIHsKCXJldHVybiBsay50b1NxbCgiTElLRSIpCn0KCi8vIE5vdExpa2UgaXMgc3ludGFjdGljIHN1Z2FyIGZvciB1c2Ugd2l0aCBMSUtFIGNvbmRpdGlvbnMuCi8vIEV4OgovLyAgICAgLldoZXJlKE5vdExpa2V7Im5hbWUiOiAiJWlycmVsIn0pCnR5cGUgTm90TGlrZSBMaWtlCgpmdW5jIChubGsgTm90TGlrZSkgVG9TcWwoKSAoc3FsIHN0cmluZywgYXJncyBbXWludGVyZmFjZXt9LCBlcnIgZXJyb3IpIHsKCXJldHVybiBMaWtlKG5saykudG9TcWwoIk5PVCBMSUtFIikKfQoKLy8gSUxpa2UgaXMgc3ludGFjdGljIHN1Z2FyIGZvciB1c2Ugd2l0aCBJTElLRSBjb25kaXRpb25zLgovLyBFeDoKLy8gICAgLldoZXJlKElMaWtleyJuYW1lIjogInNxJSJ9KQp0eXBlIElMaWtlIExpa2UKCmZ1bmMgKGlsayBJTGlrZSkgVG9TcWwoKSAoc3FsIHN0cmluZywgYXJncyBbXWludGVyZmFjZXt9LCBlcnIgZXJyb3IpIHsKCXJldHVybiBMaWtlKGlsaykudG9TcWwoIklMSUtFIikKfQoKLy8gTm90SUxpa2UgaXMgc3ludGFjdGljIHN1Z2FyIGZvciB1c2Ugd2l0aCBJTElLRSBjb25kaXRpb25zLgovLyBFeDoKLy8gICAgLldoZXJlKE5vdElMaWtleyJuYW1lIjogInNxJSJ9KQp0eXBlIE5vdElMaWtlIExpa2UKCmZ1bmMgKG5pbGsgTm90SUxpa2UpIFRvU3FsKCkgKHNxbCBzdHJpbmcsIGFyZ3MgW11pbnRlcmZhY2V7fSwgZXJyIGVycm9yKSB7CglyZXR1cm4gTGlrZShuaWxrKS50b1NxbCgiTk9UIElMSUtFIikKfQoKLy8gTHQgaXMgc3ludGFjdGljIHN1Z2FyIGZvciB1c2Ugd2l0aCBXaGVyZS9IYXZpbmcvU2V0IG1ldGhvZHMuCi8vIEV4OgovLyAgICAgLldoZXJlKEx0eyJpZCI6IDF9KQp0eXBlIEx0IG1hcFtzdHJpbmddaW50ZXJmYWNle30KCmZ1bmMgKGx0IEx0KSB0b1NxbChvcHBvc2l0ZSwgb3JFcSBib29sKSAoc3FsIHN0cmluZywgYXJncyBbXWludGVyZmFjZXt9LCBlcnIgZXJyb3IpIHsKCXZhciAoCgkJZXhwcnMgW11zdHJpbmcKCQlvcHIgICA9ICI8IgoJKQoKCWlmIG9wcG9zaXRlIHsKCQlvcHIgPSAiPiIKCX0KCglpZiBvckVxIHsKCQlvcHIgPSBmbXQuU3ByaW50ZigiJXMlcyIsIG9wciwgIj0iKQoJfQoKCXNvcnRlZEtleXMgOj0gZ2V0U29ydGVkS2V5cyhsdCkKCWZvciBfLCBrZXkgOj0gcmFuZ2Ugc29ydGVkS2V5cyB7CgkJdmFyIGV4cHIgc3RyaW5nCgkJdmFsIDo9IGx0W2tleV0KCgkJc3dpdGNoIHYgOj0gdmFsLih0eXBlKSB7CgkJY2FzZSBkcml2ZXIuVmFsdWVyOgoJCQlpZiB2YWwsIGVyciA9IHYuVmFsdWUoKTsgZXJyICE9IG5pbCB7CgkJCQlyZXR1cm4KCQkJfQoJCX0KCgkJaWYgdmFsID09IG5pbCB7CgkJCWVyciA9IGZtdC5FcnJvcmYoImNhbm5vdCB1c2UgbnVsbCB3aXRoIGxlc3MgdGhhbiBvciBncmVhdGVyIHRoYW4gb3BlcmF0b3JzIikKCQkJcmV0dXJuCgkJfQoJCWlmIGlzTGlzdFR5cGUodmFsKSB7CgkJCWVyciA9IGZtdC5FcnJvcmYoImNhbm5vdCB1c2UgYXJyYXkgb3Igc2xpY2Ugd2l0aCBsZXNzIHRoYW4gb3IgZ3JlYXRlciB0aGFuIG9wZXJhdG9ycyIpCgkJCXJldHVybgoJCX0KCQlleHByID0gZm10LlNwcmludGYoIiVzICVzID8iLCBrZXksIG9wcikKCQlhcmdzID0gYXBwZW5kKGFyZ3MsIHZhbCkKCgkJZXhwcnMgPSBhcHBlbmQoZXhwcnMsIGV4cHIpCgl9CglzcWwgPSBzdHJpbmdzLkpvaW4oZXhwcnMsICIgQU5EICIpCglyZXR1cm4KfQoKZnVuYyAobHQgTHQpIFRvU3FsKCkgKHNxbCBzdHJpbmcsIGFyZ3MgW11pbnRlcmZhY2V7fSwgZXJyIGVycm9yKSB7CglyZXR1cm4gbHQudG9TcWwoZmFsc2UsIGZhbHNlKQp9CgovLyBMdE9yRXEgaXMgc3ludGFjdGljIHN1Z2FyIGZvciB1c2Ugd2l0aCBXaGVyZS9IYXZpbmcvU2V0IG1ldGhvZHMuCi8vIEV4OgovLyAgICAgLldoZXJlKEx0T3JFcXsiaWQiOiAxfSkgPT0gImlkIDw9IDEiCnR5cGUgTHRPckVxIEx0CgpmdW5jIChsdE9yRXEgTHRPckVxKSBUb1NxbCgpIChzcWwgc3RyaW5nLCBhcmdzIFtdaW50ZXJmYWNle30sIGVyciBlcnJvcikgewoJcmV0dXJuIEx0KGx0T3JFcSkudG9TcWwoZmFsc2UsIHRydWUpCn0KCi8vIEd0IGlzIHN5bnRhY3RpYyBzdWdhciBmb3IgdXNlIHdpdGggV2hlcmUvSGF2aW5nL1NldCBtZXRob2RzLgovLyBFeDoKLy8gICAgIC5XaGVyZShHdHsiaWQiOiAxfSkgPT0gImlkID4gMSIKdHlwZSBHdCBMdAoKZnVuYyAoZ3QgR3QpIFRvU3FsKCkgKHNxbCBzdHJpbmcsIGFyZ3MgW11pbnRlcmZhY2V7fSwgZXJyIGVycm9yKSB7CglyZXR1cm4gTHQoZ3QpLnRvU3FsKHRydWUsIGZhbHNlKQp9CgovLyBHdE9yRXEgaXMgc3ludGFjdGljIHN1Z2FyIGZvciB1c2Ugd2l0aCBXaGVyZS9IYXZpbmcvU2V0IG1ldGhvZHMuCi8vIEV4OgovLyAgICAgLldoZXJlKEd0T3JFcXsiaWQiOiAxfSkgPT0gImlkID49IDEiCnR5cGUgR3RPckVxIEx0CgpmdW5jIChndE9yRXEgR3RPckVxKSBUb1NxbCgpIChzcWwgc3RyaW5nLCBhcmdzIFtdaW50ZXJmYWNle30sIGVyciBlcnJvcikgewoJcmV0dXJuIEx0KGd0T3JFcSkudG9TcWwodHJ1ZSwgdHJ1ZSkKfQoKdHlwZSBjb25qIFtdU3FsaXplcgoKZnVuYyAoYyBjb25qKSBqb2luKHNlcCwgZGVmYXVsdEV4cHIgc3RyaW5nKSAoc3FsIHN0cmluZywgYXJncyBbXWludGVyZmFjZXt9LCBlcnIgZXJyb3IpIHsKCWlmIGxlbihjKSA9PSAwIHsKCQlyZXR1cm4gZGVmYXVsdEV4cHIsIFtdaW50ZXJmYWNle317fSwgbmlsCgl9Cgl2YXIgc3FsUGFydHMgW11zdHJpbmcKCWZvciBfLCBzcWxpemVyIDo9IHJhbmdlIGMgewoJCXBhcnRTUUwsIHBhcnRBcmdzLCBlcnIgOj0gbmVzdGVkVG9TcWwoc3FsaXplcikKCQlpZiBlcnIgIT0gbmlsIHsKCQkJcmV0dXJuICIiLCBuaWwsIGVycgoJCX0KCQlpZiBwYXJ0U1FMICE9ICIiIHsKCQkJc3FsUGFydHMgPSBhcHBlbmQoc3FsUGFydHMsIHBhcnRTUUwpCgkJCWFyZ3MgPSBhcHBlbmQoYXJncywgcGFydEFyZ3MuLi4pCgkJfQoJfQoJaWYgbGVuKHNxbFBhcnRzKSA+IDAgewoJCXNxbCA9IGZtdC5TcHJpbnRmKCIoJXMpIiwgc3RyaW5ncy5Kb2luKHNxbFBhcnRzLCBzZXApKQoJfQoJcmV0dXJuCn0KCi8vIEFuZCBjb25qdW5jdGlvbiBTcWxpemVycwp0eXBlIEFuZCBjb25qCgpmdW5jIChhIEFuZCkgVG9TcWwoKSAoc3RyaW5nLCBbXWludGVyZmFjZXt9LCBlcnJvcikgewoJcmV0dXJuIGNvbmooYSkuam9pbigiIEFORCAiLCBzcWxUcnVlKQp9CgovLyBPciBjb25qdW5jdGlvbiBTcWxpemVycwp0eXBlIE9yIGNvbmoKCmZ1bmMgKG8gT3IpIFRvU3FsKCkgKHN0cmluZywgW11pbnRlcmZhY2V7fSwgZXJyb3IpIHsKCXJldHVybiBjb25qKG8pLmpvaW4oIiBPUiAiLCBzcWxGYWxzZSkKfQoKZnVuYyBnZXRTb3J0ZWRLZXlzKGV4cCBtYXBbc3RyaW5nXWludGVyZmFjZXt9KSBbXXN0cmluZyB7Cglzb3J0ZWRLZXlzIDo9IG1ha2UoW11zdHJpbmcsIDAsIGxlbihleHApKQoJZm9yIGsgOj0gcmFuZ2UgZXhwIHsKCQlzb3J0ZWRLZXlzID0gYXBwZW5kKHNvcnRlZEtleXMsIGspCgl9Cglzb3J0LlN0cmluZ3Moc29ydGVkS2V5cykKCXJldHVybiBzb3J0ZWRLZXlzCn0KCmZ1bmMgaXNMaXN0VHlwZSh2YWwgaW50ZXJmYWNle30pIGJvb2wgewoJaWYgZHJpdmVyLklzVmFsdWUodmFsKSB7CgkJcmV0dXJuIGZhbHNlCgl9Cgl2YWxWYWwgOj0gcmVmbGVjdC5WYWx1ZU9mKHZhbCkKCXJldHVybiB2YWxWYWwuS2luZCgpID09IHJlZmxlY3QuQXJyYXkgfHwgdmFsVmFsLktpbmQoKSA9PSByZWZsZWN0LlNsaWNlCn0K", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/task.toml b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4e15fc5dcf313c085420f65afbefed6ee9e8911d --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:ffced1b89dc491d3343ed314c474028a0ba42b86febf3e2025d29df47946cfa7" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/case_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/case_test.go new file mode 100644 index 0000000000000000000000000000000000000000..a2ad995cfe6d0bb71f0755c70268592ff94d8a1f --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/case_test.go @@ -0,0 +1,150 @@ +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestCaseWithVal(t *testing.T) { + caseStmt := Case("number"). + When("1", "one"). + When("2", "two"). + Else(Expr("?", "big number")) + + qb := Select(). + Column(caseStmt). + From("table") + sql, args, err := qb.ToSql() + + assert.NoError(t, err) + + expectedSql := "SELECT CASE number " + + "WHEN 1 THEN one " + + "WHEN 2 THEN two " + + "ELSE ? " + + "END " + + "FROM table" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"big number"} + assert.Equal(t, expectedArgs, args) +} + +func TestCaseWithComplexVal(t *testing.T) { + caseStmt := Case("? > ?", 10, 5). + When("true", "'T'") + + qb := Select(). + Column(Alias(caseStmt, "complexCase")). + From("table") + sql, args, err := qb.ToSql() + + assert.NoError(t, err) + + expectedSql := "SELECT (CASE ? > ? " + + "WHEN true THEN 'T' " + + "END) AS complexCase " + + "FROM table" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{10, 5} + assert.Equal(t, expectedArgs, args) +} + +func TestCaseWithNoVal(t *testing.T) { + caseStmt := Case(). + When(Eq{"x": 0}, "x is zero"). + When(Expr("x > ?", 1), Expr("CONCAT('x is greater than ', ?)", 2)) + + qb := Select().Column(caseStmt).From("table") + sql, args, err := qb.ToSql() + + assert.NoError(t, err) + + expectedSql := "SELECT CASE " + + "WHEN x = ? THEN x is zero " + + "WHEN x > ? THEN CONCAT('x is greater than ', ?) " + + "END " + + "FROM table" + + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{0, 1, 2} + assert.Equal(t, expectedArgs, args) +} + +func TestCaseWithExpr(t *testing.T) { + caseStmt := Case(Expr("x = ?", true)). + When("true", Expr("?", "it's true!")). + Else("42") + + qb := Select().Column(caseStmt).From("table") + sql, args, err := qb.ToSql() + + assert.NoError(t, err) + + expectedSql := "SELECT CASE x = ? " + + "WHEN true THEN ? " + + "ELSE 42 " + + "END " + + "FROM table" + + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{true, "it's true!"} + assert.Equal(t, expectedArgs, args) +} + +func TestMultipleCase(t *testing.T) { + caseStmtNoval := Case(Expr("x = ?", true)). + When("true", Expr("?", "it's true!")). + Else("42") + caseStmtExpr := Case(). + When(Eq{"x": 0}, "'x is zero'"). + When(Expr("x > ?", 1), Expr("CONCAT('x is greater than ', ?)", 2)) + + qb := Select(). + Column(Alias(caseStmtNoval, "case_noval")). + Column(Alias(caseStmtExpr, "case_expr")). + From("table") + + sql, args, err := qb.ToSql() + + assert.NoError(t, err) + + expectedSql := "SELECT " + + "(CASE x = ? WHEN true THEN ? ELSE 42 END) AS case_noval, " + + "(CASE WHEN x = ? THEN 'x is zero' WHEN x > ? THEN CONCAT('x is greater than ', ?) END) AS case_expr " + + "FROM table" + + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{ + true, "it's true!", + 0, 1, 2, + } + assert.Equal(t, expectedArgs, args) +} + +func TestCaseWithNoWhenClause(t *testing.T) { + caseStmt := Case("something"). + Else("42") + + qb := Select().Column(caseStmt).From("table") + + _, _, err := qb.ToSql() + + assert.Error(t, err) + + assert.Equal(t, "case expression must contain at lease one WHEN clause", err.Error()) +} + +func TestCaseBuilderMustSql(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("TestCaseBuilderMustSql should have panicked!") + } + }() + Case("").MustSql() +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/delete_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/delete_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..8a80b6ae502df4301a54a067896c7e31143ed427 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/delete_ctx_test.go @@ -0,0 +1,41 @@ +// +build go1.8 + +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestDeleteBuilderContextRunners(t *testing.T) { + db := &DBStub{} + b := Delete("test").Where("x = ?", 1).RunWith(db) + + expectedSql := "DELETE FROM test WHERE x = ?" + + b.ExecContext(ctx) + assert.Equal(t, expectedSql, db.LastExecSql) + + b.QueryContext(ctx) + assert.Equal(t, expectedSql, db.LastQuerySql) + + b.QueryRowContext(ctx) + assert.Equal(t, expectedSql, db.LastQueryRowSql) + + err := b.ScanContext(ctx) + assert.NoError(t, err) +} + +func TestDeleteBuilderContextNoRunner(t *testing.T) { + b := Delete("test").Where("x != ?", 0).Suffix("RETURNING x") + + _, err := b.ExecContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + _, err = b.QueryContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + err = b.ScanContext(ctx) + assert.Equal(t, RunnerNotSet, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/delete_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/delete_test.go new file mode 100644 index 0000000000000000000000000000000000000000..62691f246f11a751ec289bb34ad80bbca2d47313 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/delete_test.go @@ -0,0 +1,81 @@ +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestDeleteBuilderToSql(t *testing.T) { + b := Delete(""). + Prefix("WITH prefix AS ?", 0). + From("a"). + Where("b = ?", 1). + OrderBy("c"). + Limit(2). + Offset(3). + Suffix("RETURNING ?", 4) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := + "WITH prefix AS ? " + + "DELETE FROM a WHERE b = ? ORDER BY c LIMIT 2 OFFSET 3 " + + "RETURNING ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{0, 1, 4} + assert.Equal(t, expectedArgs, args) +} + +func TestDeleteBuilderToSqlErr(t *testing.T) { + _, _, err := Delete("").ToSql() + assert.Error(t, err) +} + +func TestDeleteBuilderMustSql(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("TestDeleteBuilderMustSql should have panicked!") + } + }() + Delete("").MustSql() +} + +func TestDeleteBuilderPlaceholders(t *testing.T) { + b := Delete("test").Where("x = ? AND y = ?", 1, 2) + + sql, _, _ := b.PlaceholderFormat(Question).ToSql() + assert.Equal(t, "DELETE FROM test WHERE x = ? AND y = ?", sql) + + sql, _, _ = b.PlaceholderFormat(Dollar).ToSql() + assert.Equal(t, "DELETE FROM test WHERE x = $1 AND y = $2", sql) +} + +func TestDeleteBuilderRunners(t *testing.T) { + db := &DBStub{} + b := Delete("test").Where("x = ?", 1).RunWith(db) + + expectedSql := "DELETE FROM test WHERE x = ?" + + b.Exec() + assert.Equal(t, expectedSql, db.LastExecSql) +} + +func TestDeleteBuilderNoRunner(t *testing.T) { + b := Delete("test") + + _, err := b.Exec() + assert.Equal(t, RunnerNotSet, err) +} + +func TestDeleteWithQuery(t *testing.T) { + db := &DBStub{} + b := Delete("test").Where("id=55").Suffix("RETURNING path").RunWith(db) + + expectedSql := "DELETE FROM test WHERE id=55 RETURNING path" + b.Query() + + assert.Equal(t, expectedSql, db.LastQuerySql) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/expr_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/expr_test.go new file mode 100644 index 0000000000000000000000000000000000000000..60d2ae5cc3020d0d40b10e3b3042114fbac6ffb4 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/expr_test.go @@ -0,0 +1,464 @@ +package squirrel + +import ( + "database/sql" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestConcatExpr(t *testing.T) { + b := ConcatExpr("COALESCE(name,", Expr("CONCAT(?,' ',?)", "f", "l"), ")") + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "COALESCE(name,CONCAT(?,' ',?))" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"f", "l"} + assert.Equal(t, expectedArgs, args) +} + +func TestConcatExprBadType(t *testing.T) { + b := ConcatExpr("prefix", 123, "suffix") + _, _, err := b.ToSql() + assert.Error(t, err) + assert.Contains(t, err.Error(), "123 is not") +} + +func TestEqToSql(t *testing.T) { + b := Eq{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id = ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestEqEmptyToSql(t *testing.T) { + sql, args, err := Eq{}.ToSql() + assert.NoError(t, err) + + expectedSql := "(1=1)" + assert.Equal(t, expectedSql, sql) + assert.Empty(t, args) +} + +func TestEqInToSql(t *testing.T) { + b := Eq{"id": []int{1, 2, 3}} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id IN (?,?,?)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2, 3} + assert.Equal(t, expectedArgs, args) +} + +func TestNotEqToSql(t *testing.T) { + b := NotEq{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id <> ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestEqNotInToSql(t *testing.T) { + b := NotEq{"id": []int{1, 2, 3}} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id NOT IN (?,?,?)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2, 3} + assert.Equal(t, expectedArgs, args) +} + +func TestEqInEmptyToSql(t *testing.T) { + b := Eq{"id": []int{}} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "(1=0)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{} + assert.Equal(t, expectedArgs, args) +} + +func TestNotEqInEmptyToSql(t *testing.T) { + b := NotEq{"id": []int{}} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "(1=1)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{} + assert.Equal(t, expectedArgs, args) +} + +func TestEqBytesToSql(t *testing.T) { + b := Eq{"id": []byte("test")} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id = ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{[]byte("test")} + assert.Equal(t, expectedArgs, args) +} + +func TestLtToSql(t *testing.T) { + b := Lt{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id < ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestLtOrEqToSql(t *testing.T) { + b := LtOrEq{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id <= ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestGtToSql(t *testing.T) { + b := Gt{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id > ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestGtOrEqToSql(t *testing.T) { + b := GtOrEq{"id": 1} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "id >= ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestExprNilToSql(t *testing.T) { + var b Sqlizer + b = NotEq{"name": nil} + sql, args, err := b.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + + expectedSql := "name IS NOT NULL" + assert.Equal(t, expectedSql, sql) + + b = Eq{"name": nil} + sql, args, err = b.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + + expectedSql = "name IS NULL" + assert.Equal(t, expectedSql, sql) +} + +func TestNullTypeString(t *testing.T) { + var b Sqlizer + var name sql.NullString + + b = Eq{"name": name} + sql, args, err := b.ToSql() + + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "name IS NULL", sql) + + name.Scan("Name") + b = Eq{"name": name} + sql, args, err = b.ToSql() + + assert.NoError(t, err) + assert.Equal(t, []interface{}{"Name"}, args) + assert.Equal(t, "name = ?", sql) +} + +func TestNullTypeInt64(t *testing.T) { + var userID sql.NullInt64 + userID.Scan(nil) + b := Eq{"user_id": userID} + sql, args, err := b.ToSql() + + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "user_id IS NULL", sql) + + userID.Scan(int64(10)) + b = Eq{"user_id": userID} + sql, args, err = b.ToSql() + + assert.NoError(t, err) + assert.Equal(t, []interface{}{int64(10)}, args) + assert.Equal(t, "user_id = ?", sql) +} + +func TestNilPointer(t *testing.T) { + var name *string = nil + eq := Eq{"name": name} + sql, args, err := eq.ToSql() + + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "name IS NULL", sql) + + neq := NotEq{"name": name} + sql, args, err = neq.ToSql() + + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "name IS NOT NULL", sql) + + var ids *[]int = nil + eq = Eq{"id": ids} + sql, args, err = eq.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "id IS NULL", sql) + + neq = NotEq{"id": ids} + sql, args, err = neq.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "id IS NOT NULL", sql) + + var ida *[3]int = nil + eq = Eq{"id": ida} + sql, args, err = eq.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "id IS NULL", sql) + + neq = NotEq{"id": ida} + sql, args, err = neq.ToSql() + assert.NoError(t, err) + assert.Empty(t, args) + assert.Equal(t, "id IS NOT NULL", sql) + +} + +func TestNotNilPointer(t *testing.T) { + c := "Name" + name := &c + eq := Eq{"name": name} + sql, args, err := eq.ToSql() + + assert.NoError(t, err) + assert.Equal(t, []interface{}{"Name"}, args) + assert.Equal(t, "name = ?", sql) + + neq := NotEq{"name": name} + sql, args, err = neq.ToSql() + + assert.NoError(t, err) + assert.Equal(t, []interface{}{"Name"}, args) + assert.Equal(t, "name <> ?", sql) + + s := []int{1, 2, 3} + ids := &s + eq = Eq{"id": ids} + sql, args, err = eq.ToSql() + assert.NoError(t, err) + assert.Equal(t, []interface{}{1, 2, 3}, args) + assert.Equal(t, "id IN (?,?,?)", sql) + + neq = NotEq{"id": ids} + sql, args, err = neq.ToSql() + assert.NoError(t, err) + assert.Equal(t, []interface{}{1, 2, 3}, args) + assert.Equal(t, "id NOT IN (?,?,?)", sql) + + a := [3]int{1, 2, 3} + ida := &a + eq = Eq{"id": ida} + sql, args, err = eq.ToSql() + assert.NoError(t, err) + assert.Equal(t, []interface{}{1, 2, 3}, args) + assert.Equal(t, "id IN (?,?,?)", sql) + + neq = NotEq{"id": ida} + sql, args, err = neq.ToSql() + assert.NoError(t, err) + assert.Equal(t, []interface{}{1, 2, 3}, args) + assert.Equal(t, "id NOT IN (?,?,?)", sql) +} + +func TestEmptyAndToSql(t *testing.T) { + sql, args, err := And{}.ToSql() + assert.NoError(t, err) + + expectedSql := "(1=1)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{} + assert.Equal(t, expectedArgs, args) +} + +func TestEmptyOrToSql(t *testing.T) { + sql, args, err := Or{}.ToSql() + assert.NoError(t, err) + + expectedSql := "(1=0)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{} + assert.Equal(t, expectedArgs, args) +} + +func TestLikeToSql(t *testing.T) { + b := Like{"name": "%irrel"} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "name LIKE ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"%irrel"} + assert.Equal(t, expectedArgs, args) +} + +func TestNotLikeToSql(t *testing.T) { + b := NotLike{"name": "%irrel"} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "name NOT LIKE ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"%irrel"} + assert.Equal(t, expectedArgs, args) +} + +func TestILikeToSql(t *testing.T) { + b := ILike{"name": "sq%"} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "name ILIKE ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"sq%"} + assert.Equal(t, expectedArgs, args) +} + +func TestNotILikeToSql(t *testing.T) { + b := NotILike{"name": "sq%"} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "name NOT ILIKE ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"sq%"} + assert.Equal(t, expectedArgs, args) +} + +func TestSqlEqOrder(t *testing.T) { + b := Eq{"a": 1, "b": 2, "c": 3} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "a = ? AND b = ? AND c = ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2, 3} + assert.Equal(t, expectedArgs, args) +} + +func TestSqlLtOrder(t *testing.T) { + b := Lt{"a": 1, "b": 2, "c": 3} + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "a < ? AND b < ? AND c < ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2, 3} + assert.Equal(t, expectedArgs, args) +} + +func TestExprEscaped(t *testing.T) { + b := Expr("count(??)", Expr("x")) + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "count(??)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{Expr("x")} + assert.Equal(t, expectedArgs, args) +} + +func TestExprRecursion(t *testing.T) { + { + b := Expr("count(?)", Expr("nullif(a,?)", "b")) + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "count(nullif(a,?))" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"b"} + assert.Equal(t, expectedArgs, args) + } + { + b := Expr("extract(? from ?)", Expr("epoch"), "2001-02-03") + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "extract(epoch from ?)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{"2001-02-03"} + assert.Equal(t, expectedArgs, args) + } + { + b := Expr("JOIN t1 ON ?", And{Eq{"id": 1}, Expr("NOT c1"), Expr("? @@ ?", "x", "y")}) + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "JOIN t1 ON (id = ? AND NOT c1 AND ? @@ ?)" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, "x", "y"} + assert.Equal(t, expectedArgs, args) + } +} + +func ExampleEq() { + Select("id", "created", "first_name").From("users").Where(Eq{ + "company": 20, + }) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/insert_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/insert_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..0e02ed476e05a35a22e8d298fbf53c3ca4fed0d7 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/insert_ctx_test.go @@ -0,0 +1,41 @@ +// +build go1.8 + +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestInsertBuilderContextRunners(t *testing.T) { + db := &DBStub{} + b := Insert("test").Values(1).RunWith(db) + + expectedSql := "INSERT INTO test VALUES (?)" + + b.ExecContext(ctx) + assert.Equal(t, expectedSql, db.LastExecSql) + + b.QueryContext(ctx) + assert.Equal(t, expectedSql, db.LastQuerySql) + + b.QueryRowContext(ctx) + assert.Equal(t, expectedSql, db.LastQueryRowSql) + + err := b.ScanContext(ctx) + assert.NoError(t, err) +} + +func TestInsertBuilderContextNoRunner(t *testing.T) { + b := Insert("test").Values(1) + + _, err := b.ExecContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + _, err = b.QueryContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + err = b.ScanContext(ctx) + assert.Equal(t, RunnerNotSet, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/insert_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/insert_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ced2313547fd37c5f23fc815a4394e6d8b61f197 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/insert_test.go @@ -0,0 +1,112 @@ +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestInsertBuilderToSql(t *testing.T) { + b := Insert(""). + Prefix("WITH prefix AS ?", 0). + Into("a"). + Options("DELAYED", "IGNORE"). + Columns("b", "c"). + Values(1, 2). + Values(3, Expr("? + 1", 4)). + Suffix("RETURNING ?", 5) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSQL := + "WITH prefix AS ? " + + "INSERT DELAYED IGNORE INTO a (b,c) VALUES (?,?),(?,? + 1) " + + "RETURNING ?" + assert.Equal(t, expectedSQL, sql) + + expectedArgs := []interface{}{0, 1, 2, 3, 4, 5} + assert.Equal(t, expectedArgs, args) +} + +func TestInsertBuilderToSqlErr(t *testing.T) { + _, _, err := Insert("").Values(1).ToSql() + assert.Error(t, err) + + _, _, err = Insert("x").ToSql() + assert.Error(t, err) +} + +func TestInsertBuilderMustSql(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("TestInsertBuilderMustSql should have panicked!") + } + }() + Insert("").MustSql() +} + +func TestInsertBuilderPlaceholders(t *testing.T) { + b := Insert("test").Values(1, 2) + + sql, _, _ := b.PlaceholderFormat(Question).ToSql() + assert.Equal(t, "INSERT INTO test VALUES (?,?)", sql) + + sql, _, _ = b.PlaceholderFormat(Dollar).ToSql() + assert.Equal(t, "INSERT INTO test VALUES ($1,$2)", sql) +} + +func TestInsertBuilderRunners(t *testing.T) { + db := &DBStub{} + b := Insert("test").Values(1).RunWith(db) + + expectedSQL := "INSERT INTO test VALUES (?)" + + b.Exec() + assert.Equal(t, expectedSQL, db.LastExecSql) +} + +func TestInsertBuilderNoRunner(t *testing.T) { + b := Insert("test").Values(1) + + _, err := b.Exec() + assert.Equal(t, RunnerNotSet, err) +} + +func TestInsertBuilderSetMap(t *testing.T) { + b := Insert("table").SetMap(Eq{"field1": 1, "field2": 2, "field3": 3}) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSQL := "INSERT INTO table (field1,field2,field3) VALUES (?,?,?)" + assert.Equal(t, expectedSQL, sql) + + expectedArgs := []interface{}{1, 2, 3} + assert.Equal(t, expectedArgs, args) +} + +func TestInsertBuilderSelect(t *testing.T) { + sb := Select("field1").From("table1").Where(Eq{"field1": 1}) + ib := Insert("table2").Columns("field1").Select(sb) + + sql, args, err := ib.ToSql() + assert.NoError(t, err) + + expectedSQL := "INSERT INTO table2 (field1) SELECT field1 FROM table1 WHERE field1 = ?" + assert.Equal(t, expectedSQL, sql) + + expectedArgs := []interface{}{1} + assert.Equal(t, expectedArgs, args) +} + +func TestInsertBuilderReplace(t *testing.T) { + b := Replace("table").Values(1) + + expectedSQL := "REPLACE INTO table VALUES (?)" + + sql, _, err := b.ToSql() + assert.NoError(t, err) + + assert.Equal(t, expectedSQL, sql) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/integration/integration_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/integration/integration_test.go new file mode 100644 index 0000000000000000000000000000000000000000..e861e7f6f36595633e7ce3bc0495283aa417dc52 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/integration/integration_test.go @@ -0,0 +1,135 @@ +package integration + +import ( + "context" + "database/sql" + "flag" + "fmt" + "os" + "testing" + + "github.com/stretchr/testify/assert" + + sqrl "github.com/Masterminds/squirrel" + + _ "github.com/go-sql-driver/mysql" + _ "github.com/lib/pq" + _ "github.com/mattn/go-sqlite3" +) + +const ( + testSchema = ` + CREATE TABLE squirrel_integration ( k INT, v TEXT )` + testData = ` + INSERT INTO squirrel_integration VALUES + (1, 'foo'), + (3, 'bar'), + (2, 'foo'), + (4, 'baz') + ` +) + +var ( + sb sqrl.StatementBuilderType +) + +func TestMain(m *testing.M) { + var driver, dataSource string + flag.StringVar(&driver, "driver", "", "integration database driver") + flag.StringVar(&dataSource, "dataSource", "", "integration database data source") + flag.Parse() + + if driver == "" { + driver = "sqlite3" + } + + if driver == "sqlite3" && dataSource == "" { + dataSource = ":memory:" + } + + db, err := sql.Open(driver, dataSource) + if err != nil { + fmt.Printf("error opening database: %v\n", err) + os.Exit(-1) + } + + _, err = db.Exec(testSchema) + if err != nil { + fmt.Printf("error creating test schema: %v\n", err) + os.Exit(-2) + } + + defer func() { + _, err = db.Exec("DROP TABLE squirrel_integration") + fmt.Printf("error removing test schema: %v\n", err) + }() + + _, err = db.Exec(testData) + if err != nil { + fmt.Printf("error inserting test data: %v\n", err) + os.Exit(-3) + } + + sb = sqrl.StatementBuilder.RunWith(db) + + if driver == "postgres" { + sb = sb.PlaceholderFormat(sqrl.Dollar) + } + + os.Exit(m.Run()) +} + +func assertVals(t *testing.T, s sqrl.SelectBuilder, expected ...string) { + rows, err := s.Query() + assert.NoError(t, err) + defer rows.Close() + + vals := make([]string, len(expected)) + for i := range vals { + assert.True(t, rows.Next()) + assert.NoError(t, rows.Scan(&vals[i])) + } + assert.False(t, rows.Next()) + + if expected != nil { + assert.Equal(t, expected, vals) + } +} + +func TestSimpleSelect(t *testing.T) { + assertVals( + t, + sb.Select("v").From("squirrel_integration"), + "foo", "bar", "foo", "baz") +} + +func TestEq(t *testing.T) { + s := sb.Select("v").From("squirrel_integration") + assertVals(t, s.Where(sqrl.Eq{"k": 4}), "baz") + assertVals(t, s.Where(sqrl.NotEq{"k": 2}), "foo", "bar", "baz") + assertVals(t, s.Where(sqrl.Eq{"k": []int{1, 4}}), "foo", "baz") + assertVals(t, s.Where(sqrl.NotEq{"k": []int{1, 4}}), "bar", "foo") + assertVals(t, s.Where(sqrl.Eq{"k": nil})) + assertVals(t, s.Where(sqrl.NotEq{"k": nil}), "foo", "bar", "foo", "baz") + assertVals(t, s.Where(sqrl.Eq{"k": []int{}})) + assertVals(t, s.Where(sqrl.NotEq{"k": []int{}}), "foo", "bar", "foo", "baz") +} + +func TestIneq(t *testing.T) { + s := sb.Select("v").From("squirrel_integration") + assertVals(t, s.Where(sqrl.Lt{"k": 3}), "foo", "foo") + assertVals(t, s.Where(sqrl.Gt{"k": 3}), "baz") +} + +func TestConj(t *testing.T) { + s := sb.Select("v").From("squirrel_integration") + assertVals(t, s.Where(sqrl.And{sqrl.Gt{"k": 1}, sqrl.Lt{"k": 4}}), "bar", "foo") + assertVals(t, s.Where(sqrl.Or{sqrl.Gt{"k": 3}, sqrl.Lt{"k": 2}}), "foo", "baz") +} + +func TestContext(t *testing.T) { + s := sb.Select("v").From("squirrel_integration") + ctx := context.Background() + _, err := s.QueryContext(ctx) + assert.NoError(t, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/placeholder_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/placeholder_test.go new file mode 100644 index 0000000000000000000000000000000000000000..8e7f43f4929409739603e5c61bd74be940f016b5 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/placeholder_test.go @@ -0,0 +1,67 @@ +package squirrel + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestQuestion(t *testing.T) { + sql := "x = ? AND y = ?" + s, _ := Question.ReplacePlaceholders(sql) + assert.Equal(t, sql, s) +} + +func TestDollar(t *testing.T) { + sql := "x = ? AND y = ?" + s, _ := Dollar.ReplacePlaceholders(sql) + assert.Equal(t, "x = $1 AND y = $2", s) +} + +func TestColon(t *testing.T) { + sql := "x = ? AND y = ?" + s, _ := Colon.ReplacePlaceholders(sql) + assert.Equal(t, "x = :1 AND y = :2", s) +} + +func TestAtp(t *testing.T) { + sql := "x = ? AND y = ?" + s, _ := AtP.ReplacePlaceholders(sql) + assert.Equal(t, "x = @p1 AND y = @p2", s) +} + +func TestPlaceholders(t *testing.T) { + assert.Equal(t, Placeholders(2), "?,?") +} + +func TestEscapeDollar(t *testing.T) { + sql := "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ??| array['?'] AND enabled = ?" + s, _ := Dollar.ReplacePlaceholders(sql) + assert.Equal(t, "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ?| array['$1'] AND enabled = $2", s) +} + +func TestEscapeColon(t *testing.T) { + sql := "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ??| array['?'] AND enabled = ?" + s, _ := Colon.ReplacePlaceholders(sql) + assert.Equal(t, "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ?| array[':1'] AND enabled = :2", s) +} + +func TestEscapeAtp(t *testing.T) { + sql := "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ??| array['?'] AND enabled = ?" + s, _ := AtP.ReplacePlaceholders(sql) + assert.Equal(t, "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ?| array['@p1'] AND enabled = @p2", s) +} + +func BenchmarkPlaceholdersArray(b *testing.B) { + var count = b.N + placeholders := make([]string, count) + for i := 0; i < count; i++ { + placeholders[i] = "?" + } + var _ = strings.Join(placeholders, ",") +} + +func BenchmarkPlaceholdersStrings(b *testing.B) { + Placeholders(b.N) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/row_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/row_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ebeeb85485799fc47480555357873b4c4656c1c0 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/row_test.go @@ -0,0 +1,34 @@ +package squirrel + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" +) + +type RowStub struct { + Scanned bool +} + +func (r *RowStub) Scan(_ ...interface{}) error { + r.Scanned = true + return nil +} + +func TestRowScan(t *testing.T) { + stub := &RowStub{} + row := &Row{RowScanner: stub} + err := row.Scan() + assert.True(t, stub.Scanned, "row was not scanned") + assert.NoError(t, err) +} + +func TestRowScanErr(t *testing.T) { + stub := &RowStub{} + rowErr := fmt.Errorf("scan err") + row := &Row{RowScanner: stub, err: rowErr} + err := row.Scan() + assert.False(t, stub.Scanned, "row was scanned") + assert.Equal(t, rowErr, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/select_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/select_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b36ae44285e9ced8b14376ef6b060325370137d0 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/select_ctx_test.go @@ -0,0 +1,41 @@ +// +build go1.8 + +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestSelectBuilderContextRunners(t *testing.T) { + db := &DBStub{} + b := Select("test").RunWith(db) + + expectedSql := "SELECT test" + + b.ExecContext(ctx) + assert.Equal(t, expectedSql, db.LastExecSql) + + b.QueryContext(ctx) + assert.Equal(t, expectedSql, db.LastQuerySql) + + b.QueryRowContext(ctx) + assert.Equal(t, expectedSql, db.LastQueryRowSql) + + err := b.ScanContext(ctx) + assert.NoError(t, err) +} + +func TestSelectBuilderContextNoRunner(t *testing.T) { + b := Select("test") + + _, err := b.ExecContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + _, err = b.QueryContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + err = b.ScanContext(ctx) + assert.Equal(t, RunnerNotSet, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/select_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/select_test.go new file mode 100644 index 0000000000000000000000000000000000000000..80161bf5a947cbb02b3039b857b71563630f2ad0 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/select_test.go @@ -0,0 +1,463 @@ +package squirrel + +import ( + "database/sql" + "fmt" + "log" + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +func TestSelectBuilderToSql(t *testing.T) { + subQ := Select("aa", "bb").From("dd") + b := Select("a", "b"). + Prefix("WITH prefix AS ?", 0). + Distinct(). + Columns("c"). + Column("IF(d IN ("+Placeholders(3)+"), 1, 0) as stat_column", 1, 2, 3). + Column(Expr("a > ?", 100)). + Column(Alias(Eq{"b": []int{101, 102, 103}}, "b_alias")). + Column(Alias(subQ, "subq")). + From("e"). + JoinClause("CROSS JOIN j1"). + Join("j2"). + LeftJoin("j3"). + RightJoin("j4"). + InnerJoin("j5"). + CrossJoin("j6"). + Where("f = ?", 4). + Where(Eq{"g": 5}). + Where(map[string]interface{}{"h": 6}). + Where(Eq{"i": []int{7, 8, 9}}). + Where(Or{Expr("j = ?", 10), And{Eq{"k": 11}, Expr("true")}}). + GroupBy("l"). + Having("m = n"). + OrderByClause("? DESC", 1). + OrderBy("o ASC", "p DESC"). + Limit(12). + Offset(13). + Suffix("FETCH FIRST ? ROWS ONLY", 14) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := + "WITH prefix AS ? " + + "SELECT DISTINCT a, b, c, IF(d IN (?,?,?), 1, 0) as stat_column, a > ?, " + + "(b IN (?,?,?)) AS b_alias, " + + "(SELECT aa, bb FROM dd) AS subq " + + "FROM e " + + "CROSS JOIN j1 JOIN j2 LEFT JOIN j3 RIGHT JOIN j4 INNER JOIN j5 CROSS JOIN j6 " + + "WHERE f = ? AND g = ? AND h = ? AND i IN (?,?,?) AND (j = ? OR (k = ? AND true)) " + + "GROUP BY l HAVING m = n ORDER BY ? DESC, o ASC, p DESC LIMIT 12 OFFSET 13 " + + "FETCH FIRST ? ROWS ONLY" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{0, 1, 2, 3, 100, 101, 102, 103, 4, 5, 6, 7, 8, 9, 10, 11, 1, 14} + assert.Equal(t, expectedArgs, args) +} + +func TestSelectBuilderFromSelect(t *testing.T) { + subQ := Select("c").From("d").Where(Eq{"i": 0}) + b := Select("a", "b").FromSelect(subQ, "subq") + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "SELECT a, b FROM (SELECT c FROM d WHERE i = ?) AS subq" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{0} + assert.Equal(t, expectedArgs, args) +} + +func TestSelectBuilderFromSelectNestedDollarPlaceholders(t *testing.T) { + subQ := Select("c"). + From("t"). + Where(Gt{"c": 1}). + PlaceholderFormat(Dollar) + b := Select("c"). + FromSelect(subQ, "subq"). + Where(Lt{"c": 2}). + PlaceholderFormat(Dollar) + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := "SELECT c FROM (SELECT c FROM t WHERE c > $1) AS subq WHERE c < $2" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2} + assert.Equal(t, expectedArgs, args) +} + +func TestSelectBuilderToSqlErr(t *testing.T) { + _, _, err := Select().From("x").ToSql() + assert.Error(t, err) +} + +func TestSelectBuilderPlaceholders(t *testing.T) { + b := Select("test").Where("x = ? AND y = ?") + + sql, _, _ := b.PlaceholderFormat(Question).ToSql() + assert.Equal(t, "SELECT test WHERE x = ? AND y = ?", sql) + + sql, _, _ = b.PlaceholderFormat(Dollar).ToSql() + assert.Equal(t, "SELECT test WHERE x = $1 AND y = $2", sql) + + sql, _, _ = b.PlaceholderFormat(Colon).ToSql() + assert.Equal(t, "SELECT test WHERE x = :1 AND y = :2", sql) + + sql, _, _ = b.PlaceholderFormat(AtP).ToSql() + assert.Equal(t, "SELECT test WHERE x = @p1 AND y = @p2", sql) +} + +func TestSelectBuilderRunners(t *testing.T) { + db := &DBStub{} + b := Select("test").RunWith(db) + + expectedSql := "SELECT test" + + b.Exec() + assert.Equal(t, expectedSql, db.LastExecSql) + + b.Query() + assert.Equal(t, expectedSql, db.LastQuerySql) + + b.QueryRow() + assert.Equal(t, expectedSql, db.LastQueryRowSql) + + err := b.Scan() + assert.NoError(t, err) +} + +func TestSelectBuilderNoRunner(t *testing.T) { + b := Select("test") + + _, err := b.Exec() + assert.Equal(t, RunnerNotSet, err) + + _, err = b.Query() + assert.Equal(t, RunnerNotSet, err) + + err = b.Scan() + assert.Equal(t, RunnerNotSet, err) +} + +func TestSelectBuilderSimpleJoin(t *testing.T) { + + expectedSql := "SELECT * FROM bar JOIN baz ON bar.foo = baz.foo" + expectedArgs := []interface{}(nil) + + b := Select("*").From("bar").Join("baz ON bar.foo = baz.foo") + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + assert.Equal(t, expectedSql, sql) + assert.Equal(t, args, expectedArgs) +} + +func TestSelectBuilderParamJoin(t *testing.T) { + + expectedSql := "SELECT * FROM bar JOIN baz ON bar.foo = baz.foo AND baz.foo = ?" + expectedArgs := []interface{}{42} + + b := Select("*").From("bar").Join("baz ON bar.foo = baz.foo AND baz.foo = ?", 42) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + assert.Equal(t, expectedSql, sql) + assert.Equal(t, args, expectedArgs) +} + +func TestSelectBuilderNestedSelectJoin(t *testing.T) { + + expectedSql := "SELECT * FROM bar JOIN ( SELECT * FROM baz WHERE foo = ? ) r ON bar.foo = r.foo" + expectedArgs := []interface{}{42} + + nestedSelect := Select("*").From("baz").Where("foo = ?", 42) + + b := Select("*").From("bar").JoinClause(nestedSelect.Prefix("JOIN (").Suffix(") r ON bar.foo = r.foo")) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + assert.Equal(t, expectedSql, sql) + assert.Equal(t, args, expectedArgs) +} + +func TestSelectWithOptions(t *testing.T) { + sql, _, err := Select("*").From("foo").Distinct().Options("SQL_NO_CACHE").ToSql() + + assert.NoError(t, err) + assert.Equal(t, "SELECT DISTINCT SQL_NO_CACHE * FROM foo", sql) +} + +func TestSelectWithRemoveLimit(t *testing.T) { + sql, _, err := Select("*").From("foo").Limit(10).RemoveLimit().ToSql() + + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM foo", sql) +} + +func TestSelectWithRemoveOffset(t *testing.T) { + sql, _, err := Select("*").From("foo").Offset(10).RemoveOffset().ToSql() + + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM foo", sql) +} + +func TestSelectBuilderNestedSelectDollar(t *testing.T) { + nestedBuilder := StatementBuilder.PlaceholderFormat(Dollar).Select("*").Prefix("NOT EXISTS ("). + From("bar").Where("y = ?", 42).Suffix(")") + outerSql, _, err := StatementBuilder.PlaceholderFormat(Dollar).Select("*"). + From("foo").Where("x = ?").Where(nestedBuilder).ToSql() + + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM foo WHERE x = $1 AND NOT EXISTS ( SELECT * FROM bar WHERE y = $2 )", outerSql) +} + +func TestSelectBuilderMustSql(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("TestSelectBuilderMustSql should have panicked!") + } + }() + // This function should cause a panic + Select().From("foo").MustSql() +} + +func TestSelectWithoutWhereClause(t *testing.T) { + sql, _, err := Select("*").From("users").ToSql() + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM users", sql) +} + +func TestSelectWithNilWhereClause(t *testing.T) { + sql, _, err := Select("*").From("users").Where(nil).ToSql() + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM users", sql) +} + +func TestSelectWithEmptyStringWhereClause(t *testing.T) { + sql, _, err := Select("*").From("users").Where("").ToSql() + assert.NoError(t, err) + assert.Equal(t, "SELECT * FROM users", sql) +} + +func TestSelectSubqueryPlaceholderNumbering(t *testing.T) { + subquery := Select("a").Where("b = ?", 1).PlaceholderFormat(Dollar) + with := subquery.Prefix("WITH a AS (").Suffix(")") + + sql, args, err := Select("*"). + PrefixExpr(with). + FromSelect(subquery, "q"). + Where("c = ?", 2). + PlaceholderFormat(Dollar). + ToSql() + assert.NoError(t, err) + + expectedSql := "WITH a AS ( SELECT a WHERE b = $1 ) SELECT * FROM (SELECT a WHERE b = $2) AS q WHERE c = $3" + assert.Equal(t, expectedSql, sql) + assert.Equal(t, []interface{}{1, 1, 2}, args) +} + +func TestSelectSubqueryInConjunctionPlaceholderNumbering(t *testing.T) { + subquery := Select("a").Where(Eq{"b": 1}).Prefix("EXISTS(").Suffix(")").PlaceholderFormat(Dollar) + + sql, args, err := Select("*"). + Where(Or{subquery}). + Where("c = ?", 2). + PlaceholderFormat(Dollar). + ToSql() + assert.NoError(t, err) + + expectedSql := "SELECT * WHERE (EXISTS( SELECT a WHERE b = $1 )) AND c = $2" + assert.Equal(t, expectedSql, sql) + assert.Equal(t, []interface{}{1, 2}, args) +} + +func TestSelectJoinClausePlaceholderNumbering(t *testing.T) { + subquery := Select("a").Where(Eq{"b": 2}).PlaceholderFormat(Dollar) + + sql, args, err := Select("t1.a"). + From("t1"). + Where(Eq{"a": 1}). + JoinClause(subquery.Prefix("JOIN (").Suffix(") t2 ON (t1.a = t2.a)")). + PlaceholderFormat(Dollar). + ToSql() + assert.NoError(t, err) + + expectedSql := "SELECT t1.a FROM t1 JOIN ( SELECT a WHERE b = $1 ) t2 ON (t1.a = t2.a) WHERE a = $2" + assert.Equal(t, expectedSql, sql) + assert.Equal(t, []interface{}{2, 1}, args) +} + +func ExampleSelect() { + Select("id", "created", "first_name").From("users") // ... continue building up your query + + // sql methods in select columns are ok + Select("first_name", "count(*)").From("users") + + // column aliases are ok too + Select("first_name", "count(*) as n_users").From("users") +} + +func ExampleSelectBuilder_From() { + Select("id", "created", "first_name").From("users") // ... continue building up your query +} + +func ExampleSelectBuilder_Where() { + companyId := 20 + Select("id", "created", "first_name").From("users").Where("company = ?", companyId) +} + +func ExampleSelectBuilder_Where_helpers() { + companyId := 20 + + Select("id", "created", "first_name").From("users").Where(Eq{ + "company": companyId, + }) + + Select("id", "created", "first_name").From("users").Where(GtOrEq{ + "created": time.Now().AddDate(0, 0, -7), + }) + + Select("id", "created", "first_name").From("users").Where(And{ + GtOrEq{ + "created": time.Now().AddDate(0, 0, -7), + }, + Eq{ + "company": companyId, + }, + }) +} + +func ExampleSelectBuilder_Where_multiple() { + companyId := 20 + + // multiple where's are ok + + Select("id", "created", "first_name"). + From("users"). + Where("company = ?", companyId). + Where(GtOrEq{ + "created": time.Now().AddDate(0, 0, -7), + }) +} + +func ExampleSelectBuilder_FromSelect() { + usersByCompany := Select("company", "count(*) as n_users").From("users").GroupBy("company") + query := Select("company.id", "company.name", "users_by_company.n_users"). + FromSelect(usersByCompany, "users_by_company"). + Join("company on company.id = users_by_company.company") + + sql, _, _ := query.ToSql() + fmt.Println(sql) + + // Output: SELECT company.id, company.name, users_by_company.n_users FROM (SELECT company, count(*) as n_users FROM users GROUP BY company) AS users_by_company JOIN company on company.id = users_by_company.company +} + +func ExampleSelectBuilder_Columns() { + query := Select("id").Columns("created", "first_name").From("users") + + sql, _, _ := query.ToSql() + fmt.Println(sql) + // Output: SELECT id, created, first_name FROM users +} + +func ExampleSelectBuilder_Columns_order() { + // out of order is ok too + query := Select("id").Columns("created").From("users").Columns("first_name") + + sql, _, _ := query.ToSql() + fmt.Println(sql) + // Output: SELECT id, created, first_name FROM users +} + +func ExampleSelectBuilder_Scan() { + + var db *sql.DB + + query := Select("id", "created", "first_name").From("users") + query = query.RunWith(db) + + var id int + var created time.Time + var firstName string + + if err := query.Scan(&id, &created, &firstName); err != nil { + log.Println(err) + return + } +} + +func ExampleSelectBuilder_ScanContext() { + + var db *sql.DB + + query := Select("id", "created", "first_name").From("users") + query = query.RunWith(db) + + var id int + var created time.Time + var firstName string + + if err := query.ScanContext(ctx, &id, &created, &firstName); err != nil { + log.Println(err) + return + } +} + +func ExampleSelectBuilder_RunWith() { + + var db *sql.DB + + query := Select("id", "created", "first_name").From("users").RunWith(db) + + var id int + var created time.Time + var firstName string + + if err := query.Scan(&id, &created, &firstName); err != nil { + log.Println(err) + return + } +} + +func ExampleSelectBuilder_ToSql() { + + var db *sql.DB + + query := Select("id", "created", "first_name").From("users") + + sql, args, err := query.ToSql() + if err != nil { + log.Println(err) + return + } + + rows, err := db.Query(sql, args...) + if err != nil { + log.Println(err) + return + } + + defer rows.Close() + + for rows.Next() { + // scan... + } +} + +func TestRemoveColumns(t *testing.T) { + query := Select("id"). + From("users"). + RemoveColumns() + query = query.Columns("name") + sql, _, err := query.ToSql() + assert.NoError(t, err) + assert.Equal(t, "SELECT name FROM users", sql) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/squirrel_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/squirrel_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..0e56f2b1a917331241c68f7f3d6b67ce6669a6c9 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/squirrel_ctx_test.go @@ -0,0 +1,55 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + "testing" + + "github.com/stretchr/testify/assert" +) + +func (s *DBStub) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) { + s.LastPrepareSql = query + s.PrepareCount++ + return nil, nil +} + +func (s *DBStub) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) { + s.LastExecSql = query + s.LastExecArgs = args + return nil, nil +} + +func (s *DBStub) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) { + s.LastQuerySql = query + s.LastQueryArgs = args + return nil, nil +} + +func (s *DBStub) QueryRowContext(ctx context.Context, query string, args ...interface{}) RowScanner { + s.LastQueryRowSql = query + s.LastQueryRowArgs = args + return &Row{RowScanner: &RowStub{}} +} + +var ctx = context.Background() + +func TestExecContextWith(t *testing.T) { + db := &DBStub{} + ExecContextWith(ctx, db, sqlizer) + assert.Equal(t, sqlStr, db.LastExecSql) +} + +func TestQueryContextWith(t *testing.T) { + db := &DBStub{} + QueryContextWith(ctx, db, sqlizer) + assert.Equal(t, sqlStr, db.LastQuerySql) +} + +func TestQueryRowContextWith(t *testing.T) { + db := &DBStub{} + QueryRowContextWith(ctx, db, sqlizer) + assert.Equal(t, sqlStr, db.LastQueryRowSql) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/squirrel_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/squirrel_test.go new file mode 100644 index 0000000000000000000000000000000000000000..5b6bc6268048992031dfbded60dbf0927df2a2be --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/squirrel_test.go @@ -0,0 +1,202 @@ +package squirrel + +import ( + "database/sql" + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +type DBStub struct { + err error + + LastPrepareSql string + PrepareCount int + + LastExecSql string + LastExecArgs []interface{} + + LastQuerySql string + LastQueryArgs []interface{} + + LastQueryRowSql string + LastQueryRowArgs []interface{} +} + +var StubError = fmt.Errorf("this is a stub; this is only a stub") + +func (s *DBStub) Prepare(query string) (*sql.Stmt, error) { + s.LastPrepareSql = query + s.PrepareCount++ + return nil, nil +} + +func (s *DBStub) Exec(query string, args ...interface{}) (sql.Result, error) { + s.LastExecSql = query + s.LastExecArgs = args + return nil, nil +} + +func (s *DBStub) Query(query string, args ...interface{}) (*sql.Rows, error) { + s.LastQuerySql = query + s.LastQueryArgs = args + return nil, nil +} + +func (s *DBStub) QueryRow(query string, args ...interface{}) RowScanner { + s.LastQueryRowSql = query + s.LastQueryRowArgs = args + return &Row{RowScanner: &RowStub{}} +} + +var sqlizer = Select("test") +var sqlStr = "SELECT test" + +func TestExecWith(t *testing.T) { + db := &DBStub{} + ExecWith(db, sqlizer) + assert.Equal(t, sqlStr, db.LastExecSql) +} + +func TestQueryWith(t *testing.T) { + db := &DBStub{} + QueryWith(db, sqlizer) + assert.Equal(t, sqlStr, db.LastQuerySql) +} + +func TestQueryRowWith(t *testing.T) { + db := &DBStub{} + QueryRowWith(db, sqlizer) + assert.Equal(t, sqlStr, db.LastQueryRowSql) +} + +func TestWithToSqlErr(t *testing.T) { + db := &DBStub{} + sqlizer := Select() + + _, err := ExecWith(db, sqlizer) + assert.Error(t, err) + + _, err = QueryWith(db, sqlizer) + assert.Error(t, err) + + err = QueryRowWith(db, sqlizer).Scan() + assert.Error(t, err) +} + +var testDebugUpdateSQL = Update("table").SetMap(Eq{"x": 1, "y": "val"}) +var expectedDebugUpateSQL = "UPDATE table SET x = '1', y = 'val'" + +func TestDebugSqlizerUpdateColon(t *testing.T) { + testDebugUpdateSQL.PlaceholderFormat(Colon) + assert.Equal(t, expectedDebugUpateSQL, DebugSqlizer(testDebugUpdateSQL)) +} + +func TestDebugSqlizerUpdateAtp(t *testing.T) { + testDebugUpdateSQL.PlaceholderFormat(AtP) + assert.Equal(t, expectedDebugUpateSQL, DebugSqlizer(testDebugUpdateSQL)) +} + +func TestDebugSqlizerUpdateDollar(t *testing.T) { + testDebugUpdateSQL.PlaceholderFormat(Dollar) + assert.Equal(t, expectedDebugUpateSQL, DebugSqlizer(testDebugUpdateSQL)) +} + +func TestDebugSqlizerUpdateQuestion(t *testing.T) { + testDebugUpdateSQL.PlaceholderFormat(Question) + assert.Equal(t, expectedDebugUpateSQL, DebugSqlizer(testDebugUpdateSQL)) +} + +var testDebugDeleteSQL = Delete("table").Where(And{ + Eq{"column": "val"}, + Eq{"other": 1}, +}) +var expectedDebugDeleteSQL = "DELETE FROM table WHERE (column = 'val' AND other = '1')" + +func TestDebugSqlizerDeleteColon(t *testing.T) { + testDebugDeleteSQL.PlaceholderFormat(Colon) + assert.Equal(t, expectedDebugDeleteSQL, DebugSqlizer(testDebugDeleteSQL)) +} + +func TestDebugSqlizerDeleteAtp(t *testing.T) { + testDebugDeleteSQL.PlaceholderFormat(AtP) + assert.Equal(t, expectedDebugDeleteSQL, DebugSqlizer(testDebugDeleteSQL)) +} + +func TestDebugSqlizerDeleteDollar(t *testing.T) { + testDebugDeleteSQL.PlaceholderFormat(Dollar) + assert.Equal(t, expectedDebugDeleteSQL, DebugSqlizer(testDebugDeleteSQL)) +} + +func TestDebugSqlizerDeleteQuestion(t *testing.T) { + testDebugDeleteSQL.PlaceholderFormat(Question) + assert.Equal(t, expectedDebugDeleteSQL, DebugSqlizer(testDebugDeleteSQL)) +} + +var testDebugInsertSQL = Insert("table").Values(1, "test") +var expectedDebugInsertSQL = "INSERT INTO table VALUES ('1','test')" + +func TestDebugSqlizerInsertColon(t *testing.T) { + testDebugInsertSQL.PlaceholderFormat(Colon) + assert.Equal(t, expectedDebugInsertSQL, DebugSqlizer(testDebugInsertSQL)) +} + +func TestDebugSqlizerInsertAtp(t *testing.T) { + testDebugInsertSQL.PlaceholderFormat(AtP) + assert.Equal(t, expectedDebugInsertSQL, DebugSqlizer(testDebugInsertSQL)) +} + +func TestDebugSqlizerInsertDollar(t *testing.T) { + testDebugInsertSQL.PlaceholderFormat(Dollar) + assert.Equal(t, expectedDebugInsertSQL, DebugSqlizer(testDebugInsertSQL)) +} + +func TestDebugSqlizerInsertQuestion(t *testing.T) { + testDebugInsertSQL.PlaceholderFormat(Question) + assert.Equal(t, expectedDebugInsertSQL, DebugSqlizer(testDebugInsertSQL)) +} + +var testDebugSelectSQL = Select("*").From("table").Where(And{ + Eq{"column": "val"}, + Eq{"other": 1}, +}) +var expectedDebugSelectSQL = "SELECT * FROM table WHERE (column = 'val' AND other = '1')" + +func TestDebugSqlizerSelectColon(t *testing.T) { + testDebugSelectSQL.PlaceholderFormat(Colon) + assert.Equal(t, expectedDebugSelectSQL, DebugSqlizer(testDebugSelectSQL)) +} + +func TestDebugSqlizerSelectAtp(t *testing.T) { + testDebugSelectSQL.PlaceholderFormat(AtP) + assert.Equal(t, expectedDebugSelectSQL, DebugSqlizer(testDebugSelectSQL)) +} + +func TestDebugSqlizerSelectDollar(t *testing.T) { + testDebugSelectSQL.PlaceholderFormat(Dollar) + assert.Equal(t, expectedDebugSelectSQL, DebugSqlizer(testDebugSelectSQL)) +} + +func TestDebugSqlizerSelectQuestion(t *testing.T) { + testDebugSelectSQL.PlaceholderFormat(Question) + assert.Equal(t, expectedDebugSelectSQL, DebugSqlizer(testDebugSelectSQL)) +} + +func TestDebugSqlizer(t *testing.T) { + sqlizer := Expr("x = ? AND y = ? AND z = '??'", 1, "text") + expectedDebug := "x = '1' AND y = 'text' AND z = '?'" + assert.Equal(t, expectedDebug, DebugSqlizer(sqlizer)) +} + +func TestDebugSqlizerErrors(t *testing.T) { + errorMsg := DebugSqlizer(Expr("x = ?", 1, 2)) // Not enough placeholders + assert.True(t, strings.HasPrefix(errorMsg, "[DebugSqlizer error: ")) + + errorMsg = DebugSqlizer(Expr("x = ? AND y = ?", 1)) // Too many placeholders + assert.True(t, strings.HasPrefix(errorMsg, "[DebugSqlizer error: ")) + + errorMsg = DebugSqlizer(Lt{"x": nil}) // Cannot use nil values with Lt + assert.True(t, strings.HasPrefix(errorMsg, "[ToSql error: ")) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/statement_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/statement_test.go new file mode 100644 index 0000000000000000000000000000000000000000..3c9336023c60f46844b032d9fad3eabdcebabd6a --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/statement_test.go @@ -0,0 +1,81 @@ +package squirrel + +import ( + "database/sql" + "testing" + + "github.com/lann/builder" + "github.com/stretchr/testify/assert" +) + +func TestStatementBuilder(t *testing.T) { + db := &DBStub{} + sb := StatementBuilder.RunWith(db) + + sb.Select("test").Exec() + assert.Equal(t, "SELECT test", db.LastExecSql) +} + +func TestStatementBuilderPlaceholderFormat(t *testing.T) { + db := &DBStub{} + sb := StatementBuilder.RunWith(db).PlaceholderFormat(Dollar) + + sb.Select("test").Where("x = ?").Exec() + assert.Equal(t, "SELECT test WHERE x = $1", db.LastExecSql) +} + +func TestRunWithDB(t *testing.T) { + db := &sql.DB{} + assert.NotPanics(t, func() { + builder.GetStruct(Select().RunWith(db)) + builder.GetStruct(Insert("t").RunWith(db)) + builder.GetStruct(Update("t").RunWith(db)) + builder.GetStruct(Delete("t").RunWith(db)) + }, "RunWith(*sql.DB) should not panic") + +} + +func TestRunWithTx(t *testing.T) { + tx := &sql.Tx{} + assert.NotPanics(t, func() { + builder.GetStruct(Select().RunWith(tx)) + builder.GetStruct(Insert("t").RunWith(tx)) + builder.GetStruct(Update("t").RunWith(tx)) + builder.GetStruct(Delete("t").RunWith(tx)) + }, "RunWith(*sql.Tx) should not panic") +} + +type fakeBaseRunner struct{} + +func (fakeBaseRunner) Exec(query string, args ...interface{}) (sql.Result, error) { + return nil, nil +} + +func (fakeBaseRunner) Query(query string, args ...interface{}) (*sql.Rows, error) { + return nil, nil +} + +func TestRunWithBaseRunner(t *testing.T) { + sb := StatementBuilder.RunWith(fakeBaseRunner{}) + _, err := sb.Select("test").Exec() + assert.NoError(t, err) +} + +func TestRunWithBaseRunnerQueryRowError(t *testing.T) { + sb := StatementBuilder.RunWith(fakeBaseRunner{}) + assert.Error(t, RunnerNotQueryRunner, sb.Select("test").QueryRow().Scan(nil)) + +} + +func TestStatementBuilderWhere(t *testing.T) { + sb := StatementBuilder.Where("x = ?", 1) + + sql, args, err := sb.Select("test").Where("y = ?", 2).ToSql() + assert.NoError(t, err) + + expectedSql := "SELECT test WHERE x = ? AND y = ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{1, 2} + assert.Equal(t, expectedArgs, args) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/stmtcacher_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/stmtcacher_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..1915e5e5e9b6e7577c63cec1ca908d1d7c9ad9e5 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/stmtcacher_ctx_test.go @@ -0,0 +1,21 @@ +// +build go1.8 + +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestStmtCacherPrepareContext(t *testing.T) { + db := &DBStub{} + sc := NewStmtCache(db) + query := "SELECT 1" + + sc.PrepareContext(ctx, query) + assert.Equal(t, query, db.LastPrepareSql) + + sc.PrepareContext(ctx, query) + assert.Equal(t, 1, db.PrepareCount, "expected 1 Prepare, got %d", db.PrepareCount) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/stmtcacher_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/stmtcacher_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ba47ea21ac120f54cd10d2e794e7644e09d7152c --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/stmtcacher_test.go @@ -0,0 +1,26 @@ +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestStmtCachePrepare(t *testing.T) { + db := &DBStub{} + sc := NewStmtCache(db) + query := "SELECT 1" + + sc.Prepare(query) + assert.Equal(t, query, db.LastPrepareSql) + + sc.Prepare(query) + assert.Equal(t, 1, db.PrepareCount, "expected 1 Prepare, got %d", db.PrepareCount) + + // clear statement cache + assert.Nil(t, sc.Clear()) + + // should prepare the query again + sc.Prepare(query) + assert.Equal(t, 2, db.PrepareCount, "expected 2 Prepare, got %d", db.PrepareCount) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/update_ctx_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/update_ctx_test.go new file mode 100644 index 0000000000000000000000000000000000000000..a7bc125a9d90e722a217a8ca23041b8cb4aaba9f --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/update_ctx_test.go @@ -0,0 +1,41 @@ +// +build go1.8 + +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestUpdateBuilderContextRunners(t *testing.T) { + db := &DBStub{} + b := Update("test").Set("x", 1).RunWith(db) + + expectedSql := "UPDATE test SET x = ?" + + b.ExecContext(ctx) + assert.Equal(t, expectedSql, db.LastExecSql) + + b.QueryContext(ctx) + assert.Equal(t, expectedSql, db.LastQuerySql) + + b.QueryRowContext(ctx) + assert.Equal(t, expectedSql, db.LastQueryRowSql) + + err := b.ScanContext(ctx) + assert.NoError(t, err) +} + +func TestUpdateBuilderContextNoRunner(t *testing.T) { + b := Update("test").Set("x", 1) + + _, err := b.ExecContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + _, err = b.QueryContext(ctx) + assert.Equal(t, RunnerNotSet, err) + + err = b.ScanContext(ctx) + assert.Equal(t, RunnerNotSet, err) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/update_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/update_test.go new file mode 100644 index 0000000000000000000000000000000000000000..a2bee1aad42b6b05bac373fa52f0abd08d458334 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/update_test.go @@ -0,0 +1,107 @@ +package squirrel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestUpdateBuilderToSql(t *testing.T) { + b := Update(""). + Prefix("WITH prefix AS ?", 0). + Table("a"). + Set("b", Expr("? + 1", 1)). + SetMap(Eq{"c": 2}). + Set("c1", Case("status").When("1", "2").When("2", "1")). + Set("c2", Case().When("a = 2", Expr("?", "foo")).When("a = 3", Expr("?", "bar"))). + Set("c3", Select("a").From("b")). + Where("d = ?", 3). + OrderBy("e"). + Limit(4). + Offset(5). + Suffix("RETURNING ?", 6) + + sql, args, err := b.ToSql() + assert.NoError(t, err) + + expectedSql := + "WITH prefix AS ? " + + "UPDATE a SET b = ? + 1, c = ?, " + + "c1 = CASE status WHEN 1 THEN 2 WHEN 2 THEN 1 END, " + + "c2 = CASE WHEN a = 2 THEN ? WHEN a = 3 THEN ? END, " + + "c3 = (SELECT a FROM b) " + + "WHERE d = ? " + + "ORDER BY e LIMIT 4 OFFSET 5 " + + "RETURNING ?" + assert.Equal(t, expectedSql, sql) + + expectedArgs := []interface{}{0, 1, 2, "foo", "bar", 3, 6} + assert.Equal(t, expectedArgs, args) +} + +func TestUpdateBuilderToSqlErr(t *testing.T) { + _, _, err := Update("").Set("x", 1).ToSql() + assert.Error(t, err) + + _, _, err = Update("x").ToSql() + assert.Error(t, err) +} + +func TestUpdateBuilderMustSql(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("TestUpdateBuilderMustSql should have panicked!") + } + }() + Update("").MustSql() +} + +func TestUpdateBuilderPlaceholders(t *testing.T) { + b := Update("test").SetMap(Eq{"x": 1, "y": 2}) + + sql, _, _ := b.PlaceholderFormat(Question).ToSql() + assert.Equal(t, "UPDATE test SET x = ?, y = ?", sql) + + sql, _, _ = b.PlaceholderFormat(Dollar).ToSql() + assert.Equal(t, "UPDATE test SET x = $1, y = $2", sql) +} + +func TestUpdateBuilderRunners(t *testing.T) { + db := &DBStub{} + b := Update("test").Set("x", 1).RunWith(db) + + expectedSql := "UPDATE test SET x = ?" + + b.Exec() + assert.Equal(t, expectedSql, db.LastExecSql) +} + +func TestUpdateBuilderNoRunner(t *testing.T) { + b := Update("test").Set("x", 1) + + _, err := b.Exec() + assert.Equal(t, RunnerNotSet, err) +} + +func TestUpdateBuilderFrom(t *testing.T) { + sql, _, err := Update("employees").Set("sales_count", 100).From("accounts").Where("accounts.name = ?", "ACME").ToSql() + assert.NoError(t, err) + assert.Equal(t, "UPDATE employees SET sales_count = ? FROM accounts WHERE accounts.name = ?", sql) +} + +func TestUpdateBuilderFromSelect(t *testing.T) { + sql, _, err := Update("employees"). + Set("sales_count", 100). + FromSelect(Select("id"). + From("accounts"). + Where("accounts.name = ?", "ACME"), "subquery"). + Where("employees.account_id = subquery.id").ToSql() + assert.NoError(t, err) + + expectedSql := + "UPDATE employees " + + "SET sales_count = ? " + + "FROM (SELECT id FROM accounts WHERE accounts.name = ?) AS subquery " + + "WHERE employees.account_id = subquery.id" + assert.Equal(t, expectedSql, sql) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/where_test.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/where_test.go new file mode 100644 index 0000000000000000000000000000000000000000..d2109f17c2071398d8ae2d41177cf929876ae01a --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/frozen/where_test.go @@ -0,0 +1,56 @@ +package squirrel + +import ( + "testing" + + "bytes" + + "github.com/stretchr/testify/assert" +) + +func TestWherePartsAppendToSql(t *testing.T) { + parts := []Sqlizer{ + newWherePart("x = ?", 1), + newWherePart(nil), + newWherePart(Eq{"y": 2}), + } + sql := &bytes.Buffer{} + args, _ := appendToSql(parts, sql, " AND ", []interface{}{}) + assert.Equal(t, "x = ? AND y = ?", sql.String()) + assert.Equal(t, []interface{}{1, 2}, args) +} + +func TestWherePartsAppendToSqlErr(t *testing.T) { + parts := []Sqlizer{newWherePart(1)} + _, err := appendToSql(parts, &bytes.Buffer{}, "", []interface{}{}) + assert.Error(t, err) +} + +func TestWherePartNil(t *testing.T) { + sql, _, _ := newWherePart(nil).ToSql() + assert.Equal(t, "", sql) +} + +func TestWherePartErr(t *testing.T) { + _, _, err := newWherePart(1).ToSql() + assert.Error(t, err) +} + +func TestWherePartString(t *testing.T) { + sql, args, _ := newWherePart("x = ?", 1).ToSql() + assert.Equal(t, "x = ?", sql) + assert.Equal(t, []interface{}{1}, args) +} + +func TestWherePartMap(t *testing.T) { + test := func(pred interface{}) { + sql, _, _ := newWherePart(pred).ToSql() + expect := []string{"x = ? AND y = ?", "y = ? AND x = ?"} + if sql != expect[0] && sql != expect[1] { + t.Errorf("expected one of %#v, got %#v", expect, sql) + } + } + m := map[string]interface{}{"x": 1, "y": 2} + test(m) + test(Eq(m)) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/grade.py b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/manifest.json b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..2b985ddb400515d0a4b7ef351ddec624e352b7ba --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/manifest.json @@ -0,0 +1,804 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseWithNoVal" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestMultipleCase" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqToSql" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqEmptyToSql" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqInToSql" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNotEqToSql" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqNotInToSql" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqInEmptyToSql" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNotEqInEmptyToSql" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEqBytesToSql" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestExprNilToSql" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNullTypeString" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNullTypeInt64" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNilPointer" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNotNilPointer" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSqlEqOrder" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestExprRecursion" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderSelect" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderToSql" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderFromSelect" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectSubqueryInConjunctionPlaceholderNumbering" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectJoinClausePlaceholderNumbering" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerDeleteColon" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerDeleteAtp" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerDeleteDollar" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerDeleteQuestion" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerSelectColon" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerSelectAtp" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerSelectDollar" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerSelectQuestion" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartsAppendToSql" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartMap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseWithVal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseWithComplexVal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseWithExpr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseWithNoWhenClause" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestCaseBuilderMustSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderContextRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderContextNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderMustSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteBuilderNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDeleteWithQuery" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestConcatExpr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestConcatExprBadType" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestLtToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestLtOrEqToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestGtToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestGtOrEqToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEmptyAndToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEmptyOrToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestLikeToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNotLikeToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestILikeToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestNotILikeToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSqlLtOrder" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestExprEscaped" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderContextRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderContextNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderMustSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderSetMap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestInsertBuilderReplace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestQuestion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestColon" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestAtp" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEscapeDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEscapeColon" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestEscapeAtp" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRowScan" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRowScanErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderContextRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderContextNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderFromSelectNestedDollarPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderSimpleJoin" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderParamJoin" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderNestedSelectJoin" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithOptions" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithRemoveLimit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithRemoveOffset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderNestedSelectDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectBuilderMustSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithoutWhereClause" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithNilWhereClause" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectWithEmptyStringWhereClause" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestSelectSubqueryPlaceholderNumbering" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRemoveColumns" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestExecContextWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestQueryContextWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestQueryRowContextWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestExecWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestQueryWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestQueryRowWith" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWithToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerUpdateColon" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerUpdateAtp" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerUpdateDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerUpdateQuestion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerInsertColon" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerInsertAtp" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerInsertDollar" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerInsertQuestion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestDebugSqlizerErrors" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestStatementBuilder" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestStatementBuilderPlaceholderFormat" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRunWithDB" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRunWithTx" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRunWithBaseRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestRunWithBaseRunnerQueryRowError" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestStatementBuilderWhere" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestStmtCacherPrepareContext" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestStmtCachePrepare" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderContextRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderContextNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderToSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderMustSql" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderPlaceholders" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderRunners" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderNoRunner" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestUpdateBuilderFromSelect" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartsAppendToSqlErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartErr" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "TestWherePartString" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "ExampleSelectBuilder_FromSelect" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "ExampleSelectBuilder_Columns" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/Masterminds/squirrel", + "test": "ExampleSelectBuilder_Columns_order" + } + ], + "frozen_files": { + "case_test.go": { + "mode": 420, + "sha256": "fdb8c60761dc1ab02953e86f1736bd29e644e61bb7f67a394a5f71d276a67298" + }, + "delete_ctx_test.go": { + "mode": 420, + "sha256": "07e5cd531fbc380655a6f441eeee23da925195d67a1a7e7682785806af51014e" + }, + "delete_test.go": { + "mode": 420, + "sha256": "44ac247a59eb89cd5f41e3f0948a78e51e757d0888a72874d12a12c6db1acfb0" + }, + "expr_test.go": { + "mode": 420, + "sha256": "ab52b68e40a81bda968dacc733f34c08626f299405450c383daf438e33897a65" + }, + "insert_ctx_test.go": { + "mode": 420, + "sha256": "b3e3efaf75fee82c147958afb70a90334f4f08cf29b64bd76d23a03b9824f299" + }, + "insert_test.go": { + "mode": 420, + "sha256": "665fe6694c9ce48b2bcbdfd34ab9bde67d8fd7601b3d5798f4dacd693e1da278" + }, + "integration/integration_test.go": { + "mode": 420, + "sha256": "c8631b72fa30417861d7ba87a1a9a5c0883d01744fb49bf779360dc4a61b9abf" + }, + "placeholder_test.go": { + "mode": 420, + "sha256": "c498900e8f98d981e90863f0603d19c11db17e786eae008bdc5af2b25ae8eb13" + }, + "row_test.go": { + "mode": 420, + "sha256": "7fe834ce33424df8e009fa44ee5acea25508c7e439d1bf07fddf6d4c90e77ec1" + }, + "select_ctx_test.go": { + "mode": 420, + "sha256": "560d37ac028fbf92ba5c5a20b95af7d866a4fbdecd0e868b6fe266eb4849e665" + }, + "select_test.go": { + "mode": 420, + "sha256": "3b06e89b5c358992a7165414dbeb4643820d95574981359638d609931d528630" + }, + "squirrel_ctx_test.go": { + "mode": 420, + "sha256": "4a052ae48d428a0719777189c407e5d5c7087550c0d99b2c28cceada083f76b0" + }, + "squirrel_test.go": { + "mode": 420, + "sha256": "7336a2ffda333c52c145d76e926a89e1244ff24b96c86abfc6fe06723572180f" + }, + "statement_test.go": { + "mode": 420, + "sha256": "a0f46fa71157b09eaca3da0fa6a75b25156cb552c785228836b0ffbb9fe5ac27" + }, + "stmtcacher_ctx_test.go": { + "mode": 420, + "sha256": "a0a1f49a87ebb6b35b8d66fbe9051d8a9f94346eaf5e3cd70719424433f5c878" + }, + "stmtcacher_test.go": { + "mode": 420, + "sha256": "e5b5020ac3c194cf92121100a24df580955f32f89bd600b1e56014702d24eb52" + }, + "update_ctx_test.go": { + "mode": 420, + "sha256": "3dd7bd0c17bfb61fad6e71c7736ca6a207f811ae7c3f92f8185c5f7d32dbf30a" + }, + "update_test.go": { + "mode": 420, + "sha256": "6316c8d144c647d9c7bdd6b8be4490c40398da03d331be23c4729faa7a57aa4e" + }, + "where_test.go": { + "mode": 420, + "sha256": "1a53006a294c379a8b7f212b340acf9063ea0b613062a52fc9585a7d84f853f3" + } + } +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/test.sh b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/validation/canaries/original-bug.sh b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/validation/canaries/partial-repair.sh b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/validation/canaries/partial-repair.sh new file mode 100644 index 0000000000000000000000000000000000000000..53c0b49c0d575872cbeb2060a6cce3320b173276 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/validation/canaries/partial-repair.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"expr.go": {"data": "cGFja2FnZSBzcXVpcnJlbAoKaW1wb3J0ICgKCSJieXRlcyIKCSJkYXRhYmFzZS9zcWwvZHJpdmVyIgoJImZtdCIKCSJyZWZsZWN0IgoJInNvcnQiCgkic3RyaW5ncyIKKQoKY29uc3QgKAoJLy8gUG9ydGFibGUgdHJ1ZS9mYWxzZSBsaXRlcmFscy4KCXNxbFRydWUgID0gIigxPTEpIgoJc3FsRmFsc2UgPSAiKDE9MCkiCikKCnR5cGUgZXhwciBzdHJ1Y3QgewoJc3FsICBzdHJpbmcKCWFyZ3MgW11pbnRlcmZhY2V7fQp9CgovLyBFeHByIGJ1aWxkcyBhbiBleHByZXNzaW9uIGZyb20gYSBTUUwgZnJhZ21lbnQgYW5kIGFyZ3VtZW50cy4KLy8KLy8gRXg6Ci8vICAgICBFeHByKCJGUk9NX1VOSVhUSU1FKD8pIiwgdCkKZnVuYyBFeHByKHNxbCBzdHJpbmcsIGFyZ3MgLi4uaW50ZXJmYWNle30pIFNxbGl6ZXIgewoJcmV0dXJuIGV4cHJ7c3FsOiBzcWwsIGFyZ3M6IGFyZ3N9Cn0KCmZ1bmMgKGUgZXhwcikgVG9TcWwoKSAoc3FsIHN0cmluZywgYXJncyBbXWludGVyZmFjZXt9LCBlcnIgZXJyb3IpIHsKCXNpbXBsZSA6PSB0cnVlCglmb3IgXywgYXJnIDo9IHJhbmdlIGUuYXJncyB7CgkJaWYgXywgb2sgOj0gYXJnLihTcWxpemVyKTsgb2sgewoJCQlzaW1wbGUgPSBmYWxzZQoJCX0KCX0KCWlmIHNpbXBsZSB7CgkJcmV0dXJuIGUuc3FsLCBlLmFyZ3MsIG5pbAoJfQoKCWJ1ZiA6PSAmYnl0ZXMuQnVmZmVye30KCWFwIDo9IGUuYXJncwoJc3AgOj0gZS5zcWwKCgl2YXIgaXNxbCBzdHJpbmcKCXZhciBpYXJncyBbXWludGVyZmFjZXt9CgoJZm9yIGVyciA9PSBuaWwgJiYgbGVuKGFwKSA+IDAgJiYgbGVuKHNwKSA+IDAgewoJCWkgOj0gc3RyaW5ncy5JbmRleChzcCwgIj8iKQoJCWlmIGkgPCAwIHsKCQkJLy8gbm8gbW9yZSBwbGFjZWhvbGRlcnMKCQkJYnJlYWsKCQl9CgkJaWYgbGVuKHNwKSA+IGkrMSAmJiBzcFtpKzE6aSsyXSA9PSAiPyIgewoJCQkvLyBlc2NhcGVkICI/PyI7IGFwcGVuZCBpdCBhbmQgc3RlcCBwYXN0CgkJCWJ1Zi5Xcml0ZVN0cmluZyhzcFs6aSsyXSkKCQkJc3AgPSBzcFtpKzI6XQoJCQljb250aW51ZQoJCX0KCgkJaWYgYXMsIG9rIDo9IGFwWzBdLihTcWxpemVyKTsgb2sgewoJCQkvLyBzcWxpemVyIGFyZ3VtZW50OyBleHBhbmQgaXQgYW5kIGFwcGVuZCB0aGUgcmVzdWx0CgkJCWlzcWwsIGlhcmdzLCBlcnIgPSBhcy5Ub1NxbCgpCgkJCWJ1Zi5Xcml0ZVN0cmluZyhzcFs6aV0pCgkJCWJ1Zi5Xcml0ZVN0cmluZyhpc3FsKQoJCQlhcmdzID0gYXBwZW5kKGFyZ3MsIGlhcmdzLi4uKQoJCX0gZWxzZSB7CgkJCS8vIG5vcm1hbCBhcmd1bWVudDsgYXBwZW5kIGl0IGFuZCB0aGUgcGxhY2Vob2xkZXIKCQkJYnVmLldyaXRlU3RyaW5nKHNwWzppKzFdKQoJCQlhcmdzID0gYXBwZW5kKGFyZ3MsIGFwWzBdKQoJCX0KCgkJLy8gc3RlcCBwYXN0IHRoZSBhcmd1bWVudCBhbmQgcGxhY2Vob2xkZXIKCQlhcCA9IGFwWzE6XQoJCXNwID0gc3BbaSsxOl0KCX0KCgkvLyBhcHBlbmQgdGhlIHJlbWFpbmluZyBzcWwgYW5kIGFyZ3VtZW50cwoJYnVmLldyaXRlU3RyaW5nKHNwKQoJcmV0dXJuIGJ1Zi5TdHJpbmcoKSwgYXBwZW5kKGFyZ3MsIGFwLi4uKSwgZXJyCn0KCnR5cGUgY29uY2F0RXhwciBbXWludGVyZmFjZXt9CgpmdW5jIChjZSBjb25jYXRFeHByKSBUb1NxbCgpIChzcWwgc3RyaW5nLCBhcmdzIFtdaW50ZXJmYWNle30sIGVyciBlcnJvcikgewoJZm9yIF8sIHBhcnQgOj0gcmFuZ2UgY2UgewoJCXN3aXRjaCBwIDo9IHBhcnQuKHR5cGUpIHsKCQljYXNlIHN0cmluZzoKCQkJc3FsICs9IHAKCQljYXNlIFNxbGl6ZXI6CgkJCXBTcWwsIHBBcmdzLCBlcnIgOj0gcC5Ub1NxbCgpCgkJCWlmIGVyciAhPSBuaWwgewoJCQkJcmV0dXJuICIiLCBuaWwsIGVycgoJCQl9CgkJCXNxbCArPSBwU3FsCgkJCWFyZ3MgPSBhcHBlbmQoYXJncywgcEFyZ3MuLi4pCgkJZGVmYXVsdDoKCQkJcmV0dXJuICIiLCBuaWwsIGZtdC5FcnJvcmYoIiUjdiBpcyBub3QgYSBzdHJpbmcgb3IgU3FsaXplciIsIHBhcnQpCgkJfQoJfQoJcmV0dXJuCn0KCi8vIENvbmNhdEV4cHIgYnVpbGRzIGFuIGV4cHJlc3Npb24gYnkgY29uY2F0ZW5hdGluZyBzdHJpbmdzIGFuZCBvdGhlciBleHByZXNzaW9ucy4KLy8KLy8gRXg6Ci8vICAgICBuYW1lX2V4cHIgOj0gRXhwcigiQ09OQ0FUKD8sICcgJywgPykiLCBmaXJzdE5hbWUsIGxhc3ROYW1lKQovLyAgICAgQ29uY2F0RXhwcigiQ09BTEVTQ0UoZnVsbF9uYW1lLCIsIG5hbWVfZXhwciwgIikiKQpmdW5jIENvbmNhdEV4cHIocGFydHMgLi4uaW50ZXJmYWNle30pIGNvbmNhdEV4cHIgewoJcmV0dXJuIGNvbmNhdEV4cHIocGFydHMpCn0KCi8vIGFsaWFzRXhwciBoZWxwcyB0byBhbGlhcyBwYXJ0IG9mIFNRTCBxdWVyeSBnZW5lcmF0ZWQgd2l0aCB1bmRlcmx5aW5nICJleHByIgp0eXBlIGFsaWFzRXhwciBzdHJ1Y3QgewoJZXhwciAgU3FsaXplcgoJYWxpYXMgc3RyaW5nCn0KCi8vIEFsaWFzIGFsbG93cyB0byBkZWZpbmUgYWxpYXMgZm9yIGNvbHVtbiBpbiBTZWxlY3RCdWlsZGVyLiBVc2VmdWwgd2hlbiBjb2x1bW4gaXMKLy8gZGVmaW5lZCBhcyBjb21wbGV4IGV4cHJlc3Npb24gbGlrZSBJRiBvciBDQVNFCi8vIEV4OgovLwkJLkNvbHVtbihBbGlhcyhjYXNlU3RtdCwgImNhc2VfY29sdW1uIikpCmZ1bmMgQWxpYXMoZXhwciBTcWxpemVyLCBhbGlhcyBzdHJpbmcpIGFsaWFzRXhwciB7CglyZXR1cm4gYWxpYXNFeHBye2V4cHIsIGFsaWFzfQp9CgpmdW5jIChlIGFsaWFzRXhwcikgVG9TcWwoKSAoc3FsIHN0cmluZywgYXJncyBbXWludGVyZmFjZXt9LCBlcnIgZXJyb3IpIHsKCXNxbCwgYXJncywgZXJyID0gZS5leHByLlRvU3FsKCkKCWlmIGVyciA9PSBuaWwgewoJCXNxbCA9IGZtdC5TcHJpbnRmKCIoJXMpIEFTICVzIiwgc3FsLCBlLmFsaWFzKQoJfQoJcmV0dXJuCn0KCi8vIEVxIGlzIHN5bnRhY3RpYyBzdWdhciBmb3IgdXNlIHdpdGggV2hlcmUvSGF2aW5nL1NldCBtZXRob2RzLgp0eXBlIEVxIG1hcFtzdHJpbmddaW50ZXJmYWNle30KCmZ1bmMgKGVxIEVxKSB0b1NRTCh1c2VOb3RPcHIgYm9vbCkgKHNxbCBzdHJpbmcsIGFyZ3MgW11pbnRlcmZhY2V7fSwgZXJyIGVycm9yKSB7CglpZiBsZW4oZXEpICE9IDAgewoJCS8vIEVtcHR5IFNxbHt9IGV2YWx1YXRlcyB0byB0cnVlLgoJCXNxbCA9IHNxbFRydWUKCQlyZXR1cm4KCX0KCgl2YXIgKAoJCWV4cHJzICAgICAgIFtdc3RyaW5nCgkJZXF1YWxPcHIgICAgPSAiPSIKCQlpbk9wciAgICAgICA9ICJJTiIKCQludWxsT3ByICAgICA9ICJJUyIKCQlpbkVtcHR5RXhwciA9IHNxbEZhbHNlCgkpCgoJaWYgdXNlTm90T3ByIHsKCQllcXVhbE9wciA9ICI8PiIKCQlpbk9wciA9ICJOT1QgSU4iCgkJbnVsbE9wciA9ICJJUyBOT1QiCgkJaW5FbXB0eUV4cHIgPSBzcWxUcnVlCgl9CgoJc29ydGVkS2V5cyA6PSBnZXRTb3J0ZWRLZXlzKGVxKQoJZm9yIF8sIGtleSA6PSByYW5nZSBzb3J0ZWRLZXlzIHsKCQl2YXIgZXhwciBzdHJpbmcKCQl2YWwgOj0gZXFba2V5XQoKCQlzd2l0Y2ggdiA6PSB2YWwuKHR5cGUpIHsKCQljYXNlIGRyaXZlci5WYWx1ZXI6CgkJCWlmIHZhbCwgZXJyID0gdi5WYWx1ZSgpOyBlcnIgIT0gbmlsIHsKCQkJCXJldHVybgoJCQl9CgkJfQoKCQlyIDo9IHJlZmxlY3QuVmFsdWVPZih2YWwpCgkJaWYgci5LaW5kKCkgPT0gcmVmbGVjdC5QdHIgewoJCQlpZiByLklzTmlsKCkgewoJCQkJdmFsID0gbmlsCgkJCX0gZWxzZSB7CgkJCQl2YWwgPSByLkVsZW0oKS5JbnRlcmZhY2UoKQoJCQl9CgkJfQoKCQlpZiB2YWwgPT0gbmlsIHsKCQkJZXhwciA9IGZtdC5TcHJpbnRmKCIlcyAlcyBOVUxMIiwga2V5LCBudWxsT3ByKQoJCX0gZWxzZSB7CgkJCWlmIGlzTGlzdFR5cGUodmFsKSB7CgkJCQl2YWxWYWwgOj0gcmVmbGVjdC5WYWx1ZU9mKHZhbCkKCQkJCWlmIHZhbFZhbC5MZW4oKSA9PSAwIHsKCQkJCQlleHByID0gaW5FbXB0eUV4cHIKCQkJCQlpZiBhcmdzID09IG5pbCB7CgkJCQkJCWFyZ3MgPSBbXWludGVyZmFjZXt9e30KCQkJCQl9CgkJCQl9IGVsc2UgewoJCQkJCWZvciBpIDo9IDA7IGkgPCB2YWxWYWwuTGVuKCk7IGkrKyB7CgkJCQkJCWFyZ3MgPSBhcHBlbmQoYXJncywgdmFsVmFsLkluZGV4KGkpLkludGVyZmFjZSgpKQoJCQkJCX0KCQkJCQlleHByID0gZm10LlNwcmludGYoIiVzICVzICglcykiLCBrZXksIGluT3ByLCBQbGFjZWhvbGRlcnModmFsVmFsLkxlbigpKSkKCQkJCX0KCQkJfSBlbHNlIHsKCQkJCWV4cHIgPSBmbXQuU3ByaW50ZigiJXMgJXMgPyIsIGtleSwgZXF1YWxPcHIpCgkJCQlhcmdzID0gYXBwZW5kKGFyZ3MsIHZhbCkKCQkJfQoJCX0KCQlleHBycyA9IGFwcGVuZChleHBycywgZXhwcikKCX0KCXNxbCA9IHN0cmluZ3MuSm9pbihleHBycywgIiBBTkQgIikKCXJldHVybgp9CgpmdW5jIChlcSBFcSkgVG9TcWwoKSAoc3FsIHN0cmluZywgYXJncyBbXWludGVyZmFjZXt9LCBlcnIgZXJyb3IpIHsKCXJldHVybiBlcS50b1NRTChmYWxzZSkKfQoKLy8gTm90RXEgaXMgc3ludGFjdGljIHN1Z2FyIGZvciB1c2Ugd2l0aCBXaGVyZS9IYXZpbmcvU2V0IG1ldGhvZHMuCi8vIEV4OgovLyAgICAgLldoZXJlKE5vdEVxeyJpZCI6IDF9KSA9PSAiaWQgPD4gMSIKdHlwZSBOb3RFcSBFcQoKZnVuYyAobmVxIE5vdEVxKSBUb1NxbCgpIChzcWwgc3RyaW5nLCBhcmdzIFtdaW50ZXJmYWNle30sIGVyciBlcnJvcikgewoJcmV0dXJuIEVxKG5lcSkudG9TUUwodHJ1ZSkKfQoKLy8gTGlrZSBpcyBzeW50YWN0aWMgc3VnYXIgZm9yIHVzZSB3aXRoIExJS0UgY29uZGl0aW9ucy4KLy8gRXg6Ci8vICAgICAuV2hlcmUoTGlrZXsibmFtZSI6ICIlaXJyZWwifSkKdHlwZSBMaWtlIG1hcFtzdHJpbmddaW50ZXJmYWNle30KCmZ1bmMgKGxrIExpa2UpIHRvU3FsKG9wciBzdHJpbmcpIChzcWwgc3RyaW5nLCBhcmdzIFtdaW50ZXJmYWNle30sIGVyciBlcnJvcikgewoJdmFyIGV4cHJzIFtdc3RyaW5nCglmb3Iga2V5LCB2YWwgOj0gcmFuZ2UgbGsgewoJCWV4cHIgOj0gIiIKCgkJc3dpdGNoIHYgOj0gdmFsLih0eXBlKSB7CgkJY2FzZSBkcml2ZXIuVmFsdWVyOgoJCQlpZiB2YWwsIGVyciA9IHYuVmFsdWUoKTsgZXJyICE9IG5pbCB7CgkJCQlyZXR1cm4KCQkJfQoJCX0KCgkJaWYgdmFsID09IG5pbCB7CgkJCWVyciA9IGZtdC5FcnJvcmYoImNhbm5vdCB1c2UgbnVsbCB3aXRoIGxpa2Ugb3BlcmF0b3JzIikKCQkJcmV0dXJuCgkJfSBlbHNlIHsKCQkJaWYgaXNMaXN0VHlwZSh2YWwpIHsKCQkJCWVyciA9IGZtdC5FcnJvcmYoImNhbm5vdCB1c2UgYXJyYXkgb3Igc2xpY2Ugd2l0aCBsaWtlIG9wZXJhdG9ycyIpCgkJCQlyZXR1cm4KCQkJfSBlbHNlIHsKCQkJCWV4cHIgPSBmbXQuU3ByaW50ZigiJXMgJXMgPyIsIGtleSwgb3ByKQoJCQkJYXJncyA9IGFwcGVuZChhcmdzLCB2YWwpCgkJCX0KCQl9CgkJZXhwcnMgPSBhcHBlbmQoZXhwcnMsIGV4cHIpCgl9CglzcWwgPSBzdHJpbmdzLkpvaW4oZXhwcnMsICIgQU5EICIpCglyZXR1cm4KfQoKZnVuYyAobGsgTGlrZSkgVG9TcWwoKSAoc3FsIHN0cmluZywgYXJncyBbXWludGVyZmFjZXt9LCBlcnIgZXJyb3IpIHsKCXJldHVybiBsay50b1NxbCgiTElLRSIpCn0KCi8vIE5vdExpa2UgaXMgc3ludGFjdGljIHN1Z2FyIGZvciB1c2Ugd2l0aCBMSUtFIGNvbmRpdGlvbnMuCi8vIEV4OgovLyAgICAgLldoZXJlKE5vdExpa2V7Im5hbWUiOiAiJWlycmVsIn0pCnR5cGUgTm90TGlrZSBMaWtlCgpmdW5jIChubGsgTm90TGlrZSkgVG9TcWwoKSAoc3FsIHN0cmluZywgYXJncyBbXWludGVyZmFjZXt9LCBlcnIgZXJyb3IpIHsKCXJldHVybiBMaWtlKG5saykudG9TcWwoIk5PVCBMSUtFIikKfQoKLy8gSUxpa2UgaXMgc3ludGFjdGljIHN1Z2FyIGZvciB1c2Ugd2l0aCBJTElLRSBjb25kaXRpb25zLgovLyBFeDoKLy8gICAgLldoZXJlKElMaWtleyJuYW1lIjogInNxJSJ9KQp0eXBlIElMaWtlIExpa2UKCmZ1bmMgKGlsayBJTGlrZSkgVG9TcWwoKSAoc3FsIHN0cmluZywgYXJncyBbXWludGVyZmFjZXt9LCBlcnIgZXJyb3IpIHsKCXJldHVybiBMaWtlKGlsaykudG9TcWwoIklMSUtFIikKfQoKLy8gTm90SUxpa2UgaXMgc3ludGFjdGljIHN1Z2FyIGZvciB1c2Ugd2l0aCBJTElLRSBjb25kaXRpb25zLgovLyBFeDoKLy8gICAgLldoZXJlKE5vdElMaWtleyJuYW1lIjogInNxJSJ9KQp0eXBlIE5vdElMaWtlIExpa2UKCmZ1bmMgKG5pbGsgTm90SUxpa2UpIFRvU3FsKCkgKHNxbCBzdHJpbmcsIGFyZ3MgW11pbnRlcmZhY2V7fSwgZXJyIGVycm9yKSB7CglyZXR1cm4gTGlrZShuaWxrKS50b1NxbCgiTk9UIElMSUtFIikKfQoKLy8gTHQgaXMgc3ludGFjdGljIHN1Z2FyIGZvciB1c2Ugd2l0aCBXaGVyZS9IYXZpbmcvU2V0IG1ldGhvZHMuCi8vIEV4OgovLyAgICAgLldoZXJlKEx0eyJpZCI6IDF9KQp0eXBlIEx0IG1hcFtzdHJpbmddaW50ZXJmYWNle30KCmZ1bmMgKGx0IEx0KSB0b1NxbChvcHBvc2l0ZSwgb3JFcSBib29sKSAoc3FsIHN0cmluZywgYXJncyBbXWludGVyZmFjZXt9LCBlcnIgZXJyb3IpIHsKCXZhciAoCgkJZXhwcnMgW11zdHJpbmcKCQlvcHIgICA9ICI8IgoJKQoKCWlmIG9wcG9zaXRlIHsKCQlvcHIgPSAiPiIKCX0KCglpZiBvckVxIHsKCQlvcHIgPSBmbXQuU3ByaW50ZigiJXMlcyIsIG9wciwgIj0iKQoJfQoKCXNvcnRlZEtleXMgOj0gZ2V0U29ydGVkS2V5cyhsdCkKCWZvciBfLCBrZXkgOj0gcmFuZ2Ugc29ydGVkS2V5cyB7CgkJdmFyIGV4cHIgc3RyaW5nCgkJdmFsIDo9IGx0W2tleV0KCgkJc3dpdGNoIHYgOj0gdmFsLih0eXBlKSB7CgkJY2FzZSBkcml2ZXIuVmFsdWVyOgoJCQlpZiB2YWwsIGVyciA9IHYuVmFsdWUoKTsgZXJyICE9IG5pbCB7CgkJCQlyZXR1cm4KCQkJfQoJCX0KCgkJaWYgdmFsID09IG5pbCB7CgkJCWVyciA9IGZtdC5FcnJvcmYoImNhbm5vdCB1c2UgbnVsbCB3aXRoIGxlc3MgdGhhbiBvciBncmVhdGVyIHRoYW4gb3BlcmF0b3JzIikKCQkJcmV0dXJuCgkJfQoJCWlmIGlzTGlzdFR5cGUodmFsKSB7CgkJCWVyciA9IGZtdC5FcnJvcmYoImNhbm5vdCB1c2UgYXJyYXkgb3Igc2xpY2Ugd2l0aCBsZXNzIHRoYW4gb3IgZ3JlYXRlciB0aGFuIG9wZXJhdG9ycyIpCgkJCXJldHVybgoJCX0KCQlleHByID0gZm10LlNwcmludGYoIiVzICVzID8iLCBrZXksIG9wcikKCQlhcmdzID0gYXBwZW5kKGFyZ3MsIHZhbCkKCgkJZXhwcnMgPSBhcHBlbmQoZXhwcnMsIGV4cHIpCgl9CglzcWwgPSBzdHJpbmdzLkpvaW4oZXhwcnMsICIgQU5EICIpCglyZXR1cm4KfQoKZnVuYyAobHQgTHQpIFRvU3FsKCkgKHNxbCBzdHJpbmcsIGFyZ3MgW11pbnRlcmZhY2V7fSwgZXJyIGVycm9yKSB7CglyZXR1cm4gbHQudG9TcWwoZmFsc2UsIGZhbHNlKQp9CgovLyBMdE9yRXEgaXMgc3ludGFjdGljIHN1Z2FyIGZvciB1c2Ugd2l0aCBXaGVyZS9IYXZpbmcvU2V0IG1ldGhvZHMuCi8vIEV4OgovLyAgICAgLldoZXJlKEx0T3JFcXsiaWQiOiAxfSkgPT0gImlkIDw9IDEiCnR5cGUgTHRPckVxIEx0CgpmdW5jIChsdE9yRXEgTHRPckVxKSBUb1NxbCgpIChzcWwgc3RyaW5nLCBhcmdzIFtdaW50ZXJmYWNle30sIGVyciBlcnJvcikgewoJcmV0dXJuIEx0KGx0T3JFcSkudG9TcWwoZmFsc2UsIHRydWUpCn0KCi8vIEd0IGlzIHN5bnRhY3RpYyBzdWdhciBmb3IgdXNlIHdpdGggV2hlcmUvSGF2aW5nL1NldCBtZXRob2RzLgovLyBFeDoKLy8gICAgIC5XaGVyZShHdHsiaWQiOiAxfSkgPT0gImlkID4gMSIKdHlwZSBHdCBMdAoKZnVuYyAoZ3QgR3QpIFRvU3FsKCkgKHNxbCBzdHJpbmcsIGFyZ3MgW11pbnRlcmZhY2V7fSwgZXJyIGVycm9yKSB7CglyZXR1cm4gTHQoZ3QpLnRvU3FsKHRydWUsIGZhbHNlKQp9CgovLyBHdE9yRXEgaXMgc3ludGFjdGljIHN1Z2FyIGZvciB1c2Ugd2l0aCBXaGVyZS9IYXZpbmcvU2V0IG1ldGhvZHMuCi8vIEV4OgovLyAgICAgLldoZXJlKEd0T3JFcXsiaWQiOiAxfSkgPT0gImlkID49IDEiCnR5cGUgR3RPckVxIEx0CgpmdW5jIChndE9yRXEgR3RPckVxKSBUb1NxbCgpIChzcWwgc3RyaW5nLCBhcmdzIFtdaW50ZXJmYWNle30sIGVyciBlcnJvcikgewoJcmV0dXJuIEx0KGd0T3JFcSkudG9TcWwodHJ1ZSwgdHJ1ZSkKfQoKdHlwZSBjb25qIFtdU3FsaXplcgoKZnVuYyAoYyBjb25qKSBqb2luKHNlcCwgZGVmYXVsdEV4cHIgc3RyaW5nKSAoc3FsIHN0cmluZywgYXJncyBbXWludGVyZmFjZXt9LCBlcnIgZXJyb3IpIHsKCWlmIGxlbihjKSA9PSAwIHsKCQlyZXR1cm4gZGVmYXVsdEV4cHIsIFtdaW50ZXJmYWNle317fSwgbmlsCgl9Cgl2YXIgc3FsUGFydHMgW11zdHJpbmcKCWZvciBfLCBzcWxpemVyIDo9IHJhbmdlIGMgewoJCXBhcnRTUUwsIHBhcnRBcmdzLCBlcnIgOj0gbmVzdGVkVG9TcWwoc3FsaXplcikKCQlpZiBlcnIgIT0gbmlsIHsKCQkJcmV0dXJuICIiLCBuaWwsIGVycgoJCX0KCQlpZiBwYXJ0U1FMICE9ICIiIHsKCQkJc3FsUGFydHMgPSBhcHBlbmQoc3FsUGFydHMsIHBhcnRTUUwpCgkJCWFyZ3MgPSBhcHBlbmQoYXJncywgcGFydEFyZ3MuLi4pCgkJfQoJfQoJaWYgbGVuKHNxbFBhcnRzKSA+IDAgewoJCXNxbCA9IGZtdC5TcHJpbnRmKCIoJXMpIiwgc3RyaW5ncy5Kb2luKHNxbFBhcnRzLCBzZXApKQoJfQoJcmV0dXJuCn0KCi8vIEFuZCBjb25qdW5jdGlvbiBTcWxpemVycwp0eXBlIEFuZCBjb25qCgpmdW5jIChhIEFuZCkgVG9TcWwoKSAoc3RyaW5nLCBbXWludGVyZmFjZXt9LCBlcnJvcikgewoJcmV0dXJuIGNvbmooYSkuam9pbigiIEFORCAiLCBzcWxUcnVlKQp9CgovLyBPciBjb25qdW5jdGlvbiBTcWxpemVycwp0eXBlIE9yIGNvbmoKCmZ1bmMgKG8gT3IpIFRvU3FsKCkgKHN0cmluZywgW11pbnRlcmZhY2V7fSwgZXJyb3IpIHsKCXJldHVybiBjb25qKG8pLmpvaW4oIiBPUiAiLCBzcWxGYWxzZSkKfQoKZnVuYyBnZXRTb3J0ZWRLZXlzKGV4cCBtYXBbc3RyaW5nXWludGVyZmFjZXt9KSBbXXN0cmluZyB7Cglzb3J0ZWRLZXlzIDo9IG1ha2UoW11zdHJpbmcsIDAsIGxlbihleHApKQoJZm9yIGsgOj0gcmFuZ2UgZXhwIHsKCQlzb3J0ZWRLZXlzID0gYXBwZW5kKHNvcnRlZEtleXMsIGspCgl9Cglzb3J0LlN0cmluZ3Moc29ydGVkS2V5cykKCXJldHVybiBzb3J0ZWRLZXlzCn0KCmZ1bmMgaXNMaXN0VHlwZSh2YWwgaW50ZXJmYWNle30pIGJvb2wgewoJaWYgZHJpdmVyLklzVmFsdWUodmFsKSB7CgkJcmV0dXJuIGZhbHNlCgl9Cgl2YWxWYWwgOj0gcmVmbGVjdC5WYWx1ZU9mKHZhbCkKCXJldHVybiB2YWxWYWwuS2luZCgpID09IHJlZmxlY3QuQXJyYXkgfHwgdmFsVmFsLktpbmQoKSA9PSByZWZsZWN0LlNsaWNlCn0K", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/validation/canaries/stale-reward.sh b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/validation/openenv.json b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..ce285de5ca2cffe893e9ba113e89f6f2c4f8f179 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__c7xrz7e0/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "47df11856924f5661596b9e9704b9437fb85261da8f5c478d8259935d477dda0", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/Dockerfile b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..76a175da25ac85b0b250b59a27ccee287c47b1c7 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-go-055c69f17f410bee-starter-v1@sha256:9dfb6b7417f54d78d50e6e6bdd951b854ed8da8f5f1782f4fe563a85e1cd0b7a +WORKDIR /testbed diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/.gitignore b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..4a0699f0b7f3ec657f5671571adb0acf832f0fcd --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/.gitignore @@ -0,0 +1 @@ +squirrel.test \ No newline at end of file diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/.travis.yml b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..7bb6da4878bfe468cc587a2afaaf955ddcab8e3c --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/.travis.yml @@ -0,0 +1,30 @@ +language: go + +go: + - 1.11.x + - 1.12.x + - 1.13.x + +services: + - mysql + - postgresql + +# Setting sudo access to false will let Travis CI use containers rather than +# VMs to run the tests. For more details see: +# - http://docs.travis-ci.com/user/workers/container-based-infrastructure/ +# - http://docs.travis-ci.com/user/workers/standard-infrastructure/ +sudo: false + +before_script: + - mysql -e 'CREATE DATABASE squirrel;' + - psql -c 'CREATE DATABASE squirrel;' -U postgres + +script: + - go test + - cd integration + - go test -args -driver sqlite3 + - go test -args -driver mysql -dataSource travis@/squirrel + - go test -args -driver postgres -dataSource 'postgres://postgres@localhost/squirrel?sslmode=disable' + +notifications: + irc: "irc.freenode.net#masterminds" diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/LICENSE b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b459007fd88f4ed55a1be88a8b2711f3bc98ed5f --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/LICENSE @@ -0,0 +1,23 @@ +MIT License + +Squirrel: The Masterminds +Copyright (c) 2014-2015, Lann Martin. Copyright (C) 2015-2016, Google. Copyright (C) 2015, Matt Farina and Matt Butcher. + + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/README.md b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1d37f282f1cd23d015dd059673e4312755ebb99c --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/README.md @@ -0,0 +1,142 @@ +[![Stability: Maintenance](https://masterminds.github.io/stability/maintenance.svg)](https://masterminds.github.io/stability/maintenance.html) +### Squirrel is "complete". +Bug fixes will still be merged (slowly). Bug reports are welcome, but I will not necessarily respond to them. If another fork (or substantially similar project) actively improves on what Squirrel does, let me know and I may link to it here. + + +# Squirrel - fluent SQL generator for Go + +```go +import "github.com/Masterminds/squirrel" +``` + + +[![GoDoc](https://godoc.org/github.com/Masterminds/squirrel?status.png)](https://godoc.org/github.com/Masterminds/squirrel) +[![Build Status](https://api.travis-ci.org/Masterminds/squirrel.svg?branch=master)](https://travis-ci.org/Masterminds/squirrel) + +**Squirrel is not an ORM.** For an application of Squirrel, check out +[structable, a table-struct mapper](https://github.com/Masterminds/structable) + + +Squirrel helps you build SQL queries from composable parts: + +```go +import sq "github.com/Masterminds/squirrel" + +users := sq.Select("*").From("users").Join("emails USING (email_id)") + +active := users.Where(sq.Eq{"deleted_at": nil}) + +sql, args, err := active.ToSql() + +sql == "SELECT * FROM users JOIN emails USING (email_id) WHERE deleted_at IS NULL" +``` + +```go +sql, args, err := sq. + Insert("users").Columns("name", "age"). + Values("moe", 13).Values("larry", sq.Expr("? + 5", 12)). + ToSql() + +sql == "INSERT INTO users (name,age) VALUES (?,?),(?,? + 5)" +``` + +Squirrel can also execute queries directly: + +```go +stooges := users.Where(sq.Eq{"username": []string{"moe", "larry", "curly", "shemp"}}) +three_stooges := stooges.Limit(3) +rows, err := three_stooges.RunWith(db).Query() + +// Behaves like: +rows, err := db.Query("SELECT * FROM users WHERE username IN (?,?,?,?) LIMIT 3", + "moe", "larry", "curly", "shemp") +``` + +Squirrel makes conditional query building a breeze: + +```go +if len(q) > 0 { + users = users.Where("name LIKE ?", fmt.Sprint("%", q, "%")) +} +``` + +Squirrel wants to make your life easier: + +```go +// StmtCache caches Prepared Stmts for you +dbCache := sq.NewStmtCache(db) + +// StatementBuilder keeps your syntax neat +mydb := sq.StatementBuilder.RunWith(dbCache) +select_users := mydb.Select("*").From("users") +``` + +Squirrel loves PostgreSQL: + +```go +psql := sq.StatementBuilder.PlaceholderFormat(sq.Dollar) + +// You use question marks for placeholders... +sql, _, _ := psql.Select("*").From("elephants").Where("name IN (?,?)", "Dumbo", "Verna").ToSql() + +/// ...squirrel replaces them using PlaceholderFormat. +sql == "SELECT * FROM elephants WHERE name IN ($1,$2)" + + +/// You can retrieve id ... +query := sq.Insert("nodes"). + Columns("uuid", "type", "data"). + Values(node.Uuid, node.Type, node.Data). + Suffix("RETURNING \"id\""). + RunWith(m.db). + PlaceholderFormat(sq.Dollar) + +query.QueryRow().Scan(&node.id) +``` + +You can escape question marks by inserting two question marks: + +```sql +SELECT * FROM nodes WHERE meta->'format' ??| array[?,?] +``` + +will generate with the Dollar Placeholder: + +```sql +SELECT * FROM nodes WHERE meta->'format' ?| array[$1,$2] +``` + +## FAQ + +* **How can I build an IN query on composite keys / tuples, e.g. `WHERE (col1, col2) IN ((1,2),(3,4))`? ([#104](https://github.com/Masterminds/squirrel/issues/104))** + + Squirrel does not explicitly support tuples, but you can get the same effect with e.g.: + + ```go + sq.Or{ + sq.Eq{"col1": 1, "col2": 2}, + sq.Eq{"col1": 3, "col2": 4}} + ``` + + ```sql + WHERE (col1 = 1 AND col2 = 2) OR (col1 = 3 AND col2 = 4) + ``` + + (which should produce the same query plan as the tuple version) + +* **Why doesn't `Eq{"mynumber": []uint8{1,2,3}}` turn into an `IN` query? ([#114](https://github.com/Masterminds/squirrel/issues/114))** + + Values of type `[]byte` are handled specially by `database/sql`. In Go, [`byte` is just an alias of `uint8`](https://golang.org/pkg/builtin/#byte), so there is no way to distinguish `[]uint8` from `[]byte`. + +* **Some features are poorly documented!** + + This isn't a frequent complaints section! + +* **Some features are poorly documented?** + + Yes. The tests should be considered a part of the documentation; take a look at those for ideas on how to express more complex queries. + +## License + +Squirrel is released under the +[MIT License](http://www.opensource.org/licenses/MIT). diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/case.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/case.go new file mode 100644 index 0000000000000000000000000000000000000000..299e14b9d4a08b3966bffc82e9224b6e3def4d58 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/case.go @@ -0,0 +1,128 @@ +package squirrel + +import ( + "bytes" + "errors" + + "github.com/lann/builder" +) + +func init() { + builder.Register(CaseBuilder{}, caseData{}) +} + +// sqlizerBuffer is a helper that allows to write many Sqlizers one by one +// without constant checks for errors that may come from Sqlizer +type sqlizerBuffer struct { + bytes.Buffer + args []interface{} + err error +} + +// WriteSql converts Sqlizer to SQL strings and writes it to buffer +func (b *sqlizerBuffer) WriteSql(item Sqlizer) { + if b.err != nil { + return + } + + var str string + var args []interface{} + str, args, b.err = nestedToSql(item) + + if b.err != nil { + return + } + + b.WriteString(str) + b.WriteByte(' ') + b.args = append(b.args, args...) +} + +func (b *sqlizerBuffer) ToSql() (string, []interface{}, error) { + return b.String(), b.args, b.err +} + +// whenPart is a helper structure to describe SQLs "WHEN ... THEN ..." expression +type whenPart struct { + when Sqlizer + then Sqlizer +} + +func newWhenPart(when interface{}, then interface{}) whenPart { + return whenPart{newPart(when), newPart(then)} +} + +// caseData holds all the data required to build a CASE SQL construct +type caseData struct { + What Sqlizer + WhenParts []whenPart + Else Sqlizer +} + +// ToSql implements Sqlizer +func (d *caseData) ToSql() (sqlStr string, args []interface{}, err error) { + if len(d.WhenParts) == 0 { + err = errors.New("case expression must contain at lease one WHEN clause") + + return + } + + sql := sqlizerBuffer{} + + sql.WriteString("CASE ") + if d.What != nil { + sql.WriteSql(d.What) + } + + for _, p := range d.WhenParts { + sql.WriteString("WHEN ") + sql.WriteSql(p.when) + sql.WriteString("THEN ") + sql.WriteSql(p.then) + } + + if d.Else != nil { + sql.WriteString("ELSE ") + sql.WriteSql(d.Else) + } + + sql.WriteString("END") + + return sql.ToSql() +} + +// CaseBuilder builds SQL CASE construct which could be used as parts of queries. +type CaseBuilder builder.Builder + +// ToSql builds the query into a SQL string and bound args. +func (b CaseBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(caseData) + return data.ToSql() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b CaseBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// what sets optional value for CASE construct "CASE [value] ..." +func (b CaseBuilder) what(expr interface{}) CaseBuilder { + return builder.Set(b, "What", newPart(expr)).(CaseBuilder) +} + +// When adds "WHEN ... THEN ..." part to CASE construct +func (b CaseBuilder) When(when interface{}, then interface{}) CaseBuilder { + // TODO: performance hint: replace slice of WhenPart with just slice of parts + // where even indices of the slice belong to "when"s and odd indices belong to "then"s + return builder.Append(b, "WhenParts", newWhenPart(when, then)).(CaseBuilder) +} + +// What sets optional "ELSE ..." part for CASE construct +func (b CaseBuilder) Else(expr interface{}) CaseBuilder { + return builder.Set(b, "Else", newPart(expr)).(CaseBuilder) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/delete.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/delete.go new file mode 100644 index 0000000000000000000000000000000000000000..c462d4c4a0b27c633b03be8e60f8912572b4053e --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/delete.go @@ -0,0 +1,191 @@ +package squirrel + +import ( + "bytes" + "database/sql" + "fmt" + "strings" + + "github.com/lann/builder" +) + +type deleteData struct { + PlaceholderFormat PlaceholderFormat + RunWith BaseRunner + Prefixes []Sqlizer + From string + WhereParts []Sqlizer + OrderBys []string + Limit string + Offset string + Suffixes []Sqlizer +} + +func (d *deleteData) Exec() (sql.Result, error) { + if d.RunWith != nil { + return nil, RunnerNotSet + } + return ExecWith(d.RunWith, d) +} + +func (d *deleteData) ToSql() (sqlStr string, args []interface{}, err error) { + if len(d.From) == 0 { + err = fmt.Errorf("delete statements must specify a From table") + return + } + + sql := &bytes.Buffer{} + + if len(d.Prefixes) > 0 { + args, err = appendToSql(d.Prefixes, sql, " ", args) + if err != nil { + return + } + + sql.WriteString(" ") + } + + sql.WriteString("DELETE FROM ") + sql.WriteString(d.From) + + if len(d.WhereParts) > 0 { + sql.WriteString(" WHERE ") + args, err = appendToSql(d.WhereParts, sql, " AND ", args) + if err != nil { + return + } + } + + if len(d.OrderBys) > 0 { + sql.WriteString(" ORDER BY ") + sql.WriteString(strings.Join(d.OrderBys, ", ")) + } + + if len(d.Limit) > 0 { + sql.WriteString(" LIMIT ") + sql.WriteString(d.Limit) + } + + if len(d.Offset) > 0 { + sql.WriteString(" OFFSET ") + sql.WriteString(d.Offset) + } + + if len(d.Suffixes) > 0 { + sql.WriteString(" ") + args, err = appendToSql(d.Suffixes, sql, " ", args) + if err != nil { + return + } + } + + sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sql.String()) + return +} + +// Builder + +// DeleteBuilder builds SQL DELETE statements. +type DeleteBuilder builder.Builder + +func init() { + builder.Register(DeleteBuilder{}, deleteData{}) +} + +// Format methods + +// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the +// query. +func (b DeleteBuilder) PlaceholderFormat(f PlaceholderFormat) DeleteBuilder { + return builder.Set(b, "PlaceholderFormat", f).(DeleteBuilder) +} + +// Runner methods + +// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec. +func (b DeleteBuilder) RunWith(runner BaseRunner) DeleteBuilder { + return setRunWith(b, runner).(DeleteBuilder) +} + +// Exec builds and Execs the query with the Runner set by RunWith. +func (b DeleteBuilder) Exec() (sql.Result, error) { + data := builder.GetStruct(b).(deleteData) + return data.Exec() +} + +// SQL methods + +// ToSql builds the query into a SQL string and bound args. +func (b DeleteBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(deleteData) + return data.ToSql() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b DeleteBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// Prefix adds an expression to the beginning of the query +func (b DeleteBuilder) Prefix(sql string, args ...interface{}) DeleteBuilder { + return b.PrefixExpr(Expr(sql, args...)) +} + +// PrefixExpr adds an expression to the very beginning of the query +func (b DeleteBuilder) PrefixExpr(expr Sqlizer) DeleteBuilder { + return builder.Append(b, "Prefixes", expr).(DeleteBuilder) +} + +// From sets the table to be deleted from. +func (b DeleteBuilder) From(from string) DeleteBuilder { + return builder.Set(b, "From", from).(DeleteBuilder) +} + +// Where adds WHERE expressions to the query. +// +// See SelectBuilder.Where for more information. +func (b DeleteBuilder) Where(pred interface{}, args ...interface{}) DeleteBuilder { + return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(DeleteBuilder) +} + +// OrderBy adds ORDER BY expressions to the query. +func (b DeleteBuilder) OrderBy(orderBys ...string) DeleteBuilder { + return builder.Extend(b, "OrderBys", orderBys).(DeleteBuilder) +} + +// Limit sets a LIMIT clause on the query. +func (b DeleteBuilder) Limit(limit uint64) DeleteBuilder { + return builder.Set(b, "Limit", fmt.Sprintf("%d", limit)).(DeleteBuilder) +} + +// Offset sets a OFFSET clause on the query. +func (b DeleteBuilder) Offset(offset uint64) DeleteBuilder { + return builder.Set(b, "Offset", fmt.Sprintf("%d", offset)).(DeleteBuilder) +} + +// Suffix adds an expression to the end of the query +func (b DeleteBuilder) Suffix(sql string, args ...interface{}) DeleteBuilder { + return b.SuffixExpr(Expr(sql, args...)) +} + +// SuffixExpr adds an expression to the end of the query +func (b DeleteBuilder) SuffixExpr(expr Sqlizer) DeleteBuilder { + return builder.Append(b, "Suffixes", expr).(DeleteBuilder) +} + +func (b DeleteBuilder) Query() (*sql.Rows, error) { + data := builder.GetStruct(b).(deleteData) + return data.Query() +} + +func (d *deleteData) Query() (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return QueryWith(d.RunWith, d) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/delete_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/delete_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..de83c55df3c601102c1be68a36bba7eb57a074d5 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/delete_ctx.go @@ -0,0 +1,69 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + + "github.com/lann/builder" +) + +func (d *deleteData) ExecContext(ctx context.Context) (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(ExecerContext) + if !ok { + return nil, NoContextSupport + } + return ExecContextWith(ctx, ctxRunner, d) +} + +func (d *deleteData) QueryContext(ctx context.Context) (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(QueryerContext) + if !ok { + return nil, NoContextSupport + } + return QueryContextWith(ctx, ctxRunner, d) +} + +func (d *deleteData) QueryRowContext(ctx context.Context) RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRowerContext) + if !ok { + if _, ok := d.RunWith.(QueryerContext); !ok { + return &Row{err: RunnerNotQueryRunner} + } + return &Row{err: NoContextSupport} + } + return QueryRowContextWith(ctx, queryRower, d) +} + +// ExecContext builds and ExecContexts the query with the Runner set by RunWith. +func (b DeleteBuilder) ExecContext(ctx context.Context) (sql.Result, error) { + data := builder.GetStruct(b).(deleteData) + return data.ExecContext(ctx) +} + +// QueryContext builds and QueryContexts the query with the Runner set by RunWith. +func (b DeleteBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) { + data := builder.GetStruct(b).(deleteData) + return data.QueryContext(ctx) +} + +// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith. +func (b DeleteBuilder) QueryRowContext(ctx context.Context) RowScanner { + data := builder.GetStruct(b).(deleteData) + return data.QueryRowContext(ctx) +} + +// ScanContext is a shortcut for QueryRowContext().Scan. +func (b DeleteBuilder) ScanContext(ctx context.Context, dest ...interface{}) error { + return b.QueryRowContext(ctx).Scan(dest...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/expr.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/expr.go new file mode 100644 index 0000000000000000000000000000000000000000..eba1b4579e59dcb3e93c72c87bed8d8d391e6ba7 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/expr.go @@ -0,0 +1,419 @@ +package squirrel + +import ( + "bytes" + "database/sql/driver" + "fmt" + "reflect" + "sort" + "strings" +) + +const ( + // Portable true/false literals. + sqlTrue = "(1=1)" + sqlFalse = "(1=0)" +) + +type expr struct { + sql string + args []interface{} +} + +// Expr builds an expression from a SQL fragment and arguments. +// +// Ex: +// Expr("FROM_UNIXTIME(?)", t) +func Expr(sql string, args ...interface{}) Sqlizer { + return expr{sql: sql, args: args} +} + +func (e expr) ToSql() (sql string, args []interface{}, err error) { + simple := true + for _, arg := range e.args { + if _, ok := arg.(Sqlizer); ok { + simple = false + } + } + if simple { + return e.sql, e.args, nil + } + + buf := &bytes.Buffer{} + ap := e.args + sp := e.sql + + var isql string + var iargs []interface{} + + for err == nil && len(ap) > 0 && len(sp) > 0 { + i := strings.Index(sp, "?") + if i < 0 { + // no more placeholders + break + } + if len(sp) > i+1 && sp[i+1:i+2] == "?" { + // escaped "??"; append it and step past + buf.WriteString(sp[:i+2]) + sp = sp[i+2:] + continue + } + + if as, ok := ap[0].(Sqlizer); ok { + // sqlizer argument; expand it and append the result + isql, iargs, err = as.ToSql() + buf.WriteString(sp[:i]) + buf.WriteString(isql) + args = append(args, iargs...) + } else { + // normal argument; append it and the placeholder + buf.WriteString(sp[:i+1]) + args = append(args, ap[0]) + } + + // step past the argument and placeholder + ap = ap[1:] + sp = sp[i+1:] + } + + // append the remaining sql and arguments + buf.WriteString(sp) + return buf.String(), append(args, ap...), err +} + +type concatExpr []interface{} + +func (ce concatExpr) ToSql() (sql string, args []interface{}, err error) { + for _, part := range ce { + switch p := part.(type) { + case string: + sql += p + case Sqlizer: + pSql, pArgs, err := p.ToSql() + if err != nil { + return "", nil, err + } + sql += pSql + args = append(args, pArgs...) + default: + return "", nil, fmt.Errorf("%#v is not a string or Sqlizer", part) + } + } + return +} + +// ConcatExpr builds an expression by concatenating strings and other expressions. +// +// Ex: +// name_expr := Expr("CONCAT(?, ' ', ?)", firstName, lastName) +// ConcatExpr("COALESCE(full_name,", name_expr, ")") +func ConcatExpr(parts ...interface{}) concatExpr { + return concatExpr(parts) +} + +// aliasExpr helps to alias part of SQL query generated with underlying "expr" +type aliasExpr struct { + expr Sqlizer + alias string +} + +// Alias allows to define alias for column in SelectBuilder. Useful when column is +// defined as complex expression like IF or CASE +// Ex: +// .Column(Alias(caseStmt, "case_column")) +func Alias(expr Sqlizer, alias string) aliasExpr { + return aliasExpr{expr, alias} +} + +func (e aliasExpr) ToSql() (sql string, args []interface{}, err error) { + sql, args, err = e.expr.ToSql() + if err == nil { + sql = fmt.Sprintf("(%s) AS %s", sql, e.alias) + } + return +} + +// Eq is syntactic sugar for use with Where/Having/Set methods. +type Eq map[string]interface{} + +func (eq Eq) toSQL(useNotOpr bool) (sql string, args []interface{}, err error) { + if len(eq) == 0 { + // Empty Sql{} evaluates to true. + sql = sqlTrue + return + } + + var ( + exprs []string + equalOpr = "=" + inOpr = "IN" + nullOpr = "IS" + inEmptyExpr = sqlFalse + ) + + if useNotOpr { + equalOpr = "<>" + inOpr = "NOT IN" + nullOpr = "IS NOT" + inEmptyExpr = sqlTrue + } + + sortedKeys := getSortedKeys(eq) + for _, key := range sortedKeys { + var expr string + val := eq[key] + + switch v := val.(type) { + case driver.Valuer: + if val, err = v.Value(); err != nil { + return + } + } + + r := reflect.ValueOf(val) + if r.Kind() == reflect.Ptr { + if r.IsNil() { + val = nil + } else { + val = r.Elem().Interface() + } + } + + if val == nil { + expr = fmt.Sprintf("%s %s NULL", key, nullOpr) + } else { + if isListType(val) { + valVal := reflect.ValueOf(val) + if valVal.Len() == 0 { + expr = inEmptyExpr + if args == nil { + args = []interface{}{} + } + } else { + for i := 0; i < valVal.Len(); i++ { + args = append(args, valVal.Index(i).Interface()) + } + expr = fmt.Sprintf("%s %s (%s)", key, inOpr, Placeholders(valVal.Len())) + } + } else { + expr = fmt.Sprintf("%s %s ?", key, equalOpr) + args = append(args, val) + } + } + exprs = append(exprs, expr) + } + sql = strings.Join(exprs, " AND ") + return +} + +func (eq Eq) ToSql() (sql string, args []interface{}, err error) { + return eq.toSQL(false) +} + +// NotEq is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(NotEq{"id": 1}) == "id <> 1" +type NotEq Eq + +func (neq NotEq) ToSql() (sql string, args []interface{}, err error) { + return Eq(neq).toSQL(true) +} + +// Like is syntactic sugar for use with LIKE conditions. +// Ex: +// .Where(Like{"name": "%irrel"}) +type Like map[string]interface{} + +func (lk Like) toSql(opr string) (sql string, args []interface{}, err error) { + var exprs []string + for key, val := range lk { + expr := "" + + switch v := val.(type) { + case driver.Valuer: + if val, err = v.Value(); err != nil { + return + } + } + + if val == nil { + err = fmt.Errorf("cannot use null with like operators") + return + } else { + if isListType(val) { + err = fmt.Errorf("cannot use array or slice with like operators") + return + } else { + expr = fmt.Sprintf("%s %s ?", key, opr) + args = append(args, val) + } + } + exprs = append(exprs, expr) + } + sql = strings.Join(exprs, " AND ") + return +} + +func (lk Like) ToSql() (sql string, args []interface{}, err error) { + return lk.toSql("LIKE") +} + +// NotLike is syntactic sugar for use with LIKE conditions. +// Ex: +// .Where(NotLike{"name": "%irrel"}) +type NotLike Like + +func (nlk NotLike) ToSql() (sql string, args []interface{}, err error) { + return Like(nlk).toSql("NOT LIKE") +} + +// ILike is syntactic sugar for use with ILIKE conditions. +// Ex: +// .Where(ILike{"name": "sq%"}) +type ILike Like + +func (ilk ILike) ToSql() (sql string, args []interface{}, err error) { + return Like(ilk).toSql("ILIKE") +} + +// NotILike is syntactic sugar for use with ILIKE conditions. +// Ex: +// .Where(NotILike{"name": "sq%"}) +type NotILike Like + +func (nilk NotILike) ToSql() (sql string, args []interface{}, err error) { + return Like(nilk).toSql("NOT ILIKE") +} + +// Lt is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(Lt{"id": 1}) +type Lt map[string]interface{} + +func (lt Lt) toSql(opposite, orEq bool) (sql string, args []interface{}, err error) { + var ( + exprs []string + opr = "<" + ) + + if opposite { + opr = ">" + } + + if orEq { + opr = fmt.Sprintf("%s%s", opr, "=") + } + + sortedKeys := getSortedKeys(lt) + for _, key := range sortedKeys { + var expr string + val := lt[key] + + switch v := val.(type) { + case driver.Valuer: + if val, err = v.Value(); err != nil { + return + } + } + + if val == nil { + err = fmt.Errorf("cannot use null with less than or greater than operators") + return + } + if isListType(val) { + err = fmt.Errorf("cannot use array or slice with less than or greater than operators") + return + } + expr = fmt.Sprintf("%s %s ?", key, opr) + args = append(args, val) + + exprs = append(exprs, expr) + } + sql = strings.Join(exprs, " AND ") + return +} + +func (lt Lt) ToSql() (sql string, args []interface{}, err error) { + return lt.toSql(false, false) +} + +// LtOrEq is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(LtOrEq{"id": 1}) == "id <= 1" +type LtOrEq Lt + +func (ltOrEq LtOrEq) ToSql() (sql string, args []interface{}, err error) { + return Lt(ltOrEq).toSql(false, true) +} + +// Gt is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(Gt{"id": 1}) == "id > 1" +type Gt Lt + +func (gt Gt) ToSql() (sql string, args []interface{}, err error) { + return Lt(gt).toSql(true, false) +} + +// GtOrEq is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(GtOrEq{"id": 1}) == "id >= 1" +type GtOrEq Lt + +func (gtOrEq GtOrEq) ToSql() (sql string, args []interface{}, err error) { + return Lt(gtOrEq).toSql(true, true) +} + +type conj []Sqlizer + +func (c conj) join(sep, defaultExpr string) (sql string, args []interface{}, err error) { + if len(c) == 0 { + return defaultExpr, []interface{}{}, nil + } + var sqlParts []string + for _, sqlizer := range c { + partSQL, partArgs, err := nestedToSql(sqlizer) + if err != nil { + return "", nil, err + } + if partSQL != "" { + sqlParts = append(sqlParts, partSQL) + args = append(args, partArgs...) + } + } + if len(sqlParts) > 0 { + sql = fmt.Sprintf("(%s)", strings.Join(sqlParts, sep)) + } + return +} + +// And conjunction Sqlizers +type And conj + +func (a And) ToSql() (string, []interface{}, error) { + return conj(a).join(" AND ", sqlTrue) +} + +// Or conjunction Sqlizers +type Or conj + +func (o Or) ToSql() (string, []interface{}, error) { + return conj(o).join(" OR ", sqlFalse) +} + +func getSortedKeys(exp map[string]interface{}) []string { + sortedKeys := make([]string, 0, len(exp)) + for k := range exp { + sortedKeys = append(sortedKeys, k) + } + sort.Strings(sortedKeys) + return sortedKeys +} + +func isListType(val interface{}) bool { + if driver.IsValue(val) { + return false + } + valVal := reflect.ValueOf(val) + return valVal.Kind() == reflect.Array || valVal.Kind() == reflect.Slice +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/go.mod b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..235b74d07f881f428e68d2218ead6b3dba9d335e --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/go.mod @@ -0,0 +1,11 @@ +module github.com/Masterminds/squirrel + +go 1.14 + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 + github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/stretchr/testify v1.2.2 +) diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/go.sum b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..a92f768e60f084b42661848ff2828be637d9bfac --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/go.sum @@ -0,0 +1,10 @@ +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw= +github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o= +github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk= +github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/insert.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/insert.go new file mode 100644 index 0000000000000000000000000000000000000000..97870783aad362fc20fb246ca128fefca341e637 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/insert.go @@ -0,0 +1,298 @@ +package squirrel + +import ( + "bytes" + "database/sql" + "errors" + "fmt" + "io" + "sort" + "strings" + + "github.com/lann/builder" +) + +type insertData struct { + PlaceholderFormat PlaceholderFormat + RunWith BaseRunner + Prefixes []Sqlizer + StatementKeyword string + Options []string + Into string + Columns []string + Values [][]interface{} + Suffixes []Sqlizer + Select *SelectBuilder +} + +func (d *insertData) Exec() (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return ExecWith(d.RunWith, d) +} + +func (d *insertData) Query() (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return QueryWith(d.RunWith, d) +} + +func (d *insertData) QueryRow() RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRower) + if !ok { + return &Row{err: RunnerNotQueryRunner} + } + return QueryRowWith(queryRower, d) +} + +func (d *insertData) ToSql() (sqlStr string, args []interface{}, err error) { + if len(d.Into) == 0 { + err = errors.New("insert statements must specify a table") + return + } + if len(d.Values) == 0 && d.Select == nil { + err = errors.New("insert statements must have at least one set of values or select clause") + return + } + + sql := &bytes.Buffer{} + + if len(d.Prefixes) > 0 { + args, err = appendToSql(d.Prefixes, sql, " ", args) + if err != nil { + return + } + + sql.WriteString(" ") + } + + if d.StatementKeyword == "" { + sql.WriteString("INSERT ") + } else { + sql.WriteString(d.StatementKeyword) + sql.WriteString(" ") + } + + if len(d.Options) > 0 { + sql.WriteString(strings.Join(d.Options, " ")) + sql.WriteString(" ") + } + + sql.WriteString("INTO ") + sql.WriteString(d.Into) + sql.WriteString(" ") + + if len(d.Columns) > 0 { + sql.WriteString("(") + sql.WriteString(strings.Join(d.Columns, ",")) + sql.WriteString(") ") + } + + if d.Select != nil { + args, err = d.appendSelectToSQL(sql, args) + } else { + args, err = d.appendValuesToSQL(sql, args) + } + if err != nil { + return + } + + if len(d.Suffixes) > 0 { + sql.WriteString(" ") + args, err = appendToSql(d.Suffixes, sql, " ", args) + if err != nil { + return + } + } + + sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sql.String()) + return +} + +func (d *insertData) appendValuesToSQL(w io.Writer, args []interface{}) ([]interface{}, error) { + if len(d.Values) == 0 { + return args, errors.New("values for insert statements are not set") + } + + io.WriteString(w, "VALUES ") + + valuesStrings := make([]string, len(d.Values)) + for r, row := range d.Values { + valueStrings := make([]string, len(row)) + for v, val := range row { + if vs, ok := val.(Sqlizer); ok { + vsql, vargs, err := vs.ToSql() + if err != nil { + return nil, err + } + valueStrings[v] = vsql + args = append(args, vargs...) + } else { + valueStrings[v] = "?" + args = append(args, val) + } + } + valuesStrings[r] = fmt.Sprintf("(%s)", strings.Join(valueStrings, ",")) + } + + io.WriteString(w, strings.Join(valuesStrings, ",")) + + return args, nil +} + +func (d *insertData) appendSelectToSQL(w io.Writer, args []interface{}) ([]interface{}, error) { + if d.Select == nil { + return args, errors.New("select clause for insert statements are not set") + } + + selectClause, sArgs, err := d.Select.ToSql() + if err != nil { + return args, err + } + + io.WriteString(w, selectClause) + args = append(args, sArgs...) + + return args, nil +} + +// Builder + +// InsertBuilder builds SQL INSERT statements. +type InsertBuilder builder.Builder + +func init() { + builder.Register(InsertBuilder{}, insertData{}) +} + +// Format methods + +// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the +// query. +func (b InsertBuilder) PlaceholderFormat(f PlaceholderFormat) InsertBuilder { + return builder.Set(b, "PlaceholderFormat", f).(InsertBuilder) +} + +// Runner methods + +// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec. +func (b InsertBuilder) RunWith(runner BaseRunner) InsertBuilder { + return setRunWith(b, runner).(InsertBuilder) +} + +// Exec builds and Execs the query with the Runner set by RunWith. +func (b InsertBuilder) Exec() (sql.Result, error) { + data := builder.GetStruct(b).(insertData) + return data.Exec() +} + +// Query builds and Querys the query with the Runner set by RunWith. +func (b InsertBuilder) Query() (*sql.Rows, error) { + data := builder.GetStruct(b).(insertData) + return data.Query() +} + +// QueryRow builds and QueryRows the query with the Runner set by RunWith. +func (b InsertBuilder) QueryRow() RowScanner { + data := builder.GetStruct(b).(insertData) + return data.QueryRow() +} + +// Scan is a shortcut for QueryRow().Scan. +func (b InsertBuilder) Scan(dest ...interface{}) error { + return b.QueryRow().Scan(dest...) +} + +// SQL methods + +// ToSql builds the query into a SQL string and bound args. +func (b InsertBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(insertData) + return data.ToSql() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b InsertBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// Prefix adds an expression to the beginning of the query +func (b InsertBuilder) Prefix(sql string, args ...interface{}) InsertBuilder { + return b.PrefixExpr(Expr(sql, args...)) +} + +// PrefixExpr adds an expression to the very beginning of the query +func (b InsertBuilder) PrefixExpr(expr Sqlizer) InsertBuilder { + return builder.Append(b, "Prefixes", expr).(InsertBuilder) +} + +// Options adds keyword options before the INTO clause of the query. +func (b InsertBuilder) Options(options ...string) InsertBuilder { + return builder.Extend(b, "Options", options).(InsertBuilder) +} + +// Into sets the INTO clause of the query. +func (b InsertBuilder) Into(into string) InsertBuilder { + return builder.Set(b, "Into", into).(InsertBuilder) +} + +// Columns adds insert columns to the query. +func (b InsertBuilder) Columns(columns ...string) InsertBuilder { + return builder.Extend(b, "Columns", columns).(InsertBuilder) +} + +// Values adds a single row's values to the query. +func (b InsertBuilder) Values(values ...interface{}) InsertBuilder { + return builder.Append(b, "Values", values).(InsertBuilder) +} + +// Suffix adds an expression to the end of the query +func (b InsertBuilder) Suffix(sql string, args ...interface{}) InsertBuilder { + return b.SuffixExpr(Expr(sql, args...)) +} + +// SuffixExpr adds an expression to the end of the query +func (b InsertBuilder) SuffixExpr(expr Sqlizer) InsertBuilder { + return builder.Append(b, "Suffixes", expr).(InsertBuilder) +} + +// SetMap set columns and values for insert builder from a map of column name and value +// note that it will reset all previous columns and values was set if any +func (b InsertBuilder) SetMap(clauses map[string]interface{}) InsertBuilder { + // Keep the columns in a consistent order by sorting the column key string. + cols := make([]string, 0, len(clauses)) + for col := range clauses { + cols = append(cols, col) + } + sort.Strings(cols) + + vals := make([]interface{}, 0, len(clauses)) + for _, col := range cols { + vals = append(vals, clauses[col]) + } + + b = builder.Set(b, "Columns", cols).(InsertBuilder) + b = builder.Set(b, "Values", [][]interface{}{vals}).(InsertBuilder) + + return b +} + +// Select set Select clause for insert query +// If Values and Select are used, then Select has higher priority +func (b InsertBuilder) Select(sb SelectBuilder) InsertBuilder { + return builder.Set(b, "Select", &sb).(InsertBuilder) +} + +func (b InsertBuilder) statementKeyword(keyword string) InsertBuilder { + return builder.Set(b, "StatementKeyword", keyword).(InsertBuilder) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/insert_ctx.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/insert_ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..4541c2fed325335b17253caaf066bcdd043f365b --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/insert_ctx.go @@ -0,0 +1,69 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + + "github.com/lann/builder" +) + +func (d *insertData) ExecContext(ctx context.Context) (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(ExecerContext) + if !ok { + return nil, NoContextSupport + } + return ExecContextWith(ctx, ctxRunner, d) +} + +func (d *insertData) QueryContext(ctx context.Context) (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(QueryerContext) + if !ok { + return nil, NoContextSupport + } + return QueryContextWith(ctx, ctxRunner, d) +} + +func (d *insertData) QueryRowContext(ctx context.Context) RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRowerContext) + if !ok { + if _, ok := d.RunWith.(QueryerContext); !ok { + return &Row{err: RunnerNotQueryRunner} + } + return &Row{err: NoContextSupport} + } + return QueryRowContextWith(ctx, queryRower, d) +} + +// ExecContext builds and ExecContexts the query with the Runner set by RunWith. +func (b InsertBuilder) ExecContext(ctx context.Context) (sql.Result, error) { + data := builder.GetStruct(b).(insertData) + return data.ExecContext(ctx) +} + +// QueryContext builds and QueryContexts the query with the Runner set by RunWith. +func (b InsertBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) { + data := builder.GetStruct(b).(insertData) + return data.QueryContext(ctx) +} + +// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith. +func (b InsertBuilder) QueryRowContext(ctx context.Context) RowScanner { + data := builder.GetStruct(b).(insertData) + return data.QueryRowContext(ctx) +} + +// ScanContext is a shortcut for QueryRowContext().Scan. +func (b InsertBuilder) ScanContext(ctx context.Context, dest ...interface{}) error { + return b.QueryRowContext(ctx).Scan(dest...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/integration/doc.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/integration/doc.go new file mode 100644 index 0000000000000000000000000000000000000000..3796ab9ede31bfc6ce6f0872e70aad4d46a6beb3 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/integration/doc.go @@ -0,0 +1,2 @@ +// This is a tests-only package. +package integration diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/integration/go.mod b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/integration/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..8029ff8c8b17e541eaf93d5b0d3bab3cc33067fc --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/integration/go.mod @@ -0,0 +1,14 @@ +module github.com/Masterminds/squirrel/integration + +go 1.12 + +require ( + github.com/Masterminds/squirrel v1.1.0 + github.com/go-sql-driver/mysql v1.4.1 + github.com/lib/pq v1.2.0 + github.com/mattn/go-sqlite3 v1.13.0 + github.com/stretchr/testify v1.4.0 + google.golang.org/appengine v1.6.5 // indirect +) + +replace github.com/Masterminds/squirrel => ../ diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/integration/go.sum b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/integration/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..0bfcfa9f096176f194a2b5275638d2688cb952a9 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/integration/go.sum @@ -0,0 +1,34 @@ +github.com/Masterminds/squirrel v1.1.0 h1:baP1qLdoQCeTw3ifCdOq2dkYc6vGcmRdaociKLbEJXs= +github.com/Masterminds/squirrel v1.1.0/go.mod h1:yaPeOnPG5ZRwL9oKdTsO/prlkPbXWZlRVMQ/gGlzIuA= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-sql-driver/mysql v1.4.1 h1:g24URVg0OFbNUTx9qqY1IRZ9D9z3iPyi5zKhQZpNwpA= +github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw= +github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o= +github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk= +github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw= +github.com/lib/pq v1.2.0 h1:LXpIM/LZ5xGFhOpXAQUIMM1HdyqzVYM13zNdjCEEcA0= +github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/mattn/go-sqlite3 v1.13.0 h1:LnJI81JidiW9r7pS/hXe6cFeO5EXNq7KbfvoJLRI69c= +github.com/mattn/go-sqlite3 v1.13.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +google.golang.org/appengine v1.6.5 h1:tycE03LOZYQNhDpS27tcQdAzLCVMaj7QT2SXxebnpCM= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/part.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/part.go new file mode 100644 index 0000000000000000000000000000000000000000..c58f68f1a49717818bc349bede5cbf239bb06769 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/part.go @@ -0,0 +1,63 @@ +package squirrel + +import ( + "fmt" + "io" +) + +type part struct { + pred interface{} + args []interface{} +} + +func newPart(pred interface{}, args ...interface{}) Sqlizer { + return &part{pred, args} +} + +func (p part) ToSql() (sql string, args []interface{}, err error) { + switch pred := p.pred.(type) { + case nil: + // no-op + case Sqlizer: + sql, args, err = nestedToSql(pred) + case string: + sql = pred + args = p.args + default: + err = fmt.Errorf("expected string or Sqlizer, not %T", pred) + } + return +} + +func nestedToSql(s Sqlizer) (string, []interface{}, error) { + if raw, ok := s.(rawSqlizer); ok { + return raw.toSqlRaw() + } else { + return s.ToSql() + } +} + +func appendToSql(parts []Sqlizer, w io.Writer, sep string, args []interface{}) ([]interface{}, error) { + for i, p := range parts { + partSql, partArgs, err := nestedToSql(p) + if err != nil { + return nil, err + } else if len(partSql) == 0 { + continue + } + + if i > 0 { + _, err := io.WriteString(w, sep) + if err != nil { + return nil, err + } + } + + _, err = io.WriteString(w, partSql) + if err != nil { + return nil, err + } + args = append(args, partArgs...) + } + return args, nil +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/placeholder.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/placeholder.go new file mode 100644 index 0000000000000000000000000000000000000000..8e97a6c62d4b430def230bd65a84b6e294b11284 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/placeholder.go @@ -0,0 +1,114 @@ +package squirrel + +import ( + "bytes" + "fmt" + "strings" +) + +// PlaceholderFormat is the interface that wraps the ReplacePlaceholders method. +// +// ReplacePlaceholders takes a SQL statement and replaces each question mark +// placeholder with a (possibly different) SQL placeholder. +type PlaceholderFormat interface { + ReplacePlaceholders(sql string) (string, error) +} + +type placeholderDebugger interface { + debugPlaceholder() string +} + +var ( + // Question is a PlaceholderFormat instance that leaves placeholders as + // question marks. + Question = questionFormat{} + + // Dollar is a PlaceholderFormat instance that replaces placeholders with + // dollar-prefixed positional placeholders (e.g. $1, $2, $3). + Dollar = dollarFormat{} + + // Colon is a PlaceholderFormat instance that replaces placeholders with + // colon-prefixed positional placeholders (e.g. :1, :2, :3). + Colon = colonFormat{} + + // AtP is a PlaceholderFormat instance that replaces placeholders with + // "@p"-prefixed positional placeholders (e.g. @p1, @p2, @p3). + AtP = atpFormat{} +) + +type questionFormat struct{} + +func (questionFormat) ReplacePlaceholders(sql string) (string, error) { + return sql, nil +} + +func (questionFormat) debugPlaceholder() string { + return "?" +} + +type dollarFormat struct{} + +func (dollarFormat) ReplacePlaceholders(sql string) (string, error) { + return replacePositionalPlaceholders(sql, "$") +} + +func (dollarFormat) debugPlaceholder() string { + return "$" +} + +type colonFormat struct{} + +func (colonFormat) ReplacePlaceholders(sql string) (string, error) { + return replacePositionalPlaceholders(sql, ":") +} + +func (colonFormat) debugPlaceholder() string { + return ":" +} + +type atpFormat struct{} + +func (atpFormat) ReplacePlaceholders(sql string) (string, error) { + return replacePositionalPlaceholders(sql, "@p") +} + +func (atpFormat) debugPlaceholder() string { + return "@p" +} + +// Placeholders returns a string with count ? placeholders joined with commas. +func Placeholders(count int) string { + if count < 1 { + return "" + } + + return strings.Repeat(",?", count)[1:] +} + +func replacePositionalPlaceholders(sql, prefix string) (string, error) { + buf := &bytes.Buffer{} + i := 0 + for { + p := strings.Index(sql, "?") + if p == -1 { + break + } + + if len(sql[p:]) > 1 && sql[p:p+2] == "??" { // escape ?? => ? + buf.WriteString(sql[:p]) + buf.WriteString("?") + if len(sql[p:]) == 1 { + break + } + sql = sql[p+2:] + } else { + i++ + buf.WriteString(sql[:p]) + fmt.Fprintf(buf, "%s%d", prefix, i) + sql = sql[p+1:] + } + } + + buf.WriteString(sql) + return buf.String(), nil +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/row.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/row.go new file mode 100644 index 0000000000000000000000000000000000000000..74ffda92bde903c1e54282dc59ad6ef5d52e5577 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/row.go @@ -0,0 +1,22 @@ +package squirrel + +// RowScanner is the interface that wraps the Scan method. +// +// Scan behaves like database/sql.Row.Scan. +type RowScanner interface { + Scan(...interface{}) error +} + +// Row wraps database/sql.Row to let squirrel return new errors on Scan. +type Row struct { + RowScanner + err error +} + +// Scan returns Row.err or calls RowScanner.Scan. +func (r *Row) Scan(dest ...interface{}) error { + if r.err != nil { + return r.err + } + return r.RowScanner.Scan(dest...) +} diff --git a/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/select.go b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/select.go new file mode 100644 index 0000000000000000000000000000000000000000..d55ce4c74079ac0c4dfe3316d6134cb8c2e61262 --- /dev/null +++ b/tasks/Masterminds__squirrel.1ded5784.func_pm_flip_operators__csy4cg8m/environment/source/select.go @@ -0,0 +1,403 @@ +package squirrel + +import ( + "bytes" + "database/sql" + "fmt" + "strings" + + "github.com/lann/builder" +) + +type selectData struct { + PlaceholderFormat PlaceholderFormat + RunWith BaseRunner + Prefixes []Sqlizer + Options []string + Columns []Sqlizer + From Sqlizer + Joins []Sqlizer + WhereParts []Sqlizer + GroupBys []string + HavingParts []Sqlizer + OrderByParts []Sqlizer + Limit string + Offset string + Suffixes []Sqlizer +} + +func (d *selectData) Exec() (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return ExecWith(d.RunWith, d) +} + +func (d *selectData) Query() (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return QueryWith(d.RunWith, d) +} + +func (d *selectData) QueryRow() RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRower) + if !ok { + return &Row{err: RunnerNotQueryRunner} + } + return QueryRowWith(queryRower, d) +} + +func (d *selectData) ToSql() (sqlStr string, args []interface{}, err error) { + sqlStr, args, err = d.toSqlRaw() + if err != nil { + return + } + + sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sqlStr) + return +} + +func (d *selectData) toSqlRaw() (sqlStr string, args []interface{}, err error) { + if len(d.Columns) == 0 { + err = fmt.Errorf("select statements must have at least one result column") + return + } + + sql := &bytes.Buffer{} + + if len(d.Prefixes) > 0 { + args, err = appendToSql(d.Prefixes, sql, " ", args) + if err != nil { + return + } + + sql.WriteString(" ") + } + + sql.WriteString("SELECT ") + + if len(d.Options) > 0 { + sql.WriteString(strings.Join(d.Options, " ")) + sql.WriteString(" ") + } + + if len(d.Columns) > 0 { + args, err = appendToSql(d.Columns, sql, ", ", args) + if err != nil { + return + } + } + + if d.From != nil { + sql.WriteString(" FROM ") + args, err = appendToSql([]Sqlizer{d.From}, sql, "", args) + if err != nil { + return + } + } + + if len(d.Joins) > 0 { + sql.WriteString(" ") + args, err = appendToSql(d.Joins, sql, " ", args) + if err != nil { + return + } + } + + if len(d.WhereParts) > 0 { + sql.WriteString(" WHERE ") + args, err = appendToSql(d.WhereParts, sql, " AND ", args) + if err != nil { + return + } + } + + if len(d.GroupBys) > 0 { + sql.WriteString(" GROUP BY ") + sql.WriteString(strings.Join(d.GroupBys, ", ")) + } + + if len(d.HavingParts) > 0 { + sql.WriteString(" HAVING ") + args, err = appendToSql(d.HavingParts, sql, " AND ", args) + if err != nil { + return + } + } + + if len(d.OrderByParts) > 0 { + sql.WriteString(" ORDER BY ") + args, err = appendToSql(d.OrderByParts, sql, ", ", args) + if err != nil { + return + } + } + + if len(d.Limit) > 0 { + sql.WriteString(" LIMIT ") + sql.WriteString(d.Limit) + } + + if len(d.Offset) > 0 { + sql.WriteString(" OFFSET ") + sql.WriteString(d.Offset) + } + + if len(d.Suffixes) > 0 { + sql.WriteString(" ") + + args, err = appendToSql(d.Suffixes, sql, " ", args) + if err != nil { + return + } + } + + sqlStr = sql.String() + return +} + +// Builder + +// SelectBuilder builds SQL SELECT statements. +type SelectBuilder builder.Builder + +func init() { + builder.Register(SelectBuilder{}, selectData{}) +} + +// Format methods + +// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the +// query. +func (b SelectBuilder) PlaceholderFormat(f PlaceholderFormat) SelectBuilder { + return builder.Set(b, "PlaceholderFormat", f).(SelectBuilder) +} + +// Runner methods + +// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec. +// For most cases runner will be a database connection. +// +// Internally we use this to mock out the database connection for testing. +func (b SelectBuilder) RunWith(runner BaseRunner) SelectBuilder { + return setRunWith(b, runner).(SelectBuilder) +} + +// Exec builds and Execs the query with the Runner set by RunWith. +func (b SelectBuilder) Exec() (sql.Result, error) { + data := builder.GetStruct(b).(selectData) + return data.Exec() +} + +// Query builds and Querys the query with the Runner set by RunWith. +func (b SelectBuilder) Query() (*sql.Rows, error) { + data := builder.GetStruct(b).(selectData) + return data.Query() +} + +// QueryRow builds and QueryRows the query with the Runner set by RunWith. +func (b SelectBuilder) QueryRow() RowScanner { + data := builder.GetStruct(b).(selectData) + return data.QueryRow() +} + +// Scan is a shortcut for QueryRow().Scan. +func (b SelectBuilder) Scan(dest ...interface{}) error { + return b.QueryRow().Scan(dest...) +} + +// SQL methods + +// ToSql builds the query into a SQL string and bound args. +func (b SelectBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(selectData) + return data.ToSql() +} + +func (b SelectBuilder) toSqlRaw() (string, []interface{}, error) { + data := builder.GetStruct(b).(selectData) + return data.toSqlRaw() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b SelectBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// Prefix adds an expression to the beginning of the query +func (b SelectBuilder) Prefix(sql string, args ...interface{}) SelectBuilder { + return b.PrefixExpr(Expr(sql, args...)) +} + +// PrefixExpr adds an expression to the very beginning of the query +func (b SelectBuilder) PrefixExpr(expr Sqlizer) SelectBuilder { + return builder.Append(b, "Prefixes", expr).(SelectBuilder) +} + +// Distinct adds a DISTINCT clause to the query. +func (b SelectBuilder) Distinct() SelectBuilder { + return b.Options("DISTINCT") +} + +// Options adds select option to the query +func (b SelectBuilder) Options(options ...string) SelectBuilder { + return builder.Extend(b, "Options", options).(SelectBuilder) +} + +// Columns adds result columns to the query. +func (b SelectBuilder) Columns(columns ...string) SelectBuilder { + parts := make([]interface{}, 0, len(columns)) + for _, str := range columns { + parts = append(parts, newPart(str)) + } + return builder.Extend(b, "Columns", parts).(SelectBuilder) +} + +// RemoveColumns remove all columns from query. +// Must add a new column with Column or Columns methods, otherwise +// return a error. +func (b SelectBuilder) RemoveColumns() SelectBuilder { + return builder.Delete(b, "Columns").(SelectBuilder) +} + +// Column adds a result column to the query. +// Unlike Columns, Column accepts args which will be bound to placeholders in +// the columns string, for example: +// Column("IF(col IN ("+squirrel.Placeholders(3)+"), 1, 0) as col", 1, 2, 3) +func (b SelectBuilder) Column(column interface{}, args ...interface{}) SelectBuilder { + return builder.Append(b, "Columns", newPart(column, args...)).(SelectBuilder) +} + +// From sets the FROM clause of the query. +func (b SelectBuilder) From(from string) SelectBuilder { + return builder.Set(b, "From", newPart(from)).(SelectBuilder) +} + +// FromSelect sets a subquery into the FROM clause of the query. +func (b SelectBuilder) FromSelect(from SelectBuilder, alias string) SelectBuilder { + // Prevent misnumbered parameters in nested selects (#183). + from = from.PlaceholderFormat(Question) + return builder.Set(b, "From", Alias(from, alias)).(SelectBuilder) +} + +// JoinClause adds a join clause to the query. +func (b SelectBuilder) JoinClause(pred interface{}, args ...interface{}) SelectBuilder { + return builder.Append(b, "Joins", newPart(pred, args...)).(SelectBuilder) +} + +// Join adds a JOIN clause to the query. +func (b SelectBuilder) Join(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("JOIN "+join, rest...) +} + +// LeftJoin adds a LEFT JOIN clause to the query. +func (b SelectBuilder) LeftJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("LEFT JOIN "+join, rest...) +} + +// RightJoin adds a RIGHT JOIN clause to the query. +func (b SelectBuilder) RightJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("RIGHT JOIN "+join, rest...) +} + +// InnerJoin adds a INNER JOIN clause to the query. +func (b SelectBuilder) InnerJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("INNER JOIN "+join, rest...) +} + +// CrossJoin adds a CROSS JOIN clause to the query. +func (b SelectBuilder) CrossJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("CROSS JOIN "+join, rest...) +} + +// Where adds an expression to the WHERE clause of the query. +// +// Expressions are ANDed together in the generated SQL. +// +// Where accepts several types for its pred argument: +// +// nil OR "" - ignored. +// +// string - SQL expression. +// If the expression has SQL placeholders then a set of arguments must be passed +// as well, one for each placeholder. +// +// map[string]interface{} OR Eq - map of SQL expressions to values. Each key is +// transformed into an expression like " = ?", with the corresponding value +// bound to the placeholder. If the value is nil, the expression will be " +// IS NULL". If the value is an array or slice, the expression will be " IN +// (?,?,...)", with one placeholder for each item in the value. These expressions +// are ANDed together. +// +// Where will panic if pred isn't any of the above types. +func (b SelectBuilder) Where(pred interface{}, args ...interface{}) SelectBuilder { + if pred == nil || pred == "" { + return b + } + return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(SelectBuilder) +} + +// GroupBy adds GROUP BY expressions to the query. +func (b SelectBuilder) GroupBy(groupBys ...string) SelectBuilder { + return builder.Extend(b, "GroupBys", groupBys).(SelectBuilder) +} + +// Having adds an expression to the HAVING clause of the query. +// +// See Where. +func (b SelectBuilder) Having(pred interface{}, rest ...interface{}) SelectBuilder { + return builder.Append(b, "HavingParts", newWherePart(pred, rest...)).(SelectBuilder) +} + +// OrderByClause adds ORDER BY clause to the query. +func (b SelectBuilder) OrderByClause(pred interface{}, args ...interface{}) SelectBuilder { + return builder.Append(b, "OrderByParts", newPart(pred, args...)).(SelectBuilder) +} + +// OrderBy adds ORDER BY expressions to the query. +func (b SelectBuilder) OrderBy(orderBys ...string) SelectBuilder { + for _, orderBy := range orderBys { + b = b.OrderByClause(orderBy) + } + + return b +} + +// Limit sets a LIMIT clause on the query. +func (b SelectBuilder) Limit(limit uint64) SelectBuilder { + return builder.Set(b, "Limit", fmt.Sprintf("%d", limit)).(SelectBuilder) +} + +// Limit ALL allows to access all records with limit +func (b SelectBuilder) RemoveLimit() SelectBuilder { + return builder.Delete(b, "Limit").(SelectBuilder) +} + +// Offset sets a OFFSET clause on the query. +func (b SelectBuilder) Offset(offset uint64) SelectBuilder { + return builder.Set(b, "Offset", fmt.Sprintf("%d", offset)).(SelectBuilder) +} + +// RemoveOffset removes OFFSET clause. +func (b SelectBuilder) RemoveOffset() SelectBuilder { + return builder.Delete(b, "Offset").(SelectBuilder) +} + +// Suffix adds an expression to the end of the query +func (b SelectBuilder) Suffix(sql string, args ...interface{}) SelectBuilder { + return b.SuffixExpr(Expr(sql, args...)) +} + +// SuffixExpr adds an expression to the end of the query +func (b SelectBuilder) SuffixExpr(expr Sqlizer) SelectBuilder { + return builder.Append(b, "Suffixes", expr).(SelectBuilder) +}