├── .github ├── FUNDING.yml ├── dependabot.yml └── workflows │ ├── codeql.yml │ ├── lint.yml │ └── tests.yml ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── case.go ├── case_test.go ├── delete.go ├── delete_test.go ├── expr.go ├── expr_test.go ├── go.mod ├── insert.go ├── insert_test.go ├── integration ├── doc.go ├── go.mod ├── go.sum ├── integration_test.go └── migrations │ └── 001_initial_schema.sql ├── pgq.go ├── pgq_test.go ├── placeholder.go ├── placeholder_test.go ├── scripts ├── ci-lint-fmt.sh ├── ci-lint-install.sh ├── ci-lint.sh ├── coverage.sh └── lib.sh ├── select.go ├── select_test.go ├── statement.go ├── statement_test.go ├── update.go ├── update_test.go ├── where.go └── where_test.go /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: henvic 2 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # Set update schedule for GitHub Actions 2 | 3 | version: 2 4 | updates: 5 | 6 | - package-ecosystem: "github-actions" 7 | directory: "/" 8 | schedule: 9 | # Check for updates to GitHub Actions every week 10 | interval: "weekly" 11 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | name: Code Scanning 2 | # Source: https://github.com/cli/cli/blob/trunk/.github/workflows/codeql.yml 3 | 4 | on: 5 | push: 6 | branches: [ "main" ] 7 | pull_request: 8 | types: [opened, synchronize, reopened, ready_for_review] 9 | # The branches below must be a subset of the branches above 10 | branches: [ "main" ] 11 | schedule: 12 | - cron: '32 13 * * 4' 13 | 14 | jobs: 15 | CodeQL-Build: 16 | runs-on: ubuntu-latest 17 | permissions: 18 | actions: read 19 | contents: read 20 | security-events: write 21 | 22 | steps: 23 | - name: Check out code 24 | uses: actions/checkout@v4 25 | 26 | - name: Initialize CodeQL 27 | uses: github/codeql-action/init@v3 28 | with: 29 | languages: go 30 | 31 | - name: Perform CodeQL Analysis 32 | uses: github/codeql-action/analyze@v3 33 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: Lint 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | pull_request: 7 | types: [opened, synchronize, reopened, ready_for_review] 8 | # The branches below must be a subset of the branches above 9 | branches: [ "main" ] 10 | 11 | jobs: 12 | 13 | lint: 14 | name: Build 15 | runs-on: ubuntu-latest 16 | steps: 17 | 18 | - name: Set up Go 1.x 19 | uses: actions/setup-go@v5 20 | with: 21 | go-version: "1.24.x" 22 | 23 | - name: Check out code 24 | uses: actions/checkout@v4 25 | 26 | - name: Verify dependencies 27 | run: | 28 | go mod verify 29 | go mod download 30 | 31 | - name: Installing static code analysis tools 32 | run: ./scripts/ci-lint-install.sh 33 | 34 | - name: Run checks 35 | run: ./scripts/ci-lint.sh 36 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | on: 3 | push: 4 | branches: [ "main" ] 5 | pull_request: 6 | types: [opened, synchronize, reopened, ready_for_review] 7 | # The branches below must be a subset of the branches above 8 | branches: [ "main" ] 9 | permissions: 10 | contents: read 11 | pull-requests: read 12 | jobs: 13 | # Reference: https://docs.github.com/en/actions/guides/creating-postgresql-service-containers 14 | postgres-test: 15 | strategy: 16 | matrix: 17 | go: [1.24.x, 1.23.x] # when updating versions, update it below too. 18 | runs-on: ubuntu-latest 19 | services: 20 | postgres: 21 | image: postgres 22 | env: 23 | POSTGRES_USER: runner 24 | POSTGRES_PASSWORD: postgres 25 | POSTGRES_DB: test_pgq 26 | options: >- 27 | --name postgres 28 | --health-cmd pg_isready 29 | --health-interval 10s 30 | --health-timeout 5s 31 | --health-retries 5 32 | ports: 33 | # Maps tcp port 5432 on service container to the host 34 | - 5432:5432 35 | env: 36 | INTEGRATION_TESTDB: true 37 | PGHOST: localhost 38 | PGUSER: runner 39 | PGPASSWORD: postgres 40 | PGDATABASE: test_pgq 41 | steps: 42 | - uses: actions/checkout@v4 43 | - uses: actions/setup-go@v5 44 | with: 45 | go-version: '1.24.x' 46 | - name: Run unit tests 47 | run: | 48 | go test -v -race -count 1 -covermode atomic -coverprofile=profile.cov ./... 49 | sed -i '/^github\.com\/henvic\/httpretty\/example\//d' profile.cov 50 | - name: Run Postgres tests 51 | working-directory: integration 52 | run: go test -v 53 | - name: Code coverage 54 | if: ${{ github.event_name != 'pull_request' && matrix.go == '1.24.x' }} 55 | uses: shogo82148/actions-goveralls@v1 56 | with: 57 | path-to-profile: profile.cov 58 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to pgq 2 | ## Bug reports 3 | When reporting bugs, please add information about your operating system and Go version used to compile the code. 4 | 5 | If you can provide a code snippet reproducing the issue, please do so. 6 | 7 | ## Code 8 | Please write code that satisfies [Go Code Review Comments](https://github.com/golang/go/wiki/CodeReviewComments) before submitting a pull-request. 9 | Your code should be properly covered by extensive unit tests. 10 | 11 | ## Commit messages 12 | Please follow the Go [commit messages](https://github.com/golang/go/wiki/CommitMessage) convention when contributing code. 13 | 14 | ## Running integration tests 15 | The integration tests are located in a separate module inside the integration directory to avoid polluting the regular go.mod with dependencies only required to run the tests. 16 | 17 | To run all tests: 18 | 19 | ```sh 20 | # After running small tests 21 | $ go test -v -race 22 | 23 | # cd into the integration directory, and set the INTEGRATION_TESTDB environment variable as "true" 24 | $ cd integration 25 | $ INTEGRATION_TESTDB=true go test -v 26 | ``` 27 | 28 | To run them the tests you need to have PostgreSQL configured on your machine through the following environment variable: 29 | 30 | | Environment Variable | Description | 31 | | - | - | 32 | | PostgreSQL environment variables | Please check https://www.postgresql.org/docs/current/libpq-envars.html | 33 | | INTEGRATION_TESTDB | When running go test, database tests will only run if `INTEGRATION_TESTDB=true` | 34 | 35 | Tests are safely run inside temporary databases created on-the-fly. 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Squirrel: The Masterminds 4 | Copyright (c) 2014-2015, Lann Martin. Copyright (C) 2015-2016, Google. Copyright (C) 2015, Matt Farina and Matt Butcher. 5 | 6 | 7 | Permission is hereby granted, free of charge, to any person obtaining a copy 8 | of this software and associated documentation files (the "Software"), to deal 9 | in the Software without restriction, including without limitation the rights 10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 | copies of the Software, and to permit persons to whom the Software is 12 | furnished to do so, subject to the following conditions: 13 | 14 | The above copyright notice and this permission notice shall be included in all 15 | copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 23 | SOFTWARE. 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pgq 2 | [![GoDoc](https://godoc.org/github.com/henvic/pgq?status.svg)](https://godoc.org/github.com/henvic/pgq) [![Build Status](https://github.com/henvic/pgq/workflows/Tests/badge.svg)](https://github.com/henvic/pgq/actions?query=workflow%3ATests) [![Coverage Status](https://coveralls.io/repos/henvic/pgq/badge.svg)](https://coveralls.io/r/henvic/pgq) 3 | 4 | pgq is a query builder for PostgreSQL written in Go. 5 | 6 | It is a fork of [Squirrel](https://github.com/Masterminds/squirrel) more suitable for working with the PostgreSQL database when you are able to use the native PostgreSQL protocol directly, rather than the slower textual protocol used by database/sql. 7 | 8 | You can use it with the [pgx](https://github.com/jackc/pgx) driver. 9 | 10 | ## Usage example 11 | 12 | Something like this: 13 | 14 | ```go 15 | sql, args, err := pgq.Update("employees"). 16 | Set("salary_bonus", pgq.Expr("salary_bonus + 1000")). 17 | From("accounts"). 18 | Where("accounts.team = ?", "engineering"). 19 | Returning("id", "name", "salary").SQL() 20 | 21 | if err != nil { 22 | panic(err) // bug: this should never happen. 23 | } 24 | 25 | type employee struct { 26 | ID string 27 | Name string 28 | Salary int 29 | } 30 | var data []employee 31 | rows, err := pool.Query(context.Background(), sql, args...) 32 | if err == nil { 33 | defer rows.Close() 34 | data, err = pgx.CollectRows(rows, pgx.RowTo[employee]) 35 | } 36 | ``` 37 | 38 | ## Main benefits 39 | 40 | * API is crafted with only PostgreSQL compatibility so it has a somewhat lean API. 41 | * It uses ANY and ALL [operators for slices](https://www.postgresql.org/docs/current/functions-comparisons.html) by default, which means it supports slices out of the box and you get to reuse your prepared statements. 42 | * It's throughly tested (including integration tests to check for invalid queries being generated). 43 | * If you already use pgx with Squirrel and the native PostgreSQL protocol, switching is very straightforward with just a few breaking changes (example: Alias is a type rather than a function). 44 | 45 | ## Main drawback 46 | 47 | * It's still a query builder. You can go a long way writing pure SQL queries. Consider doing so. 48 | 49 | ## FAQ 50 | 51 | **Why forking a query builder then?** Whatever it takes to make people ditch using an [ORM](https://alanilling.com/exiting-the-vietnam-of-programming-our-journey-in-dropping-the-orm-in-golang-3ce7dff24a0f), I guess. 52 | 53 | ## See also 54 | * [pgtools](https://github.com/henvic/pgtools/) 55 | * [pgxtutorial](https://github.com/henvic/pgxtutorial) 56 | -------------------------------------------------------------------------------- /case.go: -------------------------------------------------------------------------------- 1 | package pgq 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | ) 7 | 8 | // sqlizerBuffer is a helper that allows to write many SQLizers one by one 9 | // without constant checks for errors that may come from SQLizer 10 | type sqlizerBuffer struct { 11 | bytes.Buffer 12 | args []any 13 | err error 14 | } 15 | 16 | // WriteSQL converts SQLizer to SQL strings and writes it to buffer 17 | func (b *sqlizerBuffer) WriteSQL(item SQLizer) { 18 | if b.err != nil { 19 | return 20 | } 21 | 22 | var str string 23 | var args []any 24 | str, args, b.err = nestedSQL(item) 25 | 26 | if b.err != nil { 27 | return 28 | } 29 | 30 | b.WriteString(str) 31 | b.WriteByte(' ') 32 | b.args = append(b.args, args...) 33 | } 34 | 35 | func (b *sqlizerBuffer) SQL() (string, []any, error) { 36 | return b.String(), b.args, b.err 37 | } 38 | 39 | // whenPart is a helper structure to describe SQLs "WHEN ... THEN ..." expression 40 | type whenPart struct { 41 | when SQLizer 42 | then SQLizer 43 | } 44 | 45 | func newWhenPart(when any, then any) whenPart { 46 | return whenPart{newPart(when), newPart(then)} 47 | } 48 | 49 | // CaseBuilder builds SQL CASE construct which could be used as parts of queries. 50 | type CaseBuilder struct { 51 | whatParts SQLizer 52 | whenParts []whenPart 53 | elseParts SQLizer 54 | } 55 | 56 | // SQL builds the query into a SQL string and bound args. 57 | func (b CaseBuilder) SQL() (sqlStr string, args []any, err error) { 58 | if len(b.whenParts) == 0 { 59 | err = errors.New("case expression must contain at lease one WHEN clause") 60 | 61 | return 62 | } 63 | 64 | sql := sqlizerBuffer{} 65 | 66 | sql.WriteString("CASE ") 67 | if b.whatParts != nil { 68 | sql.WriteSQL(b.whatParts) 69 | } 70 | 71 | for _, p := range b.whenParts { 72 | sql.WriteString("WHEN ") 73 | sql.WriteSQL(p.when) 74 | sql.WriteString("THEN ") 75 | sql.WriteSQL(p.then) 76 | } 77 | 78 | if b.elseParts != nil { 79 | sql.WriteString("ELSE ") 80 | sql.WriteSQL(b.elseParts) 81 | } 82 | 83 | sql.WriteString("END") 84 | 85 | return sql.SQL() 86 | } 87 | 88 | // MustSQL builds the query into a SQL string and bound args. 89 | // It panics if there are any errors. 90 | func (b CaseBuilder) MustSQL() (string, []any) { 91 | sql, args, err := b.SQL() 92 | if err != nil { 93 | panic(err) 94 | } 95 | return sql, args 96 | } 97 | 98 | // what sets optional value for CASE construct "CASE [value] ..." 99 | func (b CaseBuilder) what(expr any) CaseBuilder { 100 | b.whatParts = newPart(expr) 101 | return b 102 | } 103 | 104 | // When adds "WHEN ... THEN ..." part to CASE construct 105 | func (b CaseBuilder) When(when any, then any) CaseBuilder { 106 | // TODO: performance hint: replace slice of WhenPart with just slice of parts 107 | // where even indices of the slice belong to "when"s and odd indices belong to "then"s 108 | b.whenParts = append(b.whenParts, newWhenPart(when, then)) 109 | return b 110 | } 111 | 112 | // What sets optional "ELSE ..." part for CASE construct 113 | func (b CaseBuilder) Else(expr any) CaseBuilder { 114 | b.elseParts = newPart(expr) 115 | return b 116 | } 117 | -------------------------------------------------------------------------------- /case_test.go: -------------------------------------------------------------------------------- 1 | package pgq 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestCaseWithVal(t *testing.T) { 9 | t.Parallel() 10 | caseStmt := Case("number"). 11 | When("1", "one"). 12 | When("2", "two"). 13 | Else(Expr("?", "big number")) 14 | 15 | qb := Select(). 16 | Column(caseStmt). 17 | From("atable") 18 | sql, args, err := qb.SQL() 19 | 20 | if err != nil { 21 | t.Errorf("unexpected error: %v", err) 22 | } 23 | 24 | want := "SELECT CASE number " + 25 | "WHEN 1 THEN one " + 26 | "WHEN 2 THEN two " + 27 | "ELSE $1 " + 28 | "END " + 29 | "FROM atable" 30 | if sql != want { 31 | t.Errorf("wanted %v, got %v instead", want, sql) 32 | } 33 | 34 | expectedArgs := []any{"big number"} 35 | if !reflect.DeepEqual(args, expectedArgs) { 36 | t.Errorf("wanted %v, got %v instead", expectedArgs, sql) 37 | } 38 | } 39 | 40 | func TestCaseWithComplexVal(t *testing.T) { 41 | t.Parallel() 42 | caseStmt := Case("? > ?", 10, 5). 43 | When("true", "'T'") 44 | 45 | qb := Select(). 46 | Column(Alias{ 47 | Expr: caseStmt, 48 | As: "complexCase", 49 | }). 50 | From("atable") 51 | sql, args, err := qb.SQL() 52 | 53 | if err != nil { 54 | t.Errorf("unexpected error: %v", err) 55 | } 56 | 57 | want := "SELECT (CASE $1 > $2 " + 58 | "WHEN true THEN 'T' " + 59 | "END) AS complexCase " + 60 | "FROM atable" 61 | if sql != want { 62 | t.Errorf("wanted %v, got %v instead", want, sql) 63 | } 64 | 65 | expectedArgs := []any{10, 5} 66 | if !reflect.DeepEqual(args, expectedArgs) { 67 | t.Errorf("wanted %v, got %v instead", expectedArgs, args) 68 | } 69 | } 70 | 71 | func TestCaseWithNoVal(t *testing.T) { 72 | t.Parallel() 73 | caseStmt := Case(). 74 | When(Eq{"x": 0}, "x is zero"). 75 | When(Expr("x > ?", 1), Expr("CONCAT('x is greater than ', ?)", 2)) 76 | 77 | qb := Select().Column(caseStmt).From("atable") 78 | sql, args, err := qb.SQL() 79 | 80 | if err != nil { 81 | t.Errorf("unexpected error: %v", err) 82 | } 83 | 84 | want := "SELECT CASE " + 85 | "WHEN x = $1 THEN x is zero " + 86 | "WHEN x > $2 THEN CONCAT('x is greater than ', $3) " + 87 | "END " + 88 | "FROM atable" 89 | 90 | if sql != want { 91 | t.Errorf("wanted %v, got %v instead", want, sql) 92 | } 93 | 94 | expectedArgs := []any{0, 1, 2} 95 | if !reflect.DeepEqual(args, expectedArgs) { 96 | t.Errorf("wanted %v, got %v instead", expectedArgs, args) 97 | } 98 | } 99 | 100 | func TestCaseWithExpr(t *testing.T) { 101 | t.Parallel() 102 | caseStmt := Case(Expr("x = ?", true)). 103 | When("true", Expr("?", "it's true!")). 104 | Else("42") 105 | 106 | qb := Select().Column(caseStmt).From("atable") 107 | sql, args, err := qb.SQL() 108 | 109 | if err != nil { 110 | t.Errorf("unexpected error: %v", err) 111 | } 112 | 113 | want := "SELECT CASE x = $1 " + 114 | "WHEN true THEN $2 " + 115 | "ELSE 42 " + 116 | "END " + 117 | "FROM atable" 118 | 119 | if sql != want { 120 | t.Errorf("wanted %v, got %v instead", want, sql) 121 | } 122 | 123 | expectedArgs := []any{true, "it's true!"} 124 | if !reflect.DeepEqual(args, expectedArgs) { 125 | t.Errorf("wanted %v, got %v instead", expectedArgs, args) 126 | } 127 | } 128 | 129 | func TestMultipleCase(t *testing.T) { 130 | t.Parallel() 131 | caseStmtNoval := Case(Expr("x = ?", true)). 132 | When("true", Expr("?", "it's true!")). 133 | Else("42") 134 | caseStmtExpr := Case(). 135 | When(Eq{"x": 0}, "'x is zero'"). 136 | When(Expr("x > ?", 1), Expr("CONCAT('x is greater than ', ?)", 2)) 137 | 138 | qb := Select(). 139 | Column(Alias{ 140 | Expr: caseStmtNoval, 141 | As: "case_noval", 142 | }). 143 | Column(Alias{ 144 | Expr: caseStmtExpr, 145 | As: "case_expr", 146 | }). 147 | From("atable") 148 | 149 | sql, args, err := qb.SQL() 150 | 151 | if err != nil { 152 | t.Errorf("unexpected error: %v", err) 153 | } 154 | 155 | want := "SELECT " + 156 | "(CASE x = $1 WHEN true THEN $2 ELSE 42 END) AS case_noval, " + 157 | "(CASE WHEN x = $3 THEN 'x is zero' WHEN x > $4 THEN CONCAT('x is greater than ', $5) END) AS case_expr " + 158 | "FROM atable" 159 | 160 | if sql != want { 161 | t.Errorf("wanted %v, got %v instead", want, sql) 162 | } 163 | 164 | expectedArgs := []any{ 165 | true, "it's true!", 166 | 0, 1, 2, 167 | } 168 | if !reflect.DeepEqual(args, expectedArgs) { 169 | t.Errorf("wanted %v, got %v instead", expectedArgs, args) 170 | } 171 | } 172 | 173 | func TestCaseWithNoWhenClause(t *testing.T) { 174 | t.Parallel() 175 | caseStmt := Case("something"). 176 | Else("42") 177 | 178 | qb := Select().Column(caseStmt).From("atable") 179 | 180 | _, _, err := qb.SQL() 181 | 182 | want := "case expression must contain at lease one WHEN clause" 183 | if err.Error() != want { 184 | t.Errorf("wanted error to be %v, got %v instead", want, err) 185 | } 186 | } 187 | 188 | func TestCaseBuilderMustSQL(t *testing.T) { 189 | t.Parallel() 190 | defer func() { 191 | if r := recover(); r == nil { 192 | t.Errorf("TestCaseBuilderMustSQL should have panicked!") 193 | } 194 | }() 195 | Case("").MustSQL() 196 | } 197 | -------------------------------------------------------------------------------- /delete.go: -------------------------------------------------------------------------------- 1 | package pgq 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "strings" 7 | ) 8 | 9 | // DeleteBuilder builds SQL DELETE statements. 10 | type DeleteBuilder struct { 11 | prefixes []SQLizer 12 | from string 13 | usingParts []SQLizer 14 | whereParts []SQLizer 15 | orderBys []string 16 | returning []SQLizer 17 | suffixes []SQLizer 18 | } 19 | 20 | // SQL builds the query into a SQL string and bound args. 21 | func (b DeleteBuilder) SQL() (sqlStr string, args []any, err error) { 22 | sqlStr, args, err = b.unfinalizedSQL() 23 | if err != nil { 24 | return 25 | } 26 | 27 | sqlStr, err = dollarPlaceholder(sqlStr) 28 | return 29 | } 30 | 31 | func (b DeleteBuilder) unfinalizedSQL() (sqlStr string, args []any, err error) { 32 | if b.from == "" { 33 | err = fmt.Errorf("delete statements must specify a From table") 34 | return 35 | } 36 | 37 | sql := &bytes.Buffer{} 38 | 39 | if len(b.prefixes) > 0 { 40 | args, err = appendSQL(b.prefixes, sql, " ", args) 41 | if err != nil { 42 | return 43 | } 44 | 45 | sql.WriteString(" ") 46 | } 47 | 48 | sql.WriteString("DELETE FROM ") 49 | sql.WriteString(b.from) 50 | 51 | if len(b.usingParts) > 0 { 52 | sql.WriteString(" USING ") 53 | args, err = appendSQL(b.usingParts, sql, ", ", args) 54 | if err != nil { 55 | return 56 | } 57 | } 58 | 59 | if len(b.whereParts) > 0 { 60 | sql.WriteString(" WHERE ") 61 | args, err = appendSQL(b.whereParts, sql, " AND ", args) 62 | if err != nil { 63 | return 64 | } 65 | } 66 | 67 | if len(b.orderBys) > 0 { 68 | sql.WriteString(" ORDER BY ") 69 | sql.WriteString(strings.Join(b.orderBys, ", ")) 70 | } 71 | 72 | if len(b.returning) > 0 { 73 | sql.WriteString(" RETURNING ") 74 | args, err = appendSQL(b.returning, sql, ", ", args) 75 | if err != nil { 76 | return 77 | } 78 | } 79 | 80 | if len(b.suffixes) > 0 { 81 | sql.WriteString(" ") 82 | args, err = appendSQL(b.suffixes, sql, " ", args) 83 | if err != nil { 84 | return 85 | } 86 | } 87 | 88 | sqlStr = sql.String() 89 | return 90 | } 91 | 92 | // MustSQL builds the query into a SQL string and bound args. 93 | // It panics if there are any errors. 94 | func (b DeleteBuilder) MustSQL() (string, []any) { 95 | sql, args, err := b.SQL() 96 | if err != nil { 97 | panic(err) 98 | } 99 | return sql, args 100 | } 101 | 102 | // Prefix adds an expression to the beginning of the query 103 | func (b DeleteBuilder) Prefix(sql string, args ...any) DeleteBuilder { 104 | return b.PrefixExpr(Expr(sql, args...)) 105 | } 106 | 107 | // PrefixExpr adds an expression to the very beginning of the query 108 | func (b DeleteBuilder) PrefixExpr(expr SQLizer) DeleteBuilder { 109 | b.prefixes = append(b.prefixes, expr) 110 | return b 111 | } 112 | 113 | // From sets the table to be deleted from. 114 | func (b DeleteBuilder) From(from string) DeleteBuilder { 115 | b.from = from 116 | return b 117 | } 118 | 119 | // Using adds USING expressions to the query. 120 | // 121 | // A table expression allowing columns from other tables to appear in the WHERE condition. 122 | // This uses the same syntax as the FROM clause of a SELECT statement. 123 | // Do not repeat the target table unless you intend a self-join (in which case, you must use an alias). 124 | func (b DeleteBuilder) Using(items ...string) DeleteBuilder { 125 | parts := make([]SQLizer, 0, len(items)) 126 | for _, str := range items { 127 | parts = append(parts, newPart(str)) 128 | } 129 | b.usingParts = append(b.usingParts, parts...) 130 | return b 131 | } 132 | 133 | // UsingSelect adds USING expressions to the query similar to Using, but takes a Select statement. 134 | func (b DeleteBuilder) UsingSelect(from SelectBuilder, alias string) DeleteBuilder { 135 | b.usingParts = append(b.usingParts, Alias{Expr: from, As: alias}) 136 | return b 137 | } 138 | 139 | // Where adds WHERE expressions to the query. 140 | // 141 | // See SelectBuilder.Where for more information. 142 | func (b DeleteBuilder) Where(pred any, args ...any) DeleteBuilder { 143 | b.whereParts = append(b.whereParts, newWherePart(pred, args...)) 144 | return b 145 | } 146 | 147 | // OrderBy adds ORDER BY expressions to the query. 148 | func (b DeleteBuilder) OrderBy(orderBys ...string) DeleteBuilder { 149 | b.orderBys = append(b.orderBys, orderBys...) 150 | return b 151 | } 152 | 153 | // Returning adds RETURNING expressions to the query. 154 | func (b DeleteBuilder) Returning(columns ...string) DeleteBuilder { 155 | parts := make([]SQLizer, 0, len(columns)) 156 | for _, col := range columns { 157 | parts = append(parts, newPart(col)) 158 | } 159 | b.returning = append(b.returning, parts...) 160 | return b 161 | } 162 | 163 | // ReturningSelect adds a RETURNING expressions to the query similar to Using, but takes a Select statement. 164 | func (b DeleteBuilder) ReturningSelect(from SelectBuilder, alias string) DeleteBuilder { 165 | b.returning = append(b.returning, Alias{Expr: from, As: alias}) 166 | return b 167 | } 168 | 169 | // Suffix adds an expression to the end of the query 170 | func (b DeleteBuilder) Suffix(sql string, args ...any) DeleteBuilder { 171 | return b.SuffixExpr(Expr(sql, args...)) 172 | } 173 | 174 | // SuffixExpr adds an expression to the end of the query 175 | func (b DeleteBuilder) SuffixExpr(expr SQLizer) DeleteBuilder { 176 | b.suffixes = append(b.suffixes, expr) 177 | return b 178 | } 179 | -------------------------------------------------------------------------------- /delete_test.go: -------------------------------------------------------------------------------- 1 | package pgq 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestDeleteBuilderSQL(t *testing.T) { 9 | t.Parallel() 10 | beginning := Delete(""). 11 | Prefix("WITH prefix AS ?", 0). 12 | From("a"). 13 | Where("b = ?", 1). 14 | OrderBy("c") 15 | 16 | testCases := []struct { 17 | name string 18 | b DeleteBuilder 19 | wantSQL string 20 | wantArgs []any 21 | wantErr error 22 | }{ 23 | { 24 | name: "with_suffix", 25 | b: Delete(""). 26 | Prefix("WITH prefix AS ?", 0). 27 | From("a"). 28 | Where("b = ?", 1). 29 | OrderBy("c"). 30 | Suffix("RETURNING ?", 4), 31 | wantSQL: "WITH prefix AS $1 DELETE FROM a WHERE b = $2 ORDER BY c RETURNING $3", 32 | wantArgs: []any{0, 1, 4}, 33 | }, 34 | { 35 | name: "returning", 36 | b: beginning.Returning("x"), 37 | wantSQL: "WITH prefix AS $1 DELETE FROM a WHERE b = $2 ORDER BY c RETURNING x", 38 | wantArgs: []any{0, 1}, 39 | }, 40 | { 41 | name: "returning_2", 42 | b: beginning.Returning("x", "y"), 43 | wantSQL: "WITH prefix AS $1 DELETE FROM a WHERE b = $2 ORDER BY c RETURNING x, y", 44 | wantArgs: []any{0, 1}, 45 | }, 46 | { 47 | name: "returning_3", 48 | b: beginning.Returning("x", "y", "z"), 49 | wantSQL: "WITH prefix AS $1 DELETE FROM a WHERE b = $2 ORDER BY c RETURNING x, y, z", 50 | wantArgs: []any{0, 1}, 51 | }, 52 | { 53 | name: "returning_3_multi_calls", 54 | b: beginning.Returning("x", "y").Returning("z"), 55 | wantSQL: "WITH prefix AS $1 DELETE FROM a WHERE b = $2 ORDER BY c RETURNING x, y, z", 56 | wantArgs: []any{0, 1}, 57 | }, 58 | { 59 | name: "returning_select", 60 | b: beginning.ReturningSelect(Select("abc").From("atable"), "something"), 61 | wantSQL: "WITH prefix AS $1 DELETE FROM a WHERE b = $2 ORDER BY c RETURNING (SELECT abc FROM atable) AS something", 62 | wantArgs: []any{0, 1}, 63 | }, 64 | { 65 | name: "delete_using", 66 | b: Delete("films").Using("producers").Where("producer_id = producers.id").Where("producers.name = ?", "foo"), 67 | wantSQL: "DELETE FROM films USING producers WHERE producer_id = producers.id AND producers.name = $1", 68 | wantArgs: []any{"foo"}, 69 | }, 70 | { 71 | name: "delete_using_select", 72 | b: Delete("films").UsingSelect(Select("id").From("producers").Where("name = ?", "foo"), "p"), 73 | wantSQL: "DELETE FROM films USING (SELECT id FROM producers WHERE name = $1) AS p", 74 | wantArgs: []any{"foo"}, 75 | }, 76 | } 77 | 78 | for _, tc := range testCases { 79 | tc := tc 80 | t.Run(tc.name, func(t *testing.T) { 81 | t.Parallel() 82 | sql, args, err := tc.b.SQL() 83 | if err != tc.wantErr { 84 | t.Errorf("expected error to be %v, got %v instead", tc.wantErr, err) 85 | } 86 | if sql != tc.wantSQL { 87 | t.Errorf("expected SQL to be %q, got %q instead", tc.wantSQL, sql) 88 | } 89 | if !reflect.DeepEqual(args, tc.wantArgs) { 90 | t.Errorf("wanted %v, got %v instead", tc.wantArgs, args) 91 | } 92 | }) 93 | } 94 | } 95 | 96 | func TestDeleteBuilderSQLErr(t *testing.T) { 97 | t.Parallel() 98 | _, _, err := Delete("").SQL() 99 | want := "delete statements must specify a From table" 100 | if err.Error() != want { 101 | t.Errorf("expected error to be %q, got %q instead", want, err) 102 | } 103 | } 104 | 105 | func TestDeleteBuilderMustSQL(t *testing.T) { 106 | t.Parallel() 107 | defer func() { 108 | if r := recover(); r == nil { 109 | t.Errorf("TestDeleteBuilderMustSQL should have panicked!") 110 | } 111 | }() 112 | Delete("").MustSQL() 113 | } 114 | 115 | func TestDeleteBuilder(t *testing.T) { 116 | t.Parallel() 117 | b := Delete("test").Where("x = ? AND y = ?", 1, 2) 118 | 119 | sql, args, err := b.SQL() 120 | if err != nil { 121 | t.Errorf("unexpected error: %v", err) 122 | } 123 | expectedArgs := []any{1, 2} 124 | if !reflect.DeepEqual(args, expectedArgs) { 125 | t.Errorf("wanted %v, got %v instead", expectedArgs, sql) 126 | } 127 | if want := "DELETE FROM test WHERE x = $1 AND y = $2"; sql != want { 128 | t.Errorf("expected %q, got %q instead", want, sql) 129 | } 130 | } 131 | 132 | func TestDeleteWithQuery(t *testing.T) { 133 | t.Parallel() 134 | b := Delete("test").Where("id=55").Suffix("RETURNING path") 135 | 136 | want := "DELETE FROM test WHERE id=55 RETURNING path" 137 | 138 | got, args := b.MustSQL() 139 | if got != want { 140 | t.Errorf("expected %q, got %q instead", want, got) 141 | } 142 | if len(args) != 0 { 143 | t.Errorf("wanted 0 arguments, got %d instead", len(args)) 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /expr.go: -------------------------------------------------------------------------------- 1 | package pgq 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "reflect" 7 | "sort" 8 | "strings" 9 | "time" 10 | ) 11 | 12 | const ( 13 | // PostgreSQL true/false literals. 14 | sqlTrue = "(TRUE)" 15 | sqlFalse = "(FALSE)" 16 | ) 17 | 18 | type expr struct { 19 | sql string 20 | args []any 21 | } 22 | 23 | // Expr builds an expression from a SQL fragment and arguments. 24 | // 25 | // Ex: 26 | // 27 | // Expr("FROM_UNIXTIME(?)", t) 28 | func Expr(sql string, args ...any) SQLizer { 29 | return expr{sql: sql, args: args} 30 | } 31 | 32 | func (e expr) SQL() (sql string, args []any, err error) { 33 | simple := true 34 | for _, arg := range e.args { 35 | if _, ok := arg.(SQLizer); ok { 36 | simple = false 37 | } 38 | } 39 | if simple { 40 | return e.sql, e.args, nil 41 | } 42 | 43 | buf := &bytes.Buffer{} 44 | ap := e.args 45 | sp := e.sql 46 | 47 | var isql string 48 | var iargs []any 49 | 50 | for err == nil && len(ap) > 0 && sp != "" { 51 | i := strings.Index(sp, "?") 52 | if i < 0 { 53 | // no more placeholders 54 | break 55 | } 56 | if len(sp) > i+1 && sp[i+1:i+2] == "?" { 57 | // escaped "??"; append it and step past 58 | buf.WriteString(sp[:i+2]) 59 | sp = sp[i+2:] 60 | continue 61 | } 62 | 63 | if as, ok := ap[0].(SQLizer); ok { 64 | // sqlizer argument; expand it and append the result 65 | isql, iargs, err = as.SQL() 66 | buf.WriteString(sp[:i]) 67 | buf.WriteString(isql) 68 | args = append(args, iargs...) 69 | } else { 70 | // normal argument; append it and the placeholder 71 | buf.WriteString(sp[:i+1]) 72 | args = append(args, ap[0]) 73 | } 74 | 75 | // step past the argument and placeholder 76 | ap = ap[1:] 77 | sp = sp[i+1:] 78 | } 79 | 80 | // append the remaining sql and arguments 81 | buf.WriteString(sp) 82 | return buf.String(), append(args, ap...), err 83 | } 84 | 85 | // ConcatSQL builds a SQL of an expression by concatenating strings and other expressions. 86 | // 87 | // Ex: 88 | // 89 | // name_expr := Expr("CONCAT(?, ' ', ?)", firstName, lastName) 90 | // ConcatSQL("COALESCE(full_name,", name_expr, ")") 91 | func ConcatSQL(ce ...any) (sql string, args []any, err error) { 92 | for _, part := range ce { 93 | switch p := part.(type) { 94 | case string: 95 | sql += p 96 | case SQLizer: 97 | pSQL, pArgs, err := p.SQL() 98 | if err != nil { 99 | return "", nil, err 100 | } 101 | sql += pSQL 102 | args = append(args, pArgs...) 103 | default: 104 | return "", nil, fmt.Errorf("%#v is not a string or SQLizer", part) 105 | } 106 | } 107 | return 108 | } 109 | 110 | // Alias allows to define alias for column in SelectBuilder. Useful when column is 111 | // defined as complex expression like IF or CASE 112 | // Ex: 113 | // 114 | // .Column(Alias{Expr: caseStmt, Alias: "case_column"}) 115 | type Alias struct { 116 | Expr SQLizer 117 | As string 118 | } 119 | 120 | // AliasExprSQL returns a SQL query based on the alias. 121 | func (a Alias) SQL() (sql string, args []any, err error) { 122 | sql, args, err = a.Expr.SQL() 123 | if err == nil { 124 | sql = fmt.Sprintf("(%s) AS %s", sql, a.As) 125 | } 126 | return 127 | } 128 | 129 | // Eq is syntactic sugar for use with Where/Having/Set methods. 130 | type Eq map[string]any 131 | 132 | func (eq Eq) toSQL(useNotOpr bool) (sql string, args []any, err error) { 133 | if len(eq) == 0 { 134 | // Empty SQL{} evaluates to true. 135 | sql = sqlTrue 136 | return 137 | } 138 | 139 | var ( 140 | exprs []string 141 | equalOpr = "=" 142 | nullOpr = "IS" 143 | inEmptyExpr = sqlFalse 144 | inOpr = "ANY" 145 | ) 146 | 147 | if useNotOpr { 148 | equalOpr = "<>" 149 | nullOpr = "IS NOT" 150 | inEmptyExpr = sqlTrue 151 | inOpr = "ALL" 152 | } 153 | 154 | sortedKeys := getSortedKeys(eq) 155 | for _, key := range sortedKeys { 156 | var expr string 157 | val := eq[key] 158 | 159 | switch v := val.(type) { 160 | case Valuer: 161 | if val, err = v.Value(); err != nil { 162 | return 163 | } 164 | } 165 | 166 | r := reflect.ValueOf(val) 167 | if r.Kind() == reflect.Ptr { 168 | if r.IsNil() { 169 | val = nil 170 | } else { 171 | val = r.Elem().Interface() 172 | } 173 | } 174 | 175 | if val == nil { 176 | expr = fmt.Sprintf("%s %s NULL", key, nullOpr) 177 | } else { 178 | if isListType(val) { 179 | valVal := reflect.ValueOf(val) 180 | if valVal.Len() == 0 { 181 | expr = inEmptyExpr 182 | if args == nil { 183 | args = []any{} 184 | } 185 | } else { 186 | expr = fmt.Sprintf("%s %s %s (?)", key, equalOpr, inOpr) 187 | args = append(args, val) 188 | } 189 | } else { 190 | expr = fmt.Sprintf("%s %s ?", key, equalOpr) 191 | args = append(args, val) 192 | } 193 | } 194 | exprs = append(exprs, expr) 195 | } 196 | sql = strings.Join(exprs, " AND ") 197 | return 198 | } 199 | 200 | func (eq Eq) SQL() (sql string, args []any, err error) { 201 | return eq.toSQL(false) 202 | } 203 | 204 | // NotEq is syntactic sugar for use with Where/Having/Set methods. 205 | // Ex: 206 | // 207 | // .Where(NotEq{"id": 1}) == "id <> 1" 208 | type NotEq Eq 209 | 210 | func (neq NotEq) SQL() (sql string, args []any, err error) { 211 | return Eq(neq).toSQL(true) 212 | } 213 | 214 | // Like is syntactic sugar for use with LIKE conditions. 215 | // Ex: 216 | // 217 | // .Where(Like{"name": "%irrel"}) 218 | type Like map[string]any 219 | 220 | func (lk Like) toSQL(opr string) (sql string, args []any, err error) { 221 | var exprs []string 222 | for key, val := range lk { 223 | expr := "" 224 | 225 | switch v := val.(type) { 226 | case Valuer: 227 | if val, err = v.Value(); err != nil { 228 | return 229 | } 230 | } 231 | 232 | if val == nil { 233 | err = fmt.Errorf("cannot use null with like operators") 234 | return 235 | } else { 236 | if isListType(val) { 237 | err = fmt.Errorf("cannot use array or slice with like operators") 238 | return 239 | } else { 240 | expr = fmt.Sprintf("%s %s ?", key, opr) 241 | args = append(args, val) 242 | } 243 | } 244 | exprs = append(exprs, expr) 245 | } 246 | sql = strings.Join(exprs, " AND ") 247 | return 248 | } 249 | 250 | func (lk Like) SQL() (sql string, args []any, err error) { 251 | return lk.toSQL("LIKE") 252 | } 253 | 254 | // NotLike is syntactic sugar for use with LIKE conditions. 255 | // Ex: 256 | // 257 | // .Where(NotLike{"name": "%irrel"}) 258 | type NotLike Like 259 | 260 | func (nlk NotLike) SQL() (sql string, args []any, err error) { 261 | return Like(nlk).toSQL("NOT LIKE") 262 | } 263 | 264 | // ILike is syntactic sugar for use with ILIKE conditions. 265 | // Ex: 266 | // 267 | // .Where(ILike{"name": "sq%"}) 268 | type ILike Like 269 | 270 | func (ilk ILike) SQL() (sql string, args []any, err error) { 271 | return Like(ilk).toSQL("ILIKE") 272 | } 273 | 274 | // NotILike is syntactic sugar for use with ILIKE conditions. 275 | // Ex: 276 | // 277 | // .Where(NotILike{"name": "sq%"}) 278 | type NotILike Like 279 | 280 | func (nilk NotILike) SQL() (sql string, args []any, err error) { 281 | return Like(nilk).toSQL("NOT ILIKE") 282 | } 283 | 284 | // Lt is syntactic sugar for use with Where/Having/Set methods. 285 | // Ex: 286 | // 287 | // .Where(Lt{"id": 1}) 288 | type Lt map[string]any 289 | 290 | func (lt Lt) toSQL(opposite, orEq bool) (sql string, args []any, err error) { 291 | var ( 292 | exprs []string 293 | opr = "<" 294 | ) 295 | 296 | if opposite { 297 | opr = ">" 298 | } 299 | 300 | if orEq { 301 | opr = fmt.Sprintf("%s%s", opr, "=") 302 | } 303 | 304 | sortedKeys := getSortedKeys(lt) 305 | for _, key := range sortedKeys { 306 | var expr string 307 | val := lt[key] 308 | 309 | switch v := val.(type) { 310 | case Valuer: 311 | if val, err = v.Value(); err != nil { 312 | return 313 | } 314 | } 315 | 316 | if val == nil { 317 | err = fmt.Errorf("cannot use null with less than or greater than operators") 318 | return 319 | } 320 | if isListType(val) { 321 | err = fmt.Errorf("cannot use array or slice with less than or greater than operators") 322 | return 323 | } 324 | expr = fmt.Sprintf("%s %s ?", key, opr) 325 | args = append(args, val) 326 | 327 | exprs = append(exprs, expr) 328 | } 329 | sql = strings.Join(exprs, " AND ") 330 | return 331 | } 332 | 333 | func (lt Lt) SQL() (sql string, args []any, err error) { 334 | return lt.toSQL(false, false) 335 | } 336 | 337 | // LtOrEq is syntactic sugar for use with Where/Having/Set methods. 338 | // Ex: 339 | // 340 | // .Where(LtOrEq{"id": 1}) == "id <= 1" 341 | type LtOrEq Lt 342 | 343 | func (ltOrEq LtOrEq) SQL() (sql string, args []any, err error) { 344 | return Lt(ltOrEq).toSQL(false, true) 345 | } 346 | 347 | // Gt is syntactic sugar for use with Where/Having/Set methods. 348 | // Ex: 349 | // 350 | // .Where(Gt{"id": 1}) == "id > 1" 351 | type Gt Lt 352 | 353 | func (gt Gt) SQL() (sql string, args []any, err error) { 354 | return Lt(gt).toSQL(true, false) 355 | } 356 | 357 | // GtOrEq is syntactic sugar for use with Where/Having/Set methods. 358 | // Ex: 359 | // 360 | // .Where(GtOrEq{"id": 1}) == "id >= 1" 361 | type GtOrEq Lt 362 | 363 | func (gtOrEq GtOrEq) SQL() (sql string, args []any, err error) { 364 | return Lt(gtOrEq).toSQL(true, true) 365 | } 366 | 367 | func join(c []SQLizer, sep, defaultExpr string) (sql string, args []any, err error) { 368 | if len(c) == 0 { 369 | return defaultExpr, []any{}, nil 370 | } 371 | var sqlParts []string 372 | for _, sqlizer := range c { 373 | partSQL, partArgs, err := nestedSQL(sqlizer) 374 | if err != nil { 375 | return "", nil, err 376 | } 377 | if partSQL != "" { 378 | sqlParts = append(sqlParts, partSQL) 379 | args = append(args, partArgs...) 380 | } 381 | } 382 | if len(sqlParts) > 0 { 383 | sql = fmt.Sprintf("(%s)", strings.Join(sqlParts, sep)) 384 | } 385 | return 386 | } 387 | 388 | // And conjunction SQLizers 389 | type And []SQLizer 390 | 391 | func (a And) SQL() (string, []any, error) { 392 | return join(a, " AND ", sqlTrue) 393 | } 394 | 395 | // Or conjunction SQLizers 396 | type Or []SQLizer 397 | 398 | func (o Or) SQL() (string, []any, error) { 399 | return join(o, " OR ", sqlFalse) 400 | } 401 | 402 | func getSortedKeys(exp map[string]any) []string { 403 | sortedKeys := make([]string, 0, len(exp)) 404 | for k := range exp { 405 | sortedKeys = append(sortedKeys, k) 406 | } 407 | sort.Strings(sortedKeys) 408 | return sortedKeys 409 | } 410 | 411 | func isListType(val any) bool { 412 | if isValue(val) { 413 | return false 414 | } 415 | valVal := reflect.ValueOf(val) 416 | return valVal.Kind() == reflect.Array || valVal.Kind() == reflect.Slice 417 | } 418 | 419 | // Valuer is the interface providing the Value method. 420 | // 421 | // Types implementing Valuer interface are able to convert 422 | // themselves to a driver Value. 423 | // 424 | // Similar to database/sql/driver.Value, but returns any instead of driver.Value. 425 | type Valuer interface { 426 | // Value returns a driver Value. 427 | // Value must not panic. 428 | Value() (any, error) 429 | } 430 | 431 | // isValue reports whether v is a valid Value parameter type. 432 | // 433 | // Similar to database/sql/driver.IsValue, but doesn't accept driver.decimalDecompose. 434 | func isValue(v any) bool { 435 | if v == nil { 436 | return true 437 | } 438 | switch v.(type) { 439 | case []byte, bool, float64, int64, string, time.Time: 440 | return true 441 | } 442 | return false 443 | } 444 | -------------------------------------------------------------------------------- /expr_test.go: -------------------------------------------------------------------------------- 1 | package pgq 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestConcatExpr(t *testing.T) { 9 | t.Parallel() 10 | sql, args, err := ConcatSQL("COALESCE(name,", Expr("CONCAT(?,' ',?)", "f", "l"), ")") 11 | if err != nil { 12 | t.Errorf("unexpected error: %v", err) 13 | } 14 | 15 | want := "COALESCE(name,CONCAT(?,' ',?))" 16 | if want != sql { 17 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 18 | } 19 | 20 | expectedArgs := []any{"f", "l"} 21 | if !reflect.DeepEqual(expectedArgs, args) { 22 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 23 | } 24 | } 25 | 26 | func TestConcatExprBadType(t *testing.T) { 27 | t.Parallel() 28 | _, _, err := ConcatSQL("prefix", 123, "suffix") 29 | want := "123 is not a string or SQLizer" 30 | if err.Error() != want { 31 | t.Errorf("expected error to be %q, got %q instead", want, err) 32 | } 33 | if want := "123 is not a string or SQLizer"; err.Error() != want { 34 | t.Errorf("expected %q, got %q instead", want, err) 35 | } 36 | } 37 | 38 | func TestEqSQL(t *testing.T) { 39 | t.Parallel() 40 | b := Eq{"id": 1} 41 | sql, args, err := b.SQL() 42 | if err != nil { 43 | t.Errorf("unexpected error: %v", err) 44 | } 45 | 46 | want := "id = ?" 47 | if want != sql { 48 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 49 | } 50 | 51 | expectedArgs := []any{1} 52 | if !reflect.DeepEqual(expectedArgs, args) { 53 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 54 | } 55 | } 56 | 57 | func TestEqEmptySQL(t *testing.T) { 58 | t.Parallel() 59 | sql, args, err := Eq{}.SQL() 60 | if err != nil { 61 | t.Errorf("unexpected error: %v", err) 62 | } 63 | 64 | want := "(TRUE)" 65 | if want != sql { 66 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 67 | } 68 | if len(args) != 0 { 69 | t.Errorf("wanted 0 arguments, got %d instead", len(args)) 70 | } 71 | } 72 | 73 | func TestEqInSQL(t *testing.T) { 74 | t.Parallel() 75 | b := Eq{"id": []int{1, 2, 3}} 76 | sql, args, err := b.SQL() 77 | if err != nil { 78 | t.Errorf("unexpected error: %v", err) 79 | } 80 | 81 | want := "id = ANY (?)" 82 | if want != sql { 83 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 84 | } 85 | 86 | expectedArgs := []any{[]int{1, 2, 3}} 87 | if !reflect.DeepEqual(expectedArgs, args) { 88 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 89 | } 90 | } 91 | 92 | func TestNotEqSQL(t *testing.T) { 93 | t.Parallel() 94 | b := NotEq{"id": 1} 95 | sql, args, err := b.SQL() 96 | if err != nil { 97 | t.Errorf("unexpected error: %v", err) 98 | } 99 | 100 | want := "id <> ?" 101 | if want != sql { 102 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 103 | } 104 | 105 | expectedArgs := []any{1} 106 | if !reflect.DeepEqual(expectedArgs, args) { 107 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 108 | } 109 | } 110 | 111 | func TestEqNotInSQL(t *testing.T) { 112 | t.Parallel() 113 | b := NotEq{"id": []int{1, 2, 3}} 114 | sql, args, err := b.SQL() 115 | if err != nil { 116 | t.Errorf("unexpected error: %v", err) 117 | } 118 | 119 | want := "id <> ALL (?)" 120 | if want != sql { 121 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 122 | } 123 | 124 | expectedArgs := []any{[]int{1, 2, 3}} 125 | if !reflect.DeepEqual(expectedArgs, args) { 126 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 127 | } 128 | } 129 | 130 | func TestEqInEmptySQL(t *testing.T) { 131 | t.Parallel() 132 | b := Eq{"id": []int{}} 133 | sql, args, err := b.SQL() 134 | if err != nil { 135 | t.Errorf("unexpected error: %v", err) 136 | } 137 | 138 | want := "(FALSE)" 139 | if want != sql { 140 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 141 | } 142 | 143 | expectedArgs := []any{} 144 | if !reflect.DeepEqual(expectedArgs, args) { 145 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 146 | } 147 | } 148 | 149 | func TestNotEqInEmptySQL(t *testing.T) { 150 | t.Parallel() 151 | b := NotEq{"id": []int{}} 152 | sql, args, err := b.SQL() 153 | if err != nil { 154 | t.Errorf("unexpected error: %v", err) 155 | } 156 | 157 | want := "(TRUE)" 158 | if want != sql { 159 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 160 | } 161 | 162 | expectedArgs := []any{} 163 | if !reflect.DeepEqual(expectedArgs, args) { 164 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 165 | } 166 | } 167 | 168 | func TestEqBytesSQL(t *testing.T) { 169 | t.Parallel() 170 | b := Eq{"id": []byte("test")} 171 | sql, args, err := b.SQL() 172 | if err != nil { 173 | t.Errorf("unexpected error: %v", err) 174 | } 175 | 176 | want := "id = ?" 177 | if want != sql { 178 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 179 | } 180 | 181 | expectedArgs := []any{[]byte("test")} 182 | if !reflect.DeepEqual(expectedArgs, args) { 183 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 184 | } 185 | } 186 | 187 | func TestLtSQL(t *testing.T) { 188 | t.Parallel() 189 | b := Lt{"id": 1} 190 | sql, args, err := b.SQL() 191 | if err != nil { 192 | t.Errorf("unexpected error: %v", err) 193 | } 194 | 195 | want := "id < ?" 196 | if want != sql { 197 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 198 | } 199 | 200 | expectedArgs := []any{1} 201 | if !reflect.DeepEqual(expectedArgs, args) { 202 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 203 | } 204 | } 205 | 206 | func TestLtOrEqSQL(t *testing.T) { 207 | t.Parallel() 208 | b := LtOrEq{"id": 1} 209 | sql, args, err := b.SQL() 210 | if err != nil { 211 | t.Errorf("unexpected error: %v", err) 212 | } 213 | 214 | want := "id <= ?" 215 | if want != sql { 216 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 217 | } 218 | 219 | expectedArgs := []any{1} 220 | if !reflect.DeepEqual(expectedArgs, args) { 221 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 222 | } 223 | } 224 | 225 | func TestGtSQL(t *testing.T) { 226 | t.Parallel() 227 | b := Gt{"id": 1} 228 | sql, args, err := b.SQL() 229 | if err != nil { 230 | t.Errorf("unexpected error: %v", err) 231 | } 232 | 233 | want := "id > ?" 234 | if want != sql { 235 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 236 | } 237 | 238 | expectedArgs := []any{1} 239 | if !reflect.DeepEqual(expectedArgs, args) { 240 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 241 | } 242 | } 243 | 244 | func TestGtOrEqSQL(t *testing.T) { 245 | t.Parallel() 246 | b := GtOrEq{"id": 1} 247 | sql, args, err := b.SQL() 248 | if err != nil { 249 | t.Errorf("unexpected error: %v", err) 250 | } 251 | 252 | want := "id >= ?" 253 | if want != sql { 254 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 255 | } 256 | 257 | expectedArgs := []any{1} 258 | if !reflect.DeepEqual(expectedArgs, args) { 259 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 260 | } 261 | } 262 | 263 | func TestExprNilSQL(t *testing.T) { 264 | t.Parallel() 265 | var b SQLizer 266 | b = NotEq{"name": nil} 267 | sql, args, err := b.SQL() 268 | if err != nil { 269 | t.Errorf("unexpected error: %v", err) 270 | } 271 | if len(args) != 0 { 272 | t.Errorf("wanted 0 arguments, got %d instead", len(args)) 273 | } 274 | 275 | want := "name IS NOT NULL" 276 | if want != sql { 277 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 278 | } 279 | 280 | b = Eq{"name": nil} 281 | sql, args, err = b.SQL() 282 | if err != nil { 283 | t.Errorf("unexpected error: %v", err) 284 | } 285 | if len(args) != 0 { 286 | t.Errorf("wanted 0 arguments, got %d instead", len(args)) 287 | } 288 | 289 | want = "name IS NULL" 290 | if want != sql { 291 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 292 | } 293 | } 294 | 295 | func TestNullTypeString(t *testing.T) { 296 | t.Parallel() 297 | var b SQLizer 298 | var name *string 299 | 300 | b = Eq{"name": name} 301 | sql, args, err := b.SQL() 302 | 303 | if err != nil { 304 | t.Errorf("unexpected error: %v", err) 305 | } 306 | if len(args) != 0 { 307 | t.Errorf("wanted 0 arguments, got %d instead", len(args)) 308 | } 309 | if want := "name IS NULL"; sql != want { 310 | t.Errorf("expected args to be %q, got %q instead", want, sql) 311 | } 312 | 313 | name = ptr("Name") 314 | b = Eq{"name": name} 315 | sql, args, err = b.SQL() 316 | 317 | if err != nil { 318 | t.Errorf("unexpected error: %v", err) 319 | } 320 | if want := []any{"Name"}; !reflect.DeepEqual(args, want) { 321 | t.Errorf("expected args to be %q, got %q instead", want, args) 322 | } 323 | if want := "name = ?"; sql != want { 324 | t.Errorf("expected args to be %q, got %q instead", want, sql) 325 | } 326 | } 327 | 328 | func TestNullTypeInt64(t *testing.T) { 329 | t.Parallel() 330 | var userID *int64 331 | b := Eq{"user_id": userID} 332 | sql, args, err := b.SQL() 333 | 334 | if err != nil { 335 | t.Errorf("unexpected error: %v", err) 336 | } 337 | if len(args) != 0 { 338 | t.Errorf("wanted 0 arguments, got %d instead", len(args)) 339 | } 340 | if want := "user_id IS NULL"; sql != want { 341 | t.Errorf("expected args to be %q, got %q instead", want, sql) 342 | } 343 | 344 | userID = ptr(int64(10)) 345 | b = Eq{"user_id": userID} 346 | sql, args, err = b.SQL() 347 | 348 | if err != nil { 349 | t.Errorf("unexpected error: %v", err) 350 | } 351 | if want := []any{int64(10)}; !reflect.DeepEqual(args, want) { 352 | t.Errorf("expected args to be %q, got %q instead", want, args) 353 | } 354 | if want := "user_id = ?"; sql != want { 355 | t.Errorf("expected args to be %q, got %q instead", want, sql) 356 | } 357 | } 358 | 359 | func TestNilPointer(t *testing.T) { 360 | t.Parallel() 361 | var name *string = nil 362 | eq := Eq{"name": name} 363 | sql, args, err := eq.SQL() 364 | 365 | if err != nil { 366 | t.Errorf("unexpected error: %v", err) 367 | } 368 | if len(args) != 0 { 369 | t.Errorf("wanted 0 arguments, got %d instead", len(args)) 370 | } 371 | if want := "name IS NULL"; sql != want { 372 | t.Errorf("expected args to be %q, got %q instead", want, sql) 373 | } 374 | 375 | neq := NotEq{"name": name} 376 | sql, args, err = neq.SQL() 377 | 378 | if err != nil { 379 | t.Errorf("unexpected error: %v", err) 380 | } 381 | if len(args) != 0 { 382 | t.Errorf("wanted 0 arguments, got %d instead", len(args)) 383 | } 384 | if want := "name IS NOT NULL"; sql != want { 385 | t.Errorf("expected args to be %q, got %q instead", want, sql) 386 | } 387 | 388 | var ids *[]int = nil 389 | eq = Eq{"id": ids} 390 | sql, args, err = eq.SQL() 391 | if err != nil { 392 | t.Errorf("unexpected error: %v", err) 393 | } 394 | if len(args) != 0 { 395 | t.Errorf("wanted 0 arguments, got %d instead", len(args)) 396 | } 397 | if want := "id IS NULL"; sql != want { 398 | t.Errorf("expected args to be %q, got %q instead", want, sql) 399 | } 400 | 401 | neq = NotEq{"id": ids} 402 | sql, args, err = neq.SQL() 403 | if err != nil { 404 | t.Errorf("unexpected error: %v", err) 405 | } 406 | if len(args) != 0 { 407 | t.Errorf("wanted 0 arguments, got %d instead", len(args)) 408 | } 409 | if want := "id IS NOT NULL"; sql != want { 410 | t.Errorf("expected args to be %q, got %q instead", want, sql) 411 | } 412 | 413 | var ida *[3]int = nil 414 | eq = Eq{"id": ida} 415 | sql, args, err = eq.SQL() 416 | if err != nil { 417 | t.Errorf("unexpected error: %v", err) 418 | } 419 | if len(args) != 0 { 420 | t.Errorf("wanted 0 arguments, got %d instead", len(args)) 421 | } 422 | if want := "id IS NULL"; sql != want { 423 | t.Errorf("expected args to be %q, got %q instead", want, sql) 424 | } 425 | 426 | neq = NotEq{"id": ida} 427 | sql, args, err = neq.SQL() 428 | if err != nil { 429 | t.Errorf("unexpected error: %v", err) 430 | } 431 | if len(args) != 0 { 432 | t.Errorf("wanted 0 arguments, got %d instead", len(args)) 433 | } 434 | if want := "id IS NOT NULL"; sql != want { 435 | t.Errorf("expected args to be %q, got %q instead", want, sql) 436 | } 437 | 438 | } 439 | 440 | func TestNotNilPointer(t *testing.T) { 441 | t.Parallel() 442 | c := "Name" 443 | name := &c 444 | eq := Eq{"name": name} 445 | sql, args, err := eq.SQL() 446 | 447 | if err != nil { 448 | t.Errorf("unexpected error: %v", err) 449 | } 450 | if want := []any{"Name"}; !reflect.DeepEqual(args, want) { 451 | t.Errorf("expected args to be %q, got %q instead", want, args) 452 | } 453 | if want := "name = ?"; sql != want { 454 | t.Errorf("expected args to be %q, got %q instead", want, sql) 455 | } 456 | 457 | neq := NotEq{"name": name} 458 | sql, args, err = neq.SQL() 459 | 460 | if err != nil { 461 | t.Errorf("unexpected error: %v", err) 462 | } 463 | if want := []any{"Name"}; !reflect.DeepEqual(args, want) { 464 | t.Errorf("expected args to be %q, got %q instead", want, args) 465 | } 466 | if want := "name <> ?"; sql != want { 467 | t.Errorf("expected args to be %q, got %q instead", want, sql) 468 | } 469 | 470 | s := []int{1, 2, 3} 471 | ids := &s 472 | eq = Eq{"id": ids} 473 | sql, args, err = eq.SQL() 474 | if err != nil { 475 | t.Errorf("unexpected error: %v", err) 476 | } 477 | if want := []any{[]int{1, 2, 3}}; !reflect.DeepEqual(args, want) { 478 | t.Errorf("expected args to be %q, got %q instead", want, args) 479 | } 480 | if want := "id = ANY (?)"; sql != want { 481 | t.Errorf("expected args to be %q, got %q instead", want, sql) 482 | } 483 | 484 | neq = NotEq{"id": ids} 485 | sql, args, err = neq.SQL() 486 | if err != nil { 487 | t.Errorf("unexpected error: %v", err) 488 | } 489 | if want := []any{[]int{1, 2, 3}}; !reflect.DeepEqual(args, want) { 490 | t.Errorf("expected args to be %q, got %q instead", want, args) 491 | } 492 | if want := "id <> ALL (?)"; sql != want { 493 | t.Errorf("expected args to be %q, got %q instead", want, sql) 494 | } 495 | 496 | a := [3]int{1, 2, 3} 497 | ida := &a 498 | eq = Eq{"id": ida} 499 | sql, args, err = eq.SQL() 500 | if err != nil { 501 | t.Errorf("unexpected error: %v", err) 502 | } 503 | if want := []any{[3]int{1, 2, 3}}; !reflect.DeepEqual(args, want) { 504 | t.Errorf("expected args to be %q, got %q instead", want, args) 505 | } 506 | if want := "id = ANY (?)"; sql != want { 507 | t.Errorf("expected args to be %q, got %q instead", want, sql) 508 | } 509 | 510 | neq = NotEq{"id": ida} 511 | sql, args, err = neq.SQL() 512 | if err != nil { 513 | t.Errorf("unexpected error: %v", err) 514 | } 515 | if want := []any{[3]int{1, 2, 3}}; !reflect.DeepEqual(args, want) { 516 | t.Errorf("expected args to be %q, got %q instead", want, args) 517 | } 518 | if want := "id <> ALL (?)"; sql != want { 519 | t.Errorf("expected args to be %q, got %q instead", want, sql) 520 | } 521 | } 522 | 523 | func TestEmptyAndSQL(t *testing.T) { 524 | t.Parallel() 525 | sql, args, err := And{}.SQL() 526 | if err != nil { 527 | t.Errorf("unexpected error: %v", err) 528 | } 529 | 530 | want := "(TRUE)" 531 | if want != sql { 532 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 533 | } 534 | 535 | expectedArgs := []any{} 536 | if !reflect.DeepEqual(expectedArgs, args) { 537 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 538 | } 539 | } 540 | 541 | func TestEmptyOrSQL(t *testing.T) { 542 | t.Parallel() 543 | sql, args, err := Or{}.SQL() 544 | if err != nil { 545 | t.Errorf("unexpected error: %v", err) 546 | } 547 | 548 | want := "(FALSE)" 549 | if want != sql { 550 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 551 | } 552 | 553 | expectedArgs := []any{} 554 | if !reflect.DeepEqual(expectedArgs, args) { 555 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 556 | } 557 | } 558 | 559 | func TestLikeSQL(t *testing.T) { 560 | t.Parallel() 561 | b := Like{"name": "%irrel"} 562 | sql, args, err := b.SQL() 563 | if err != nil { 564 | t.Errorf("unexpected error: %v", err) 565 | } 566 | 567 | want := "name LIKE ?" 568 | if want != sql { 569 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 570 | } 571 | 572 | expectedArgs := []any{"%irrel"} 573 | if !reflect.DeepEqual(expectedArgs, args) { 574 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 575 | } 576 | } 577 | 578 | func TestNotLikeSQL(t *testing.T) { 579 | t.Parallel() 580 | b := NotLike{"name": "%irrel"} 581 | sql, args, err := b.SQL() 582 | if err != nil { 583 | t.Errorf("unexpected error: %v", err) 584 | } 585 | 586 | want := "name NOT LIKE ?" 587 | if want != sql { 588 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 589 | } 590 | 591 | expectedArgs := []any{"%irrel"} 592 | if !reflect.DeepEqual(expectedArgs, args) { 593 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 594 | } 595 | } 596 | 597 | func TestILikeSQL(t *testing.T) { 598 | t.Parallel() 599 | b := ILike{"name": "sq%"} 600 | sql, args, err := b.SQL() 601 | if err != nil { 602 | t.Errorf("unexpected error: %v", err) 603 | } 604 | 605 | want := "name ILIKE ?" 606 | if want != sql { 607 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 608 | } 609 | 610 | expectedArgs := []any{"sq%"} 611 | if !reflect.DeepEqual(expectedArgs, args) { 612 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 613 | } 614 | } 615 | 616 | func TestNotILikeSQL(t *testing.T) { 617 | t.Parallel() 618 | b := NotILike{"name": "sq%"} 619 | sql, args, err := b.SQL() 620 | if err != nil { 621 | t.Errorf("unexpected error: %v", err) 622 | } 623 | 624 | want := "name NOT ILIKE ?" 625 | if want != sql { 626 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 627 | } 628 | 629 | expectedArgs := []any{"sq%"} 630 | if !reflect.DeepEqual(expectedArgs, args) { 631 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 632 | } 633 | } 634 | 635 | func TestSQLEqOrder(t *testing.T) { 636 | t.Parallel() 637 | b := Eq{"a": 1, "b": 2, "c": 3} 638 | sql, args, err := b.SQL() 639 | if err != nil { 640 | t.Errorf("unexpected error: %v", err) 641 | } 642 | 643 | want := "a = ? AND b = ? AND c = ?" 644 | if want != sql { 645 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 646 | } 647 | 648 | expectedArgs := []any{1, 2, 3} 649 | if !reflect.DeepEqual(expectedArgs, args) { 650 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 651 | } 652 | } 653 | 654 | func TestSQLLtOrder(t *testing.T) { 655 | t.Parallel() 656 | b := Lt{"a": 1, "b": 2, "c": 3} 657 | sql, args, err := b.SQL() 658 | if err != nil { 659 | t.Errorf("unexpected error: %v", err) 660 | } 661 | 662 | want := "a < ? AND b < ? AND c < ?" 663 | if want != sql { 664 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 665 | } 666 | 667 | expectedArgs := []any{1, 2, 3} 668 | if !reflect.DeepEqual(expectedArgs, args) { 669 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 670 | } 671 | } 672 | 673 | func TestExprEscaped(t *testing.T) { 674 | t.Parallel() 675 | b := Expr("count(??)", Expr("x")) 676 | sql, args, err := b.SQL() 677 | if err != nil { 678 | t.Errorf("unexpected error: %v", err) 679 | } 680 | 681 | want := "count(??)" 682 | if want != sql { 683 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 684 | } 685 | 686 | expectedArgs := []any{Expr("x")} 687 | if !reflect.DeepEqual(expectedArgs, args) { 688 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 689 | } 690 | } 691 | 692 | func TestExprRecursion(t *testing.T) { 693 | t.Parallel() 694 | { 695 | b := Expr("count(?)", Expr("nullif(a,?)", "b")) 696 | sql, args, err := b.SQL() 697 | if err != nil { 698 | t.Errorf("unexpected error: %v", err) 699 | } 700 | 701 | want := "count(nullif(a,?))" 702 | if want != sql { 703 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 704 | } 705 | 706 | expectedArgs := []any{"b"} 707 | if !reflect.DeepEqual(expectedArgs, args) { 708 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 709 | } 710 | } 711 | { 712 | b := Expr("extract(? from ?)", Expr("epoch"), "2001-02-03") 713 | sql, args, err := b.SQL() 714 | if err != nil { 715 | t.Errorf("unexpected error: %v", err) 716 | } 717 | 718 | want := "extract(epoch from ?)" 719 | if want != sql { 720 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 721 | } 722 | 723 | expectedArgs := []any{"2001-02-03"} 724 | if !reflect.DeepEqual(expectedArgs, args) { 725 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 726 | } 727 | } 728 | { 729 | b := Expr("JOIN t1 ON ?", And{Eq{"id": 1}, Expr("NOT c1"), Expr("? @@ ?", "x", "y")}) 730 | sql, args, err := b.SQL() 731 | if err != nil { 732 | t.Errorf("unexpected error: %v", err) 733 | } 734 | 735 | want := "JOIN t1 ON (id = ? AND NOT c1 AND ? @@ ?)" 736 | if want != sql { 737 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 738 | } 739 | 740 | expectedArgs := []any{1, "x", "y"} 741 | if !reflect.DeepEqual(expectedArgs, args) { 742 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 743 | } 744 | } 745 | } 746 | 747 | func ExampleEq() { 748 | Select("id", "created", "first_name").From("users").Where(Eq{ 749 | "company": 20, 750 | }) 751 | } 752 | 753 | func ptr[T any](v T) *T { 754 | return &v 755 | } 756 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/henvic/pgq 2 | 3 | go 1.23 4 | -------------------------------------------------------------------------------- /insert.go: -------------------------------------------------------------------------------- 1 | package pgq 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | "fmt" 7 | "io" 8 | "sort" 9 | "strings" 10 | ) 11 | 12 | // InsertBuilder builds SQL INSERT statements. 13 | type InsertBuilder struct { 14 | prefixes []SQLizer 15 | verb string 16 | into string 17 | columns []string 18 | values [][]any 19 | returning []SQLizer 20 | suffixes []SQLizer 21 | selectBuilder *SelectBuilder 22 | } 23 | 24 | // Verb to be used for the operation (default: INSERT). 25 | func (b InsertBuilder) Verb(v string) InsertBuilder { 26 | b.verb = v 27 | return b 28 | } 29 | 30 | // SQL builds the query into a SQL string and bound args. 31 | func (b InsertBuilder) SQL() (sqlStr string, args []any, err error) { 32 | if b.into == "" { 33 | err = errors.New("insert statements must specify a table") 34 | return 35 | } 36 | if len(b.values) == 0 && b.selectBuilder == nil { 37 | err = errors.New("insert statements must have at least one set of values or select clause") 38 | return 39 | } 40 | 41 | sql := &bytes.Buffer{} 42 | 43 | if len(b.prefixes) > 0 { 44 | args, err = appendSQL(b.prefixes, sql, " ", args) 45 | if err != nil { 46 | return 47 | } 48 | 49 | sql.WriteString(" ") 50 | } 51 | 52 | if b.verb != "" { 53 | sql.WriteString(b.verb + " ") 54 | } else { 55 | sql.WriteString("INSERT ") 56 | } 57 | 58 | sql.WriteString("INTO ") 59 | sql.WriteString(b.into) 60 | sql.WriteString(" ") 61 | 62 | if len(b.columns) > 0 { 63 | sql.WriteString("(") 64 | sql.WriteString(strings.Join(b.columns, ",")) 65 | sql.WriteString(") ") 66 | } 67 | 68 | if b.selectBuilder != nil { 69 | args, err = b.appendSelectToSQL(sql, args) 70 | } else { 71 | args, err = b.appendValuesToSQL(sql, args) 72 | } 73 | if err != nil { 74 | return 75 | } 76 | 77 | if len(b.returning) > 0 { 78 | sql.WriteString(" RETURNING ") 79 | args, err = appendSQL(b.returning, sql, ", ", args) 80 | if err != nil { 81 | return 82 | } 83 | } 84 | 85 | if len(b.suffixes) > 0 { 86 | sql.WriteString(" ") 87 | args, err = appendSQL(b.suffixes, sql, " ", args) 88 | if err != nil { 89 | return 90 | } 91 | } 92 | 93 | sqlStr, err = dollarPlaceholder(sql.String()) 94 | return 95 | } 96 | 97 | func (b InsertBuilder) appendValuesToSQL(w io.Writer, args []any) ([]any, error) { 98 | if len(b.values) == 0 { 99 | return args, errors.New("values for insert statements are not set") 100 | } 101 | 102 | io.WriteString(w, "VALUES ") 103 | 104 | valuesStrings := make([]string, len(b.values)) 105 | for r, row := range b.values { 106 | valueStrings := make([]string, len(row)) 107 | for v, val := range row { 108 | if vs, ok := val.(SQLizer); ok { 109 | vsql, vargs, err := vs.SQL() 110 | if err != nil { 111 | return nil, err 112 | } 113 | valueStrings[v] = vsql 114 | args = append(args, vargs...) 115 | } else { 116 | valueStrings[v] = "?" 117 | args = append(args, val) 118 | } 119 | } 120 | valuesStrings[r] = fmt.Sprintf("(%s)", strings.Join(valueStrings, ",")) 121 | } 122 | 123 | io.WriteString(w, strings.Join(valuesStrings, ",")) 124 | 125 | return args, nil 126 | } 127 | 128 | func (b InsertBuilder) appendSelectToSQL(w io.Writer, args []any) ([]any, error) { 129 | if b.selectBuilder == nil { 130 | return args, errors.New("select clause for insert statements are not set") 131 | } 132 | 133 | selectClause, sArgs, err := b.selectBuilder.SQL() 134 | if err != nil { 135 | return args, err 136 | } 137 | 138 | io.WriteString(w, selectClause) 139 | args = append(args, sArgs...) 140 | 141 | return args, nil 142 | } 143 | 144 | // MustSQL builds the query into a SQL string and bound args. 145 | // It panics if there are any errors. 146 | func (b InsertBuilder) MustSQL() (string, []any) { 147 | sql, args, err := b.SQL() 148 | if err != nil { 149 | panic(err) 150 | } 151 | return sql, args 152 | } 153 | 154 | // Prefix adds an expression to the beginning of the query 155 | func (b InsertBuilder) Prefix(sql string, args ...any) InsertBuilder { 156 | return b.PrefixExpr(Expr(sql, args...)) 157 | } 158 | 159 | // PrefixExpr adds an expression to the very beginning of the query 160 | func (b InsertBuilder) PrefixExpr(expr SQLizer) InsertBuilder { 161 | b.prefixes = append(b.prefixes, expr) 162 | return b 163 | } 164 | 165 | // Into sets the INTO clause of the query. 166 | func (b InsertBuilder) Into(from string) InsertBuilder { 167 | b.into = from 168 | return b 169 | } 170 | 171 | // Columns adds insert columns to the query. 172 | func (b InsertBuilder) Columns(columns ...string) InsertBuilder { 173 | b.columns = append(b.columns, columns...) 174 | return b 175 | } 176 | 177 | // Values adds a single row's values to the query. 178 | func (b InsertBuilder) Values(values ...any) InsertBuilder { 179 | b.values = append(b.values, values) 180 | return b 181 | } 182 | 183 | // Returning adds RETURNING expressions to the query. 184 | func (b InsertBuilder) Returning(columns ...string) InsertBuilder { 185 | parts := make([]SQLizer, 0, len(columns)) 186 | for _, col := range columns { 187 | parts = append(parts, newPart(col)) 188 | } 189 | b.returning = append(b.returning, parts...) 190 | return b 191 | } 192 | 193 | // ReturningSelect adds a RETURNING expressions to the query similar to Using, but takes a Select statement. 194 | func (b InsertBuilder) ReturningSelect(from SelectBuilder, alias string) InsertBuilder { 195 | b.returning = append(b.returning, Alias{Expr: from, As: alias}) 196 | return b 197 | } 198 | 199 | // Suffix adds an expression to the end of the query 200 | func (b InsertBuilder) Suffix(sql string, args ...any) InsertBuilder { 201 | return b.SuffixExpr(Expr(sql, args...)) 202 | } 203 | 204 | // SuffixExpr adds an expression to the end of the query 205 | func (b InsertBuilder) SuffixExpr(expr SQLizer) InsertBuilder { 206 | b.suffixes = append(b.suffixes, expr) 207 | return b 208 | } 209 | 210 | // SetMap set columns and values for insert builder from a map of column name and value 211 | // note that it will reset all previous columns and values was set if any 212 | func (b InsertBuilder) SetMap(clauses map[string]any) InsertBuilder { 213 | // Keep the columns in a consistent order by sorting the column key string. 214 | cols := make([]string, 0, len(clauses)) 215 | for col := range clauses { 216 | cols = append(cols, col) 217 | } 218 | sort.Strings(cols) 219 | 220 | vals := make([]any, 0, len(clauses)) 221 | for _, col := range cols { 222 | vals = append(vals, clauses[col]) 223 | } 224 | 225 | b.columns = cols 226 | b.values = [][]any{vals} 227 | return b 228 | } 229 | 230 | // Select set Select clause for insert query 231 | // If Values and Select are used, then Select has higher priority 232 | func (b InsertBuilder) Select(sb SelectBuilder) InsertBuilder { 233 | b.selectBuilder = &sb 234 | return b 235 | } 236 | -------------------------------------------------------------------------------- /insert_test.go: -------------------------------------------------------------------------------- 1 | package pgq 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestInsertBuilderSQL(t *testing.T) { 9 | t.Parallel() 10 | testCases := []struct { 11 | name string 12 | b InsertBuilder 13 | wantSQL string 14 | wantArgs []any 15 | wantErr error 16 | }{ 17 | { 18 | name: "with_suffix", 19 | b: Insert(""). 20 | Prefix("WITH prefix AS ?", 0). 21 | Into("a"). 22 | Columns("b", "c"). 23 | Values(1, 2). 24 | Values(3, Expr("? + 1", 4)). 25 | Suffix("RETURNING ?", 5), 26 | wantSQL: "WITH prefix AS $1 " + 27 | "INSERT INTO a (b,c) VALUES ($2,$3),($4,$5 + 1) " + 28 | "RETURNING $6", 29 | wantArgs: []any{0, 1, 2, 3, 4, 5}, 30 | }, 31 | { 32 | name: "returning", 33 | b: Insert("a"). 34 | Columns("b", "c"). 35 | Values(1, 2). 36 | Values(3, Expr("? + 1", 4)). 37 | Returning("x"), 38 | wantSQL: "INSERT INTO a (b,c) VALUES ($1,$2),($3,$4 + 1) RETURNING x", 39 | wantArgs: []any{1, 2, 3, 4}, 40 | }, 41 | { 42 | name: "returning_2", 43 | b: Insert("a"). 44 | Columns("b", "c"). 45 | Values(1, 2). 46 | Values(3, Expr("? + 1", 4)). 47 | Returning("x", "y"), 48 | wantSQL: "INSERT INTO a (b,c) VALUES ($1,$2),($3,$4 + 1) RETURNING x, y", 49 | wantArgs: []any{1, 2, 3, 4}, 50 | }, 51 | { 52 | name: "returning_3", 53 | b: Insert("a"). 54 | Columns("b", "c"). 55 | Values(1, 2). 56 | Values(3, Expr("? + 1", 4)). 57 | Returning("x", "y", "z"), 58 | wantSQL: "INSERT INTO a (b,c) VALUES ($1,$2),($3,$4 + 1) RETURNING x, y, z", 59 | wantArgs: []any{1, 2, 3, 4}, 60 | }, 61 | { 62 | name: "returning_3_multi_calls", 63 | b: Insert("a"). 64 | Columns("b", "c"). 65 | Values(1, 2). 66 | Values(3, Expr("? + 1", 4)). 67 | Returning("x", "y").Returning("z"), 68 | wantSQL: "INSERT INTO a (b,c) VALUES ($1,$2),($3,$4 + 1) RETURNING x, y, z", 69 | wantArgs: []any{1, 2, 3, 4}, 70 | }, 71 | { 72 | name: "returning_select", 73 | b: Insert("a"). 74 | Columns("b", "c"). 75 | Values(1, 2). 76 | Values(3, Expr("? + 1", 4)). 77 | ReturningSelect(Select("abc").From("atable"), "something"), 78 | wantSQL: "INSERT INTO a (b,c) VALUES ($1,$2),($3,$4 + 1) RETURNING (SELECT abc FROM atable) AS something", 79 | wantArgs: []any{1, 2, 3, 4}, 80 | }, 81 | } 82 | for _, tc := range testCases { 83 | tc := tc 84 | t.Run(tc.name, func(t *testing.T) { 85 | t.Parallel() 86 | sql, args, err := tc.b.SQL() 87 | if err != tc.wantErr { 88 | t.Errorf("expected error to be %v, got %v instead", tc.wantErr, err) 89 | } 90 | if sql != tc.wantSQL { 91 | t.Errorf("expected SQL to be %q, got %q instead", tc.wantSQL, sql) 92 | } 93 | if !reflect.DeepEqual(args, tc.wantArgs) { 94 | t.Errorf("wanted %v, got %v instead", tc.wantArgs, args) 95 | } 96 | }) 97 | } 98 | } 99 | 100 | func TestInsertStruct(t *testing.T) { 101 | example := struct{ What string }{What: "lol"} 102 | t.Parallel() 103 | b := Insert(""). 104 | Into("a"). 105 | Columns("something", "extra"). 106 | Values(1, example) 107 | 108 | sql, args, err := b.SQL() 109 | if err != nil { 110 | t.Errorf("unexpected error: %v", err) 111 | } 112 | 113 | if want := "INSERT INTO a (something,extra) VALUES ($1,$2)"; want != sql { 114 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 115 | } 116 | 117 | expectedArgs := []any{1, example} 118 | if !reflect.DeepEqual(expectedArgs, args) { 119 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 120 | } 121 | } 122 | 123 | func TestInsertBuilderSQLErr(t *testing.T) { 124 | t.Parallel() 125 | _, _, err := Insert("").Values(1).SQL() 126 | if want := "insert statements must specify a table"; err.Error() != want { 127 | t.Errorf("expected error to be %q, got %q instead", want, err) 128 | } 129 | 130 | _, _, err = Insert("x").SQL() 131 | if want := "insert statements must have at least one set of values or select clause"; err.Error() != want { 132 | t.Errorf("expected error to be %q, got %q instead", want, err) 133 | } 134 | } 135 | 136 | func TestInsertBuilderMustSQL(t *testing.T) { 137 | t.Parallel() 138 | defer func() { 139 | if r := recover(); r == nil { 140 | t.Errorf("TestInsertBuilderMustSQL should have panicked!") 141 | } 142 | }() 143 | Insert("").MustSQL() 144 | } 145 | 146 | func TestInsertBuilderPlaceholders(t *testing.T) { 147 | t.Parallel() 148 | b := Insert("test").Values(1, 2) 149 | 150 | sql, _, err := b.SQL() 151 | if err != nil { 152 | t.Errorf("unexpected error: %v", err) 153 | } 154 | if want := "INSERT INTO test VALUES ($1,$2)"; sql != want { 155 | t.Errorf("expected %q, got %q instead", sql, want) 156 | } 157 | } 158 | 159 | func TestInsertBuilderRunners(t *testing.T) { 160 | t.Parallel() 161 | b := Insert("test").Values(1) 162 | 163 | want := "INSERT INTO test VALUES ($1)" 164 | 165 | got, args := b.MustSQL() 166 | if want != got { 167 | t.Errorf("expected SQL to be %q, got %q instead", want, got) 168 | } 169 | if expectedArgs := []any{1}; !reflect.DeepEqual(args, expectedArgs) { 170 | t.Errorf("wanted %v, got %v instead", expectedArgs, args) 171 | } 172 | } 173 | 174 | func TestInsertBuilderSetMap(t *testing.T) { 175 | t.Parallel() 176 | b := Insert("table").SetMap(Eq{"field1": 1, "field2": 2, "field3": 3}) 177 | 178 | sql, args, err := b.SQL() 179 | if err != nil { 180 | t.Errorf("unexpected error: %v", err) 181 | } 182 | 183 | want := "INSERT INTO table (field1,field2,field3) VALUES ($1,$2,$3)" 184 | if want != sql { 185 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 186 | } 187 | 188 | expectedArgs := []any{1, 2, 3} 189 | if !reflect.DeepEqual(expectedArgs, args) { 190 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 191 | } 192 | } 193 | 194 | func TestInsertBuilderSelect(t *testing.T) { 195 | t.Parallel() 196 | sb := Select("field1").From("table1").Where(Eq{"field1": 1}) 197 | ib := Insert("table2").Columns("field1").Select(sb) 198 | 199 | sql, args, err := ib.SQL() 200 | if err != nil { 201 | t.Errorf("unexpected error: %v", err) 202 | } 203 | 204 | want := "INSERT INTO table2 (field1) SELECT field1 FROM table1 WHERE field1 = $1" 205 | if want != sql { 206 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 207 | } 208 | 209 | expectedArgs := []any{1} 210 | if !reflect.DeepEqual(expectedArgs, args) { 211 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 212 | } 213 | } 214 | 215 | func TestInsertBuilderReplace(t *testing.T) { 216 | t.Parallel() 217 | b := Replace("table").Values(1) 218 | 219 | want := "REPLACE INTO table VALUES ($1)" 220 | 221 | sql, _, err := b.SQL() 222 | if err != nil { 223 | t.Errorf("unexpected error: %v", err) 224 | } 225 | 226 | if want != sql { 227 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 228 | } 229 | } 230 | 231 | func TestInsertBuilderVerb(t *testing.T) { 232 | t.Parallel() 233 | b := Insert("table").Verb("REPLACE").Values(1) 234 | 235 | want := "REPLACE INTO table VALUES ($1)" 236 | 237 | sql, _, err := b.SQL() 238 | if err != nil { 239 | t.Errorf("unexpected error: %v", err) 240 | } 241 | 242 | if want != sql { 243 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 244 | } 245 | } 246 | -------------------------------------------------------------------------------- /integration/doc.go: -------------------------------------------------------------------------------- 1 | // This is a tests-only package. 2 | package integration 3 | -------------------------------------------------------------------------------- /integration/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/henvic/pgq/integration 2 | 3 | go 1.24 4 | 5 | require ( 6 | github.com/henvic/pgq v0.0.4 7 | github.com/henvic/pgtools v0.2.0 8 | github.com/jackc/pgx/v5 v5.7.4 9 | ) 10 | 11 | require ( 12 | dario.cat/mergo v1.0.1 // indirect 13 | github.com/Masterminds/goutils v1.1.1 // indirect 14 | github.com/Masterminds/semver/v3 v3.3.1 // indirect 15 | github.com/Masterminds/sprig/v3 v3.3.0 // indirect 16 | github.com/google/uuid v1.6.0 // indirect 17 | github.com/huandu/xstrings v1.5.0 // indirect 18 | github.com/jackc/pgpassfile v1.0.0 // indirect 19 | github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect 20 | github.com/jackc/puddle/v2 v2.2.2 // indirect 21 | github.com/jackc/tern/v2 v2.3.2 // indirect 22 | github.com/mitchellh/copystructure v1.2.0 // indirect 23 | github.com/mitchellh/reflectwalk v1.0.2 // indirect 24 | github.com/shopspring/decimal v1.4.0 // indirect 25 | github.com/spf13/cast v1.7.1 // indirect 26 | golang.org/x/crypto v0.37.0 // indirect 27 | golang.org/x/sync v0.13.0 // indirect 28 | golang.org/x/text v0.24.0 // indirect 29 | ) 30 | 31 | replace github.com/henvic/pgq => ../ 32 | -------------------------------------------------------------------------------- /integration/go.sum: -------------------------------------------------------------------------------- 1 | dario.cat/mergo v1.0.1 h1:Ra4+bf83h2ztPIQYNP99R6m+Y7KfnARDfID+a+vLl4s= 2 | dario.cat/mergo v1.0.1/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk= 3 | github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= 4 | github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= 5 | github.com/Masterminds/semver/v3 v3.3.1 h1:QtNSWtVZ3nBfk8mAOu/B6v7FMJ+NHTIgUPi7rj+4nv4= 6 | github.com/Masterminds/semver/v3 v3.3.1/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= 7 | github.com/Masterminds/sprig/v3 v3.3.0 h1:mQh0Yrg1XPo6vjYXgtf5OtijNAKJRNcTdOOGZe3tPhs= 8 | github.com/Masterminds/sprig/v3 v3.3.0/go.mod h1:Zy1iXRYNqNLUolqCpL4uhk6SHUMAOSCzdgBfDb35Lz0= 9 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 10 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 11 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 12 | github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= 13 | github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= 14 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= 15 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 16 | github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= 17 | github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 18 | github.com/henvic/pgtools v0.2.0 h1:1Sca4p5TJrjXAhxUgzWe0Dn5kCCh3+8WrJ1WRG6areQ= 19 | github.com/henvic/pgtools v0.2.0/go.mod h1:4lq4zJmN6WZZUzMyDQUcdfu5wyKKvUxUuCO2BPeLfsc= 20 | github.com/huandu/xstrings v1.5.0 h1:2ag3IFq9ZDANvthTwTiqSSZLjDc+BedvHPAp5tJy2TI= 21 | github.com/huandu/xstrings v1.5.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= 22 | github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= 23 | github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= 24 | github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= 25 | github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= 26 | github.com/jackc/pgx/v5 v5.7.4 h1:9wKznZrhWa2QiHL+NjTSPP6yjl3451BX3imWDnokYlg= 27 | github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ= 28 | github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= 29 | github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= 30 | github.com/jackc/tern/v2 v2.3.2 h1:/d3ML6jyQGDDtvKCGnHp8HY0swh86VcNvTMkC65+frk= 31 | github.com/jackc/tern/v2 v2.3.2/go.mod h1:cJYmwlpXLs3vBtbkfKdgoZL0G96mH56W+fugKx+k3zw= 32 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= 33 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= 34 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= 35 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= 36 | github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= 37 | github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= 38 | github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= 39 | github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= 40 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 41 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 42 | github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= 43 | github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= 44 | github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k= 45 | github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= 46 | github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y= 47 | github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= 48 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 49 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 50 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 51 | github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= 52 | github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 53 | golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE= 54 | golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc= 55 | golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610= 56 | golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= 57 | golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0= 58 | golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU= 59 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 60 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 61 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 62 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 63 | -------------------------------------------------------------------------------- /integration/integration_test.go: -------------------------------------------------------------------------------- 1 | package integration 2 | 3 | import ( 4 | "context" 5 | "embed" 6 | "flag" 7 | "fmt" 8 | "io/fs" 9 | "log" 10 | "os" 11 | "reflect" 12 | "testing" 13 | "time" 14 | 15 | "github.com/henvic/pgq" 16 | "github.com/henvic/pgtools/sqltest" 17 | "github.com/jackc/pgx/v5" 18 | ) 19 | 20 | //go:embed migrations 21 | var mig embed.FS 22 | 23 | var force = flag.Bool("force", false, "Force cleaning the database before starting") 24 | 25 | func TestMain(m *testing.M) { 26 | if os.Getenv("INTEGRATION_TESTDB") != "true" { 27 | log.Printf("Skipping tests that require database connection") 28 | return 29 | } 30 | os.Exit(m.Run()) 31 | } 32 | 33 | func TestIntegration(t *testing.T) { 34 | t.Parallel() 35 | 36 | fsys, err := fs.Sub(mig, "migrations") 37 | if err != nil { 38 | t.Fatal(fsys) 39 | } 40 | migration := sqltest.New(t, sqltest.Options{ 41 | Force: *force, 42 | Files: fsys, 43 | }) 44 | pool := migration.Setup(context.Background(), "") 45 | 46 | s := pgq.Select("v").From("pgq_integration") 47 | 48 | type sqler interface { 49 | SQL() (sqlStr string, args []any, err error) 50 | } 51 | 52 | var testCases = []struct { 53 | name string 54 | q sqler 55 | sql string 56 | args []any 57 | rows []string 58 | }{ 59 | { 60 | name: "keq4", 61 | q: s.Where(pgq.Eq{"k": 4}), 62 | sql: "SELECT v FROM pgq_integration WHERE k = $1", 63 | args: []any{4}, 64 | rows: []string{"baz"}, 65 | }, 66 | { 67 | name: "kneq2", 68 | q: s.Where(pgq.NotEq{"k": 2}), 69 | sql: "SELECT v FROM pgq_integration WHERE k <> $1", 70 | args: []any{2}, 71 | rows: []string{"foo", "bar", "baz"}, 72 | }, 73 | { 74 | name: "keq14", 75 | q: s.Where(pgq.Eq{"k": []int{1, 4}}), 76 | sql: "SELECT v FROM pgq_integration WHERE k = ANY ($1)", 77 | args: []any{[]int{1, 4}}, 78 | rows: []string{"foo", "baz"}, 79 | }, 80 | { 81 | name: "kneq14", 82 | q: s.Where(pgq.NotEq{"k": []int{1, 4}}), 83 | sql: "SELECT v FROM pgq_integration WHERE k <> ALL ($1)", 84 | args: []any{[]int{1, 4}}, 85 | rows: []string{"bar", "foo"}, 86 | }, 87 | { 88 | name: "knil", 89 | q: s.Where(pgq.Eq{"k": nil}), 90 | sql: "SELECT v FROM pgq_integration WHERE k IS NULL", 91 | rows: []string{}, 92 | }, 93 | { 94 | name: "knotnil", 95 | q: s.Where(pgq.NotEq{"k": nil}), 96 | sql: "SELECT v FROM pgq_integration WHERE k IS NOT NULL", 97 | rows: []string{"foo", "bar", "foo", "baz"}, 98 | }, 99 | { 100 | name: "keqempty", 101 | q: s.Where(pgq.Eq{"k": []int{}}), 102 | sql: "SELECT v FROM pgq_integration WHERE (FALSE)", 103 | rows: []string{}, 104 | }, 105 | { 106 | name: "knoteqempty", 107 | q: s.Where(pgq.NotEq{"k": []int{}}), 108 | sql: "SELECT v FROM pgq_integration WHERE (TRUE)", 109 | rows: []string{"foo", "bar", "foo", "baz"}, 110 | }, 111 | { 112 | name: "klt3", 113 | q: s.Where(pgq.Lt{"k": 3}), 114 | sql: "SELECT v FROM pgq_integration WHERE k < $1", 115 | args: []any{3}, 116 | rows: []string{"foo", "foo"}, 117 | }, 118 | { 119 | name: "kgt3", 120 | q: s.Where(pgq.Gt{"k": 3}), 121 | sql: "SELECT v FROM pgq_integration WHERE k > $1", 122 | args: []any{3}, 123 | rows: []string{"baz"}, 124 | }, 125 | { 126 | name: "kgt1andlt4", 127 | q: s.Where(pgq.And{pgq.Gt{"k": 1}, pgq.Lt{"k": 4}}), 128 | sql: "SELECT v FROM pgq_integration WHERE (k > $1 AND k < $2)", 129 | args: []any{1, 4}, 130 | rows: []string{"bar", "foo"}, 131 | }, 132 | { 133 | name: "kgt3orlt2", 134 | q: s.Where(pgq.Or{pgq.Gt{"k": 3}, pgq.Lt{"k": 2}}), 135 | sql: "SELECT v FROM pgq_integration WHERE (k > $1 OR k < $2)", 136 | args: []any{3, 2}, 137 | rows: []string{"foo", "baz"}, 138 | }, 139 | } 140 | 141 | for _, tc := range testCases { 142 | tc := tc 143 | t.Run(tc.name, func(t *testing.T) { 144 | t.Parallel() 145 | sql, args, err := tc.q.SQL() 146 | if err != nil { 147 | t.Errorf("expected no error, got %v instead", err) 148 | } 149 | if sql != tc.sql { 150 | t.Errorf("expected %q, got %q instead", tc.sql, sql) 151 | } 152 | if !reflect.DeepEqual(args, tc.args) { 153 | t.Errorf("expected %v, got %v instead", tc.args, args) 154 | } 155 | 156 | var data []string 157 | rows, err := pool.Query(context.Background(), sql, args...) 158 | if err == nil { 159 | defer rows.Close() 160 | data, err = pgx.CollectRows(rows, pgx.RowTo[string]) 161 | } 162 | if err != nil { 163 | t.Errorf("expected no error, got %v instead", err) 164 | } 165 | 166 | if !reflect.DeepEqual(data, tc.rows) { 167 | t.Errorf("expected %v, got %v instead", tc.rows, data) 168 | } 169 | }) 170 | } 171 | } 172 | 173 | func TestValidQueries(t *testing.T) { 174 | t.Parallel() 175 | 176 | fsys, err := fs.Sub(mig, "migrations") 177 | if err != nil { 178 | t.Fatal(fsys) 179 | } 180 | migration := sqltest.New(t, sqltest.Options{ 181 | Force: *force, 182 | Files: fsys, 183 | }) 184 | pool := migration.Setup(context.Background(), "") 185 | 186 | type sqler interface { 187 | SQL() (sql string, args []interface{}, err error) 188 | } 189 | 190 | testCases := []struct { 191 | name string 192 | q sqler 193 | want string 194 | }{ 195 | { 196 | "select", 197 | func() sqler { 198 | caseStmt := pgq.Case("number"). 199 | When("1", "one"). 200 | When("2", "two"). 201 | Else(pgq.Expr("?", "big number")) 202 | 203 | return pgq.Select(). 204 | Column(caseStmt). 205 | From("atable") 206 | }(), 207 | "SELECT CASE number " + 208 | "WHEN 1 THEN one " + 209 | "WHEN 2 THEN two " + 210 | "ELSE $1 " + 211 | "END " + 212 | "FROM atable", 213 | }, 214 | { 215 | "select_with_alias", 216 | func() sqler { 217 | caseStmt := pgq.Case("? > ?", 10, 5). 218 | When("true", "'T'") 219 | 220 | return pgq.Select(). 221 | Column(pgq.Alias{ 222 | Expr: caseStmt, 223 | As: "complexCase", 224 | }). 225 | From("atable") 226 | }(), 227 | "SELECT (CASE $1 > $2 " + 228 | "WHEN true THEN 'T' " + 229 | "END) AS complexCase " + 230 | "FROM atable", 231 | }, 232 | { 233 | "select_with_case", 234 | func() sqler { 235 | caseStmt := pgq.Case(pgq.Expr("x = ?", true)). 236 | When("true", pgq.Expr("?", "it's true!")). 237 | Else("42") 238 | 239 | return pgq.Select().Column(caseStmt).From("atable") 240 | }(), 241 | "SELECT CASE x = $1 " + 242 | "WHEN true THEN $2 " + 243 | "ELSE 42 " + 244 | "END " + 245 | "FROM atable", 246 | }, 247 | { 248 | "select_with_case_and_alias", 249 | func() sqler { 250 | caseStmtNoval := pgq.Case(pgq.Expr("x = ?", true)). 251 | When("true", pgq.Expr("?", "it's true!")). 252 | Else("42") 253 | caseStmtExpr := pgq.Case(). 254 | When(pgq.Eq{"x": 0}, "'x is zero'"). 255 | When(pgq.Expr("x > ?", 1), pgq.Expr("CONCAT('x is greater than ', ?)", 2)) 256 | 257 | return pgq.Select(). 258 | Column(pgq.Alias{ 259 | Expr: caseStmtNoval, 260 | As: "case_noval", 261 | }). 262 | Column(pgq.Alias{ 263 | Expr: caseStmtExpr, 264 | As: "case_expr", 265 | }). 266 | From("atable") 267 | }(), 268 | "SELECT " + 269 | "(CASE x = $1 WHEN true THEN $2 ELSE 42 END) AS case_noval, " + 270 | "(CASE WHEN x = $3 THEN 'x is zero' WHEN x > $4 THEN CONCAT('x is greater than ', $5) END) AS case_expr " + 271 | "FROM atable", 272 | }, 273 | { 274 | "delete_where_multi", 275 | func() sqler { 276 | return pgq.Delete("test").Where("x = ? AND y = ?", 1, 2) 277 | }(), 278 | "DELETE FROM test WHERE x = $1 AND y = $2", 279 | }, 280 | { 281 | "delete_where_suffix", 282 | func() sqler { 283 | return pgq.Delete("test").Where("id=55").Suffix("RETURNING path") 284 | }(), 285 | "DELETE FROM test WHERE id=55 RETURNING path", 286 | }, 287 | { 288 | "insert_values", 289 | pgq.Insert("test").Values(1, 2), 290 | "INSERT INTO test VALUES ($1,$2)", 291 | }, 292 | { 293 | "insert_value", 294 | pgq.Insert("test").Values(1), 295 | "INSERT INTO test VALUES ($1)", 296 | }, 297 | { 298 | "insert_setmap", 299 | pgq.Insert("atable").SetMap(pgq.Eq{"field1": 1, "field2": 2, "field3": 3}), 300 | "INSERT INTO atable (field1,field2,field3) VALUES ($1,$2,$3)", 301 | }, 302 | { 303 | "insert_with_select", 304 | func() sqler { 305 | sb := pgq.Select("field1").From("table1").Where(pgq.Eq{"field1": 1}) 306 | return pgq.Insert("table2").Columns("field1").Select(sb) 307 | }(), 308 | "INSERT INTO table2 (field1) SELECT field1 FROM table1 WHERE field1 = $1", 309 | }, 310 | { 311 | "insert_with_returning", 312 | pgq.Insert("a"). 313 | Columns("b", "c"). 314 | Values(1, 2). 315 | Values(3, pgq.Expr("? + 1", 4)). 316 | Returning("abc"), 317 | "INSERT INTO a (b,c) VALUES ($1,$2),($3,$4 + 1) RETURNING abc", 318 | }, 319 | { 320 | "insert_with_returning_multi", 321 | pgq.Insert("a"). 322 | Columns("b", "c"). 323 | Values(1, 2). 324 | Values(3, pgq.Expr("? + 1", 4)). 325 | Returning("abc", "def"), 326 | "INSERT INTO a (b,c) VALUES ($1,$2),($3,$4 + 1) RETURNING abc, def", 327 | }, 328 | { 329 | "insert_with_returning_table_row", 330 | pgq.Insert("a"). 331 | Columns("b", "c"). 332 | Values(1, 2). 333 | Values(3, pgq.Expr("? + 1", 4)). 334 | ReturningSelect(pgq.Select("abc").From("atable"), "something"), 335 | "INSERT INTO a (b,c) VALUES ($1,$2),($3,$4 + 1) RETURNING (SELECT abc FROM atable) AS something", 336 | }, 337 | { 338 | "select_from_select", 339 | func() sqler { 340 | subQ := pgq.Select("c").From("d").Where(pgq.Eq{"i": 0}) 341 | return pgq.Select("a", "b").FromSelect(subQ, "subq") 342 | }(), 343 | "SELECT a, b FROM (SELECT c FROM d WHERE i = $1) AS subq", 344 | }, 345 | { 346 | "select_from_select_2", 347 | func() sqler { 348 | subQ := pgq.Select("c"). 349 | From("t"). 350 | Where(pgq.Gt{"c": 1}) 351 | return pgq.Select("c"). 352 | FromSelect(subQ, "subq"). 353 | Where(pgq.Lt{"c": 2}) 354 | }(), 355 | "SELECT c FROM (SELECT c FROM t WHERE c > $1) AS subq WHERE c < $2", 356 | }, 357 | { 358 | "select_where", 359 | pgq.Select("test").Where("x = ? AND y = ?"), 360 | "SELECT test WHERE x = $1 AND y = $2", 361 | }, 362 | { 363 | "select_from_join", 364 | pgq.Select("*").From("bar").Join("baz ON bar.foo = baz.foo"), 365 | "SELECT * FROM bar JOIN baz ON bar.foo = baz.foo", 366 | }, 367 | { 368 | "select_from_join_on", 369 | pgq.Select("*").From("bar").Join("baz ON bar.foo = baz.foo AND baz.foo = ?", 42), 370 | "SELECT * FROM bar JOIN baz ON bar.foo = baz.foo AND baz.foo = $1", 371 | }, 372 | { 373 | "select_from_join_select_on", 374 | func() sqler { 375 | nestedSelect := pgq.Select("*").From("baz").Where("foo = ?", 42) 376 | return pgq.Select("*").From("bar").JoinClause(nestedSelect.Prefix("JOIN (").Suffix(") r ON bar.foo = r.foo")) 377 | }(), 378 | "SELECT * FROM bar JOIN ( SELECT * FROM baz WHERE foo = $1 ) r ON bar.foo = r.foo", 379 | }, 380 | { 381 | "select_from_option", 382 | pgq.Select("*").From("foo").Options("DISTINCT"), 383 | "SELECT DISTINCT * FROM foo", 384 | }, 385 | { 386 | "select_from_remove_limit", 387 | pgq.Select("*").From("foo").Limit(10).RemoveLimit(), 388 | "SELECT * FROM foo", 389 | }, 390 | { 391 | "select_from_remove_offset", 392 | pgq.Select("*").From("foo").Offset(10).RemoveOffset(), 393 | "SELECT * FROM foo", 394 | }, 395 | { 396 | "select_with_nested_not_exists", 397 | func() sqler { 398 | nestedBuilder := pgq.Select("*").Prefix("NOT EXISTS ("). 399 | From("bar").Where("y = ?", 42).Suffix(")") 400 | return pgq.Select("*"). 401 | From("foo").Where("x = ?").Where(nestedBuilder) 402 | }(), 403 | "SELECT * FROM foo WHERE x = $1 AND NOT EXISTS ( SELECT * FROM bar WHERE y = $2 )", 404 | }, 405 | { 406 | "select_from_users", 407 | pgq.Select("*").From("users"), 408 | "SELECT * FROM users", 409 | }, 410 | { 411 | "select_from_users_where_where_nil", 412 | pgq.Select("*").From("users").Where(nil), 413 | "SELECT * FROM users", 414 | }, 415 | { 416 | "select_from_users_where_where_empty", 417 | pgq.Select("*").From("users").Where(""), 418 | "SELECT * FROM users", 419 | }, 420 | { 421 | "with_select_from_select", 422 | func() sqler { 423 | subquery := pgq.Select("a").Where("b = ?", 1) 424 | with := subquery.Prefix("WITH a AS (").Suffix(")") 425 | return pgq.Select("*"). 426 | PrefixExpr(with). 427 | FromSelect(subquery, "q"). 428 | Where("c = ?", 2) 429 | }(), 430 | "WITH a AS ( SELECT a WHERE b = $1 ) SELECT * FROM (SELECT a WHERE b = $2) AS q WHERE c = $3", 431 | }, 432 | { 433 | "select_where_exists_select", 434 | func() sqler { 435 | subquery := pgq.Select("a").Where(pgq.Eq{"b": 1}).Prefix("EXISTS(").Suffix(")") 436 | return pgq.Select("*"). 437 | Where(pgq.Or{subquery}). 438 | Where("c = ?", 2) 439 | }(), 440 | "SELECT * WHERE (EXISTS( SELECT a WHERE b = $1 )) AND c = $2", 441 | }, 442 | { 443 | "select_join_select_on_where", 444 | func() sqler { 445 | subquery := pgq.Select("a").Where(pgq.Eq{"b": 2}) 446 | 447 | return pgq.Select("t1.a"). 448 | From("t1"). 449 | Where(pgq.Eq{"a": 1}). 450 | JoinClause(subquery.Prefix("JOIN (").Suffix(") t2 ON (t1.a = t2.a)")) 451 | }(), 452 | "SELECT t1.a FROM t1 JOIN ( SELECT a WHERE b = $1 ) t2 ON (t1.a = t2.a) WHERE a = $2", 453 | }, 454 | { 455 | "select_fields_from_table", 456 | pgq.Select("id", "created", "first_name").From("users"), 457 | "SELECT id, created, first_name FROM users", 458 | }, 459 | { 460 | "select_field_and_count_from_table", 461 | pgq.Select("first_name", "count(*)").From("users"), 462 | "SELECT first_name, count(*) FROM users", 463 | }, 464 | { 465 | "select_field_and_count_from_table_as", 466 | pgq.Select("first_name", "count(*) as n_users").From("users"), 467 | "SELECT first_name, count(*) as n_users FROM users", 468 | }, 469 | { 470 | "select_fields_from_table_where", 471 | pgq.Select("id", "created", "first_name").From("users"). 472 | Where("company = ?", "abc"), 473 | "SELECT id, created, first_name FROM users WHERE company = $1", 474 | }, 475 | { 476 | "select_fields_from_table_where_map", 477 | pgq.Select("id", "created", "first_name").From("users"). 478 | Where(pgq.Eq{"company": 123}), 479 | "SELECT id, created, first_name FROM users WHERE company = $1", 480 | }, 481 | { 482 | "select_fields_from_table_where_map_gt_or_eq", 483 | pgq.Select("id", "created", "first_name").From("users"). 484 | Where(pgq.GtOrEq{"created": time.Now().AddDate(0, 0, -7)}), 485 | "SELECT id, created, first_name FROM users WHERE created >= $1", 486 | }, 487 | { 488 | "select_fields_where_multi_maps", 489 | func() sqler { 490 | return pgq.Select("id", "created", "first_name").From("users").Where(pgq.And{ 491 | pgq.GtOrEq{ 492 | "created": time.Now().AddDate(0, 0, -7), 493 | }, 494 | pgq.Eq{ 495 | "company": "whatever", 496 | }, 497 | }) 498 | }(), 499 | "SELECT id, created, first_name FROM users WHERE (created >= $1 AND company = $2)", 500 | }, 501 | { 502 | "select_fields_from_multi_where", 503 | func() sqler { 504 | return pgq.Select("id", "created", "first_name"). 505 | From("users"). 506 | Where("company = ?", "whatever"). 507 | Where(pgq.GtOrEq{ 508 | "created": time.Now().AddDate(0, 0, -7), 509 | }) 510 | }(), 511 | "SELECT id, created, first_name FROM users WHERE company = $1 AND created >= $2", 512 | }, 513 | { 514 | "multi_select_complex", 515 | func() sqler { 516 | usersByCompany := pgq.Select("company", "count(*) as n_users").From("users").GroupBy("company") 517 | return pgq.Select("company.id", "company.name", "users_by_company.n_users"). 518 | FromSelect(usersByCompany, "users_by_company"). 519 | Join("company on company.id = users_by_company.company") 520 | }(), 521 | "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", 522 | }, 523 | { 524 | "select_columns_from", 525 | pgq.Select("id").Columns("created", "first_name").From("users"), 526 | "SELECT id, created, first_name FROM users", 527 | }, 528 | { 529 | "select_columns", 530 | pgq.Select("id").Columns("created").From("users").Columns("first_name"), 531 | "SELECT id, created, first_name FROM users", 532 | }, 533 | { 534 | "select_remove_column", 535 | func() sqler { 536 | query := pgq.Select("id"). 537 | From("users"). 538 | RemoveColumns() 539 | return query.Columns("name") 540 | }(), 541 | "SELECT name FROM users", 542 | }, 543 | { 544 | "select_table_where", 545 | pgq.Select("test").Where("x = ?", 1), 546 | "SELECT test WHERE x = $1", 547 | }, 548 | { 549 | "update_where_set", 550 | pgq.Update("foo").Where("x = ?", "z").Set("a", "b"), 551 | "UPDATE foo SET a = $1 WHERE x = $2", 552 | }, 553 | { 554 | "delete_where", 555 | pgq.Delete("foo").Where("x = ?", "z"), 556 | "DELETE FROM foo WHERE x = $1", 557 | }, 558 | { 559 | "update_set_map", 560 | pgq.Update("test").SetMap(pgq.Eq{"x": 1, "y": 2}), 561 | "UPDATE test SET x = $1, y = $2", 562 | }, 563 | } 564 | for _, tc := range testCases { 565 | tc := tc 566 | t.Run(tc.name, func(t *testing.T) { 567 | t.Parallel() 568 | 569 | sql, _, err := tc.q.SQL() 570 | if err != nil { 571 | t.Errorf("expected no error, got %v instead", err) 572 | } 573 | if sql != tc.want { 574 | t.Errorf("expected SQL to be %q, got %q instead", tc.want, sql) 575 | } 576 | rows, err := pool.Query(context.Background(), fmt.Sprintf(syntaxCheckTemplate, sql)) 577 | if err == nil { 578 | defer rows.Close() 579 | // Forcing reading rows to catch query errors. 580 | _, err = pgx.CollectRows(rows, pgx.RowToMap) 581 | } 582 | if err != nil { 583 | t.Errorf("expected no error, got %v instead for query %q", err, sql) 584 | } 585 | }) 586 | } 587 | } 588 | 589 | // syntaxCheckTemplate wraps the query in a construction that returns early. 590 | // This way, we can check the query for correctness without executing it. 591 | // See https://stackoverflow.com/questions/8271606/postgresql-syntax-check-without-running-the-query 592 | const syntaxCheckTemplate = `DO $SYNTAX_CHECK$ BEGIN RETURN; %s; END; $SYNTAX_CHECK$;` 593 | -------------------------------------------------------------------------------- /integration/migrations/001_initial_schema.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE pgq_integration ( k INT, v TEXT ); 2 | INSERT INTO pgq_integration VALUES (1, 'foo'), (3, 'bar'), (2, 'foo'), (4, 'baz'); 3 | -------------------------------------------------------------------------------- /pgq.go: -------------------------------------------------------------------------------- 1 | // package pgq provides a fluent SQL generator. 2 | // 3 | // See https://github.com/Masterminds/pgq for examples. 4 | package pgq 5 | 6 | import ( 7 | "bytes" 8 | "fmt" 9 | "io" 10 | "strings" 11 | ) 12 | 13 | // SQLizer is the interface that wraps the SQL method. 14 | // 15 | // SQL() returns a SQL representation of the SQLizer, along with a slice of arguments. 16 | // If the query cannot be created, it returns an error. 17 | type SQLizer interface { 18 | SQL() (string, []any, error) 19 | } 20 | 21 | // rawSQLizer is expected to do what SQLizer does, but without finalizing placeholders. 22 | // This is useful for nested queries. 23 | type rawSQLizer interface { 24 | unfinalizedSQL() (string, []any, error) 25 | } 26 | 27 | // Debug calls SQL on s and shows the approximate SQL to be executed 28 | // 29 | // If SQL returns an error, the result of this method will look like: 30 | // "[SQL error: %s]" or "[DebugSQLizer error: %s]" 31 | // 32 | // IMPORTANT: As its name suggests, this function should only be used for 33 | // debugging. While the string result *might* be valid SQL, this function does 34 | // not try very hard to ensure it. Additionally, executing the output of this 35 | // function with any untrusted user input is certainly insecure. 36 | func Debug(s SQLizer) string { 37 | sql, args, err := s.SQL() 38 | if err != nil { 39 | return fmt.Sprintf("[SQL error: %s]", err) 40 | } 41 | 42 | buf := &bytes.Buffer{} 43 | i := 0 44 | for { 45 | p := strings.Index(sql, "?") 46 | if p == -1 { 47 | break 48 | } 49 | if len(sql[p:]) > 1 && sql[p:p+2] == "??" { // escape ?? => ? 50 | buf.WriteString(sql[:p]) 51 | buf.WriteString("?") 52 | if len(sql[p:]) == 1 { 53 | break 54 | } 55 | sql = sql[p+2:] 56 | } else { 57 | if i+1 > len(args) { 58 | return fmt.Sprintf( 59 | "[DebugSQLizer error: too many placeholders in %#v for %d args]", 60 | sql, len(args)) 61 | } 62 | buf.WriteString(sql[:p]) 63 | fmt.Fprintf(buf, "'%v'", args[i]) 64 | // advance our sql string "cursor" beyond the arg we placed 65 | sql = sql[p+1:] 66 | i++ 67 | } 68 | } 69 | if i < len(args) { 70 | return fmt.Sprintf( 71 | "[DebugSQLizer error: not enough placeholders in %#v for %d args]", 72 | sql, len(args)) 73 | } 74 | // "append" any remaning sql that won't need interpolating 75 | buf.WriteString(sql) 76 | return buf.String() 77 | } 78 | 79 | type part struct { 80 | pred any 81 | args []any 82 | } 83 | 84 | func newPart(pred any, args ...any) SQLizer { 85 | return &part{pred, args} 86 | } 87 | 88 | func (p part) SQL() (sql string, args []any, err error) { 89 | switch pred := p.pred.(type) { 90 | case nil: 91 | // no-op 92 | case SQLizer: 93 | sql, args, err = nestedSQL(pred) 94 | case string: 95 | sql = pred 96 | args = p.args 97 | default: 98 | err = fmt.Errorf("expected string or SQLizer, not %T", pred) 99 | } 100 | return 101 | } 102 | 103 | func nestedSQL(s SQLizer) (string, []any, error) { 104 | if raw, ok := s.(rawSQLizer); ok { 105 | return raw.unfinalizedSQL() 106 | } else { 107 | return s.SQL() 108 | } 109 | } 110 | 111 | func appendSQL(parts []SQLizer, w io.Writer, sep string, args []any) ([]any, error) { 112 | for i, p := range parts { 113 | partSQL, partArgs, err := nestedSQL(p) 114 | if err != nil { 115 | return nil, err 116 | } else if partSQL == "" { 117 | continue 118 | } 119 | 120 | if i > 0 { 121 | _, err := io.WriteString(w, sep) 122 | if err != nil { 123 | return nil, err 124 | } 125 | } 126 | 127 | _, err = io.WriteString(w, partSQL) 128 | if err != nil { 129 | return nil, err 130 | } 131 | args = append(args, partArgs...) 132 | } 133 | return args, nil 134 | } 135 | -------------------------------------------------------------------------------- /pgq_test.go: -------------------------------------------------------------------------------- 1 | package pgq 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestDebug(t *testing.T) { 8 | t.Parallel() 9 | sqlizer := Expr("x = ? AND y = ? AND z = '??'", 1, "text") 10 | expectedDebug := "x = '1' AND y = 'text' AND z = '?'" 11 | if got := Debug(sqlizer); got != expectedDebug { 12 | t.Errorf("expected %q, got %q instead", got, expectedDebug) 13 | } 14 | } 15 | 16 | func TestDebugSQLizerErrors(t *testing.T) { 17 | t.Parallel() 18 | var errorMessages = []struct { 19 | s SQLizer 20 | want string 21 | }{ 22 | // Not enough placeholders 23 | { 24 | s: Expr("x = ?", 1, 2), 25 | want: "[DebugSQLizer error: not enough placeholders in \"\" for 2 args]", 26 | }, 27 | // Too many placeholders 28 | { 29 | s: Expr("x = ? AND y = ?", 1), 30 | want: "[DebugSQLizer error: too many placeholders in \" AND y = ?\" for 1 args]", 31 | }, 32 | // Cannot use nil values with Lt 33 | { 34 | s: Lt{"x": nil}, 35 | want: "[SQL error: cannot use null with less than or greater than operators]", 36 | }, 37 | } 38 | 39 | for _, m := range errorMessages { 40 | if msg := Debug(m.s); msg != m.want { 41 | t.Errorf("expected %q, got error message = %q instead", m.want, msg) 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /placeholder.go: -------------------------------------------------------------------------------- 1 | package pgq 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "strings" 7 | ) 8 | 9 | // placeholder takes a SQL statement and replaces each question mark 10 | // placeholder with a (possibly different) SQL placeholder. 11 | type placeholder func(sql string) (string, error) 12 | 13 | // questionPlaceholder just leaves question marks ("?") as placeholders. 14 | func questionPlaceholder(sql string) (string, error) { 15 | return sql, nil 16 | } 17 | 18 | // Placeholders returns a string with count ? placeholders joined with commas. 19 | func Placeholders(count int) string { 20 | if count < 1 { 21 | return "" 22 | } 23 | 24 | return strings.Repeat(",?", count)[1:] 25 | } 26 | 27 | // dollarPlaceholder replaces question marks ("?") placeholders with 28 | // dollar-prefixed positional placeholders (e.g. $1, $2, $3). 29 | func dollarPlaceholder(sql string) (string, error) { 30 | buf := &bytes.Buffer{} 31 | i := 0 32 | for { 33 | p := strings.Index(sql, "?") 34 | if p == -1 { 35 | break 36 | } 37 | 38 | if len(sql[p:]) > 1 && sql[p:p+2] == "??" { // escape ?? => ? 39 | buf.WriteString(sql[:p]) 40 | buf.WriteString("?") 41 | if len(sql[p:]) == 1 { 42 | break 43 | } 44 | sql = sql[p+2:] 45 | } else { 46 | i++ 47 | buf.WriteString(sql[:p]) 48 | fmt.Fprintf(buf, "$%d", i) 49 | sql = sql[p+1:] 50 | } 51 | } 52 | 53 | buf.WriteString(sql) 54 | return buf.String(), nil 55 | } 56 | -------------------------------------------------------------------------------- /placeholder_test.go: -------------------------------------------------------------------------------- 1 | package pgq 2 | 3 | import ( 4 | "strings" 5 | "testing" 6 | ) 7 | 8 | func TestDollar(t *testing.T) { 9 | t.Parallel() 10 | sql := "x = ? AND y = ?" 11 | s, err := dollarPlaceholder(sql) 12 | if err != nil { 13 | t.Errorf("unexpected error: %v", err) 14 | } 15 | if want := "x = $1 AND y = $2"; s != want { 16 | t.Errorf("expected %q, got %q instead", want, s) 17 | } 18 | } 19 | 20 | func TestPlaceholders(t *testing.T) { 21 | t.Parallel() 22 | got := Placeholders(2) 23 | if want := "?,?"; got != want { 24 | t.Errorf("expected %q, got %q instead", want, got) 25 | } 26 | } 27 | 28 | func TestEscapeDollar(t *testing.T) { 29 | t.Parallel() 30 | sql := "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ??| array['?'] AND enabled = ?" 31 | s, err := dollarPlaceholder(sql) 32 | if err != nil { 33 | t.Errorf("unexpected error: %v", err) 34 | } 35 | want := "SELECT uuid, \"data\" #> '{tags}' AS tags FROM nodes WHERE \"data\" -> 'tags' ?| array['$1'] AND enabled = $2" 36 | if s != want { 37 | t.Errorf("expected %q, got %q instead", want, s) 38 | } 39 | } 40 | 41 | func BenchmarkPlaceholdersArray(b *testing.B) { 42 | var count = b.N 43 | placeholders := make([]string, count) 44 | for i := 0; i < count; i++ { 45 | placeholders[i] = "?" 46 | } 47 | var _ = strings.Join(placeholders, ",") 48 | } 49 | 50 | func BenchmarkPlaceholdersStrings(b *testing.B) { 51 | Placeholders(b.N) 52 | } 53 | -------------------------------------------------------------------------------- /scripts/ci-lint-fmt.sh: -------------------------------------------------------------------------------- 1 | # Adapted from @aminueza's go-github-action/fmt/fmt.sh 2 | # Reference: https://github.com/aminueza/go-github-action/blob/master/fmt/fmt.sh 3 | # Execute fmt tool, resolve and emit each unformatted file 4 | UNFORMATTED_FILES=$(go fmt $(go list ./... | grep -v /vendor/)) 5 | 6 | if [ -n "$UNFORMATTED_FILES" ]; then 7 | echo '::error::The following files are not properly formatted:' 8 | echo "$UNFORMATTED_FILES" | while read -r LINE; do 9 | FILE=$(realpath --relative-base="." "$LINE") 10 | echo "::error:: $FILE" 11 | done 12 | exit 1 13 | fi 14 | -------------------------------------------------------------------------------- /scripts/ci-lint-install.sh: -------------------------------------------------------------------------------- 1 | source scripts/lib.sh 2 | 3 | ensure_go_binary honnef.co/go/tools/cmd/staticcheck 4 | -------------------------------------------------------------------------------- /scripts/ci-lint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -euo pipefail 3 | IFS=$'\n\t' 4 | 5 | # Static analysis scripts 6 | cd $(dirname $0)/.. 7 | 8 | source scripts/ci-lint-install.sh 9 | source scripts/ci-lint-fmt.sh 10 | 11 | set -x 12 | go vet ./... 13 | staticcheck ./... 14 | -------------------------------------------------------------------------------- /scripts/coverage.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Modified version of chef-runner/script/coverage 4 | # Copyright 2004 Mathias Lafeldt 5 | # Apache License 2.0 6 | # Source: https://github.com/mlafeldt/chef-runner/blob/v0.7.0/script/coverage 7 | 8 | # Generate test coverage statistics for Go packages. 9 | # 10 | # Works around the fact that `go test -coverprofile` currently does not work 11 | # with multiple packages, see https://code.google.com/p/go/issues/detail?id=6909 12 | # 13 | # Usage: script/coverage [--html|--coveralls] 14 | # 15 | # --html Additionally create HTML report and open it in browser 16 | # --coveralls Push coverage statistics to coveralls.io 17 | # 18 | # Changes: directories ending in .go used to fail 19 | 20 | set -e 21 | 22 | workdir=.cover 23 | profile="$workdir/cover.out" 24 | mode=count 25 | 26 | generate_cover_data() { 27 | rm -rf "$workdir" 28 | mkdir "$workdir" 29 | 30 | for pkg in "$@"; do 31 | f="$workdir/$(echo $pkg | tr / -).cover" 32 | go test -covermode="$mode" -coverprofile="$f" "$pkg/" 33 | done 34 | 35 | echo "mode: $mode" >"$profile" 36 | grep -h -v "^mode:" "$workdir"/*.cover >>"$profile" 37 | } 38 | 39 | show_cover_report() { 40 | go tool cover -${1}="$profile" 41 | } 42 | 43 | push_to_coveralls() { 44 | echo "Pushing coverage statistics to coveralls.io" 45 | goveralls -coverprofile="$profile" 46 | } 47 | 48 | generate_cover_data $(go list ./...) 49 | show_cover_report func 50 | case "$1" in 51 | "") 52 | ;; 53 | --html) 54 | show_cover_report html ;; 55 | --coveralls) 56 | push_to_coveralls ;; 57 | *) 58 | echo >&2 "error: invalid option: $1"; exit 1 ;; 59 | esac 60 | -------------------------------------------------------------------------------- /scripts/lib.sh: -------------------------------------------------------------------------------- 1 | # ensure_go_binary verifies that a binary exists in $PATH corresponding to the 2 | # given go-gettable URI. If no such binary exists, it is fetched via `go get`. 3 | # Reference: https://github.com/golang/pkgsite/blob/65d33554b34b666d37b22bed7de136b562d5dba8/all.bash#L93-L103 4 | # Copyright 2019 The Go Authors. 5 | ensure_go_binary() { 6 | local binary=$(basename $1) 7 | if ! [ -x "$(command -v $binary)" ]; then 8 | echo "Installing: $1" 9 | # Run in a subshell for convenience, so that we don't have to worry about 10 | # our PWD. 11 | (set -x; cd && go install $1@latest) 12 | fi 13 | } 14 | -------------------------------------------------------------------------------- /select.go: -------------------------------------------------------------------------------- 1 | package pgq 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "strings" 7 | ) 8 | 9 | // SelectBuilder builds SQL SELECT statements. 10 | type SelectBuilder struct { 11 | placeholder placeholder 12 | prefixes []SQLizer 13 | options []string 14 | columns []SQLizer 15 | from SQLizer 16 | joins []SQLizer 17 | whereParts []SQLizer 18 | groupBys []string 19 | havingParts []SQLizer 20 | orderByParts []SQLizer 21 | limit string 22 | offset string 23 | suffixes []SQLizer 24 | } 25 | 26 | // SQL builds the query into a SQL string and bound args. 27 | func (b SelectBuilder) SQL() (sqlStr string, args []any, err error) { 28 | sqlStr, args, err = b.unfinalizedSQL() 29 | if err != nil { 30 | return 31 | } 32 | 33 | f := b.placeholder 34 | if f == nil { 35 | f = dollarPlaceholder 36 | } 37 | sqlStr, err = f(sqlStr) 38 | return 39 | } 40 | 41 | func (b SelectBuilder) unfinalizedSQL() (sqlStr string, args []any, err error) { 42 | if len(b.columns) == 0 { 43 | err = fmt.Errorf("select statements must have at least one result column") 44 | return 45 | } 46 | 47 | sql := &bytes.Buffer{} 48 | 49 | if len(b.prefixes) > 0 { 50 | args, err = appendSQL(b.prefixes, sql, " ", args) 51 | if err != nil { 52 | return 53 | } 54 | 55 | sql.WriteString(" ") 56 | } 57 | 58 | sql.WriteString("SELECT ") 59 | 60 | if len(b.options) > 0 { 61 | sql.WriteString(strings.Join(b.options, " ")) 62 | sql.WriteString(" ") 63 | } 64 | 65 | if len(b.columns) > 0 { 66 | args, err = appendSQL(b.columns, sql, ", ", args) 67 | if err != nil { 68 | return 69 | } 70 | } 71 | 72 | if b.from != nil { 73 | sql.WriteString(" FROM ") 74 | args, err = appendSQL([]SQLizer{b.from}, sql, "", args) 75 | if err != nil { 76 | return 77 | } 78 | } 79 | 80 | if len(b.joins) > 0 { 81 | sql.WriteString(" ") 82 | args, err = appendSQL(b.joins, sql, " ", args) 83 | if err != nil { 84 | return 85 | } 86 | } 87 | 88 | if len(b.whereParts) > 0 { 89 | sql.WriteString(" WHERE ") 90 | args, err = appendSQL(b.whereParts, sql, " AND ", args) 91 | if err != nil { 92 | return 93 | } 94 | } 95 | 96 | if len(b.groupBys) > 0 { 97 | sql.WriteString(" GROUP BY ") 98 | sql.WriteString(strings.Join(b.groupBys, ", ")) 99 | } 100 | 101 | if len(b.havingParts) > 0 { 102 | sql.WriteString(" HAVING ") 103 | args, err = appendSQL(b.havingParts, sql, " AND ", args) 104 | if err != nil { 105 | return 106 | } 107 | } 108 | 109 | if len(b.orderByParts) > 0 { 110 | sql.WriteString(" ORDER BY ") 111 | args, err = appendSQL(b.orderByParts, sql, ", ", args) 112 | if err != nil { 113 | return 114 | } 115 | } 116 | 117 | if b.limit != "" { 118 | sql.WriteString(" LIMIT ") 119 | sql.WriteString(b.limit) 120 | } 121 | 122 | if b.offset != "" { 123 | sql.WriteString(" OFFSET ") 124 | sql.WriteString(b.offset) 125 | } 126 | 127 | if len(b.suffixes) > 0 { 128 | sql.WriteString(" ") 129 | 130 | args, err = appendSQL(b.suffixes, sql, " ", args) 131 | if err != nil { 132 | return 133 | } 134 | } 135 | 136 | sqlStr = sql.String() 137 | return 138 | } 139 | 140 | // MustSQL builds the query into a SQL string and bound args. 141 | // It panics if there are any errors. 142 | func (b SelectBuilder) MustSQL() (string, []any) { 143 | sql, args, err := b.SQL() 144 | if err != nil { 145 | panic(err) 146 | } 147 | return sql, args 148 | } 149 | 150 | // Prefix adds an expression to the beginning of the query 151 | func (b SelectBuilder) Prefix(sql string, args ...any) SelectBuilder { 152 | return b.PrefixExpr(Expr(sql, args...)) 153 | } 154 | 155 | // PrefixExpr adds an expression to the very beginning of the query 156 | func (b SelectBuilder) PrefixExpr(expr SQLizer) SelectBuilder { 157 | b.prefixes = append(b.prefixes, expr) 158 | return b 159 | } 160 | 161 | // Distinct adds a DISTINCT clause to the query. 162 | func (b SelectBuilder) Distinct() SelectBuilder { 163 | return b.Options("DISTINCT") 164 | } 165 | 166 | // Options adds select option to the query 167 | func (b SelectBuilder) Options(options ...string) SelectBuilder { 168 | b.options = append(b.options, options...) 169 | return b 170 | } 171 | 172 | // Columns adds result columns to the query. 173 | func (b SelectBuilder) Columns(columns ...string) SelectBuilder { 174 | parts := make([]SQLizer, 0, len(columns)) 175 | for _, str := range columns { 176 | parts = append(parts, newPart(str)) 177 | } 178 | b.columns = append(b.columns, parts...) 179 | return b 180 | } 181 | 182 | // RemoveColumns remove all columns from query. 183 | // Must add a new column with Column or Columns methods, otherwise 184 | // return a error. 185 | func (b SelectBuilder) RemoveColumns() SelectBuilder { 186 | b.columns = nil 187 | return b 188 | } 189 | 190 | // Column adds a result column to the query. 191 | // Unlike Columns, Column accepts args which will be bound to placeholders in 192 | // the columns string, for example: 193 | // 194 | // Column("IF(col IN ("+pgq.Placeholders(3)+"), 1, 0) as col", 1, 2, 3) 195 | func (b SelectBuilder) Column(column any, args ...any) SelectBuilder { 196 | b.columns = append(b.columns, newPart(column, args...)) 197 | return b 198 | } 199 | 200 | // From sets the FROM clause of the query. 201 | func (b SelectBuilder) From(from string) SelectBuilder { 202 | b.from = newPart(from) 203 | return b 204 | } 205 | 206 | // FromSelect sets a subquery into the FROM clause of the query. 207 | func (b SelectBuilder) FromSelect(from SelectBuilder, alias string) SelectBuilder { 208 | // Prevent misnumbered parameters in nested selects 209 | // See https://github.com/Masterminds/squirrel/issues/183 210 | from.placeholder = questionPlaceholder 211 | b.from = Alias{ 212 | Expr: from, 213 | As: alias, 214 | } 215 | return b 216 | } 217 | 218 | // JoinClause adds a join clause to the query. 219 | func (b SelectBuilder) JoinClause(pred any, args ...any) SelectBuilder { 220 | b.joins = append(b.joins, newPart(pred, args...)) 221 | return b 222 | } 223 | 224 | // Join adds a JOIN clause to the query. 225 | func (b SelectBuilder) Join(join string, rest ...any) SelectBuilder { 226 | return b.JoinClause("JOIN "+join, rest...) 227 | } 228 | 229 | // LeftJoin adds a LEFT JOIN clause to the query. 230 | func (b SelectBuilder) LeftJoin(join string, rest ...any) SelectBuilder { 231 | return b.JoinClause("LEFT JOIN "+join, rest...) 232 | } 233 | 234 | // RightJoin adds a RIGHT JOIN clause to the query. 235 | func (b SelectBuilder) RightJoin(join string, rest ...any) SelectBuilder { 236 | return b.JoinClause("RIGHT JOIN "+join, rest...) 237 | } 238 | 239 | // InnerJoin adds a INNER JOIN clause to the query. 240 | func (b SelectBuilder) InnerJoin(join string, rest ...any) SelectBuilder { 241 | return b.JoinClause("INNER JOIN "+join, rest...) 242 | } 243 | 244 | // CrossJoin adds a CROSS JOIN clause to the query. 245 | func (b SelectBuilder) CrossJoin(join string, rest ...any) SelectBuilder { 246 | return b.JoinClause("CROSS JOIN "+join, rest...) 247 | } 248 | 249 | // Where adds an expression to the WHERE clause of the query. 250 | // 251 | // Expressions are ANDed together in the generated SQL. 252 | // 253 | // Where accepts several types for its pred argument: 254 | // 255 | // nil OR "" - ignored. 256 | // 257 | // string - SQL expression. 258 | // If the expression has SQL placeholders then a set of arguments must be passed 259 | // as well, one for each placeholder. 260 | // 261 | // map[string]any OR Eq - map of SQL expressions to values. Each key is 262 | // transformed into an expression like " = ?", with the corresponding value 263 | // bound to the placeholder. If the value is nil, the expression will be " 264 | // IS NULL". If the value is an array or slice, the expression will be " = ANY 265 | // (?)". These expressions 266 | // are ANDed together. 267 | // 268 | // Where will panic if pred isn't any of the above types. 269 | func (b SelectBuilder) Where(pred any, args ...any) SelectBuilder { 270 | if pred == nil || pred == "" { 271 | return b 272 | } 273 | b.whereParts = append(b.whereParts, newWherePart(pred, args...)) 274 | return b 275 | } 276 | 277 | // GroupBy adds GROUP BY expressions to the query. 278 | func (b SelectBuilder) GroupBy(groupBys ...string) SelectBuilder { 279 | b.groupBys = append(b.groupBys, groupBys...) 280 | return b 281 | } 282 | 283 | // Having adds an expression to the HAVING clause of the query. 284 | // 285 | // See Where. 286 | func (b SelectBuilder) Having(pred any, rest ...any) SelectBuilder { 287 | b.havingParts = append(b.havingParts, newWherePart(pred, rest...)) 288 | return b 289 | } 290 | 291 | // OrderByClause adds ORDER BY clause to the query. 292 | func (b SelectBuilder) OrderByClause(pred any, args ...any) SelectBuilder { 293 | b.orderByParts = append(b.orderByParts, newPart(pred, args...)) 294 | return b 295 | } 296 | 297 | // OrderBy adds ORDER BY expressions to the query. 298 | func (b SelectBuilder) OrderBy(orderBys ...string) SelectBuilder { 299 | for _, orderBy := range orderBys { 300 | b = b.OrderByClause(orderBy) 301 | } 302 | 303 | return b 304 | } 305 | 306 | // RemoveOrderBy removes ORDER BY clause. 307 | func (b SelectBuilder) RemoveOrderBy() SelectBuilder { 308 | b.orderByParts = nil 309 | return b 310 | } 311 | 312 | // Limit sets a LIMIT clause on the query. 313 | func (b SelectBuilder) Limit(limit uint64) SelectBuilder { 314 | b.limit = fmt.Sprintf("%d", limit) 315 | return b 316 | } 317 | 318 | // Limit ALL allows to access all records with limit 319 | func (b SelectBuilder) RemoveLimit() SelectBuilder { 320 | b.limit = "" 321 | return b 322 | } 323 | 324 | // Offset sets a OFFSET clause on the query. 325 | func (b SelectBuilder) Offset(offset uint64) SelectBuilder { 326 | b.offset = fmt.Sprintf("%d", offset) 327 | return b 328 | } 329 | 330 | // RemoveOffset removes OFFSET clause. 331 | func (b SelectBuilder) RemoveOffset() SelectBuilder { 332 | b.offset = "" 333 | return b 334 | } 335 | 336 | // Suffix adds an expression to the end of the query 337 | func (b SelectBuilder) Suffix(sql string, args ...any) SelectBuilder { 338 | return b.SuffixExpr(Expr(sql, args...)) 339 | } 340 | 341 | // SuffixExpr adds an expression to the end of the query 342 | func (b SelectBuilder) SuffixExpr(expr SQLizer) SelectBuilder { 343 | b.suffixes = append(b.suffixes, expr) 344 | return b 345 | } 346 | -------------------------------------------------------------------------------- /select_test.go: -------------------------------------------------------------------------------- 1 | package pgq 2 | 3 | import ( 4 | "fmt" 5 | "reflect" 6 | "testing" 7 | "time" 8 | ) 9 | 10 | func TestSelectBuilderSQL(t *testing.T) { 11 | t.Parallel() 12 | subQ := Select("aa", "bb").From("dd") 13 | b := Select("a", "b"). 14 | Prefix("WITH prefix AS ?", 0). 15 | Distinct(). 16 | Columns("c"). 17 | Column("IF(d IN ("+Placeholders(3)+"), 1, 0) as stat_column", 1, 2, 3). 18 | Column(Expr("a > ?", 100)). 19 | Column(Alias{ 20 | Expr: Eq{"b": []int{101, 102, 103}}, 21 | As: "b_alias", 22 | }). 23 | Column(Alias{ 24 | Expr: subQ, 25 | As: "subq", 26 | }). 27 | From("e"). 28 | JoinClause("CROSS JOIN j1"). 29 | Join("j2"). 30 | LeftJoin("j3"). 31 | RightJoin("j4"). 32 | InnerJoin("j5"). 33 | CrossJoin("j6"). 34 | Where("f = ?", 4). 35 | Where(Eq{"g": 5}). 36 | Where(map[string]any{"h": 6}). 37 | Where(Eq{"i": []int{7, 8, 9}}). 38 | Where(Or{Expr("j = ?", 10), And{Eq{"k": 11}, Expr("true")}}). 39 | GroupBy("l"). 40 | Having("m = n"). 41 | OrderBy("a ASC"). 42 | RemoveOrderBy(). 43 | OrderByClause("? DESC", 1). 44 | OrderBy("o ASC", "p DESC"). 45 | Limit(12). 46 | Offset(13). 47 | Suffix("FETCH FIRST ? ROWS ONLY", 14) 48 | 49 | sql, args, err := b.SQL() 50 | if err != nil { 51 | t.Errorf("unexpected error: %v", err) 52 | } 53 | 54 | want := 55 | "WITH prefix AS $1 " + 56 | "SELECT DISTINCT a, b, c, IF(d IN ($2,$3,$4), 1, 0) as stat_column, a > $5, " + 57 | "(b = ANY ($6)) AS b_alias, " + 58 | "(SELECT aa, bb FROM dd) AS subq " + 59 | "FROM e " + 60 | "CROSS JOIN j1 JOIN j2 LEFT JOIN j3 RIGHT JOIN j4 INNER JOIN j5 CROSS JOIN j6 " + 61 | "WHERE f = $7 AND g = $8 AND h = $9 AND i = ANY ($10) AND (j = $11 OR (k = $12 AND true)) " + 62 | "GROUP BY l HAVING m = n ORDER BY $13 DESC, o ASC, p DESC LIMIT 12 OFFSET 13 " + 63 | "FETCH FIRST $14 ROWS ONLY" 64 | if want != sql { 65 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 66 | } 67 | 68 | expectedArgs := []any{0, 1, 2, 3, 100, []int{101, 102, 103}, 4, 5, 6, []int{7, 8, 9}, 10, 11, 1, 14} 69 | if !reflect.DeepEqual(expectedArgs, args) { 70 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 71 | } 72 | } 73 | 74 | func TestSelectBuilderFromSelect(t *testing.T) { 75 | t.Parallel() 76 | subQ := Select("c").From("d").Where(Eq{"i": 0}) 77 | b := Select("a", "b").FromSelect(subQ, "subq") 78 | sql, args, err := b.SQL() 79 | if err != nil { 80 | t.Errorf("unexpected error: %v", err) 81 | } 82 | 83 | want := "SELECT a, b FROM (SELECT c FROM d WHERE i = $1) AS subq" 84 | if want != sql { 85 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 86 | } 87 | 88 | expectedArgs := []any{0} 89 | if !reflect.DeepEqual(expectedArgs, args) { 90 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 91 | } 92 | } 93 | 94 | func TestSelectBuilderFromSelectNestedDollarPlaceholders(t *testing.T) { 95 | t.Parallel() 96 | subQ := Select("c"). 97 | From("t"). 98 | Where(Gt{"c": 1}) 99 | b := Select("c"). 100 | FromSelect(subQ, "subq"). 101 | Where(Lt{"c": 2}) 102 | sql, args, err := b.SQL() 103 | if err != nil { 104 | t.Errorf("unexpected error: %v", err) 105 | } 106 | 107 | want := "SELECT c FROM (SELECT c FROM t WHERE c > $1) AS subq WHERE c < $2" 108 | if want != sql { 109 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 110 | } 111 | 112 | expectedArgs := []any{1, 2} 113 | if !reflect.DeepEqual(expectedArgs, args) { 114 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 115 | } 116 | } 117 | 118 | func TestSelectBuilderSQLErr(t *testing.T) { 119 | t.Parallel() 120 | _, _, err := Select().From("x").SQL() 121 | 122 | want := "select statements must have at least one result column" 123 | if err.Error() != want { 124 | t.Errorf("expected error to be %q, got %q instead", want, err) 125 | } 126 | } 127 | 128 | func TestSelectBuilderPlaceholders(t *testing.T) { 129 | t.Parallel() 130 | b := Select("test").Where("x = ? AND y = ?") 131 | 132 | sql, _, err := b.SQL() 133 | if err != nil { 134 | t.Errorf("unexpected error: %v", err) 135 | } 136 | if want := "SELECT test WHERE x = $1 AND y = $2"; sql != want { 137 | t.Errorf("expected %q, got %q instead", want, sql) 138 | } 139 | } 140 | 141 | func TestSelectBuilderSimpleJoin(t *testing.T) { 142 | t.Parallel() 143 | want := "SELECT * FROM bar JOIN baz ON bar.foo = baz.foo" 144 | expectedArgs := []any(nil) 145 | 146 | b := Select("*").From("bar").Join("baz ON bar.foo = baz.foo") 147 | 148 | sql, args, err := b.SQL() 149 | if err != nil { 150 | t.Errorf("unexpected error: %v", err) 151 | } 152 | 153 | if want != sql { 154 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 155 | } 156 | if !reflect.DeepEqual(args, expectedArgs) { 157 | t.Errorf("expected %v, got %v instead", expectedArgs, args) 158 | } 159 | } 160 | 161 | func TestSelectBuilderParamJoin(t *testing.T) { 162 | t.Parallel() 163 | want := "SELECT * FROM bar JOIN baz ON bar.foo = baz.foo AND baz.foo = $1" 164 | expectedArgs := []any{42} 165 | 166 | b := Select("*").From("bar").Join("baz ON bar.foo = baz.foo AND baz.foo = ?", 42) 167 | 168 | sql, args, err := b.SQL() 169 | if err != nil { 170 | t.Errorf("unexpected error: %v", err) 171 | } 172 | 173 | if want != sql { 174 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 175 | } 176 | if !reflect.DeepEqual(args, expectedArgs) { 177 | t.Errorf("expected %v, got %v instead", expectedArgs, args) 178 | } 179 | } 180 | 181 | func TestSelectBuilderNestedSelectJoin(t *testing.T) { 182 | t.Parallel() 183 | want := "SELECT * FROM bar JOIN ( SELECT * FROM baz WHERE foo = $1 ) r ON bar.foo = r.foo" 184 | expectedArgs := []any{42} 185 | 186 | nestedSelect := Select("*").From("baz").Where("foo = ?", 42) 187 | 188 | b := Select("*").From("bar").JoinClause(nestedSelect.Prefix("JOIN (").Suffix(") r ON bar.foo = r.foo")) 189 | 190 | sql, args, err := b.SQL() 191 | if err != nil { 192 | t.Errorf("unexpected error: %v", err) 193 | } 194 | 195 | if want != sql { 196 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 197 | } 198 | if !reflect.DeepEqual(args, expectedArgs) { 199 | t.Errorf("expected %v, got %v instead", expectedArgs, args) 200 | } 201 | } 202 | 203 | func TestSelectWithOptions(t *testing.T) { 204 | t.Parallel() 205 | sql, _, err := Select("*").From("foo").Options("ALL").SQL() 206 | 207 | if err != nil { 208 | t.Errorf("unexpected error: %v", err) 209 | } 210 | if want := "SELECT ALL * FROM foo"; sql != want { 211 | t.Errorf("expected %q, got %v", want, sql) 212 | } 213 | } 214 | 215 | func TestSelectWithRemoveLimit(t *testing.T) { 216 | t.Parallel() 217 | sql, _, err := Select("*").From("foo").Limit(10).RemoveLimit().SQL() 218 | 219 | if err != nil { 220 | t.Errorf("unexpected error: %v", err) 221 | } 222 | if want := "SELECT * FROM foo"; sql != want { 223 | t.Errorf("expected %q, got %v", want, sql) 224 | } 225 | } 226 | 227 | func TestSelectWithRemoveOffset(t *testing.T) { 228 | t.Parallel() 229 | sql, _, err := Select("*").From("foo").Offset(10).RemoveOffset().SQL() 230 | 231 | if err != nil { 232 | t.Errorf("unexpected error: %v", err) 233 | } 234 | if want := "SELECT * FROM foo"; sql != want { 235 | t.Errorf("expected %q, got %v", want, sql) 236 | } 237 | } 238 | 239 | func TestSelectBuilderNestedSelectDollar(t *testing.T) { 240 | t.Parallel() 241 | nestedBuilder := Select("*").Prefix("NOT EXISTS ("). 242 | From("bar").Where("y = ?", 42).Suffix(")") 243 | outerSQL, _, err := Select("*"). 244 | From("foo").Where("x = ?").Where(nestedBuilder).SQL() 245 | 246 | if err != nil { 247 | t.Errorf("unexpected error: %v", err) 248 | } 249 | if want := "SELECT * FROM foo WHERE x = $1 AND NOT EXISTS ( SELECT * FROM bar WHERE y = $2 )"; outerSQL != want { 250 | t.Errorf("expected %q, got %v", want, outerSQL) 251 | } 252 | } 253 | 254 | func TestSelectBuilderMustSQL(t *testing.T) { 255 | t.Parallel() 256 | defer func() { 257 | if r := recover(); r == nil { 258 | t.Errorf("TestSelectBuilderMustSQL should have panicked!") 259 | } 260 | }() 261 | // This function should cause a panic 262 | Select().From("foo").MustSQL() 263 | } 264 | 265 | func TestSelectWithoutWhereClause(t *testing.T) { 266 | t.Parallel() 267 | sql, _, err := Select("*").From("users").SQL() 268 | if err != nil { 269 | t.Errorf("unexpected error: %v", err) 270 | } 271 | if want := "SELECT * FROM users"; sql != want { 272 | t.Errorf("expected %q, got %v", want, sql) 273 | } 274 | } 275 | 276 | func TestSelectWithNilWhereClause(t *testing.T) { 277 | t.Parallel() 278 | sql, _, err := Select("*").From("users").Where(nil).SQL() 279 | if err != nil { 280 | t.Errorf("unexpected error: %v", err) 281 | } 282 | if want := "SELECT * FROM users"; sql != want { 283 | t.Errorf("expected %q, got %v", want, sql) 284 | } 285 | } 286 | 287 | func TestSelectWithEmptyStringWhereClause(t *testing.T) { 288 | t.Parallel() 289 | sql, _, err := Select("*").From("users").Where("").SQL() 290 | if err != nil { 291 | t.Errorf("unexpected error: %v", err) 292 | } 293 | if want := "SELECT * FROM users"; sql != want { 294 | t.Errorf("expected %q, got %v", want, sql) 295 | } 296 | } 297 | 298 | func TestSelectSubqueryPlaceholderNumbering(t *testing.T) { 299 | t.Parallel() 300 | subquery := Select("a").Where("b = ?", 1) 301 | with := subquery.Prefix("WITH a AS (").Suffix(")") 302 | 303 | sql, args, err := Select("*"). 304 | PrefixExpr(with). 305 | FromSelect(subquery, "q"). 306 | Where("c = ?", 2). 307 | SQL() 308 | if err != nil { 309 | t.Errorf("unexpected error: %v", err) 310 | } 311 | 312 | want := "WITH a AS ( SELECT a WHERE b = $1 ) SELECT * FROM (SELECT a WHERE b = $2) AS q WHERE c = $3" 313 | if want != sql { 314 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 315 | } 316 | if want := []any{1, 1, 2}; !reflect.DeepEqual(args, want) { 317 | t.Errorf("expected %q, got %q instead", want, args) 318 | } 319 | } 320 | 321 | func TestSelectSubqueryInConjunctionPlaceholderNumbering(t *testing.T) { 322 | t.Parallel() 323 | subquery := Select("a").Where(Eq{"b": 1}).Prefix("EXISTS(").Suffix(")") 324 | 325 | sql, args, err := Select("*"). 326 | Where(Or{subquery}). 327 | Where("c = ?", 2). 328 | SQL() 329 | if err != nil { 330 | t.Errorf("unexpected error: %v", err) 331 | } 332 | 333 | want := "SELECT * WHERE (EXISTS( SELECT a WHERE b = $1 )) AND c = $2" 334 | if want != sql { 335 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 336 | } 337 | if want := []any{1, 2}; !reflect.DeepEqual(args, want) { 338 | t.Errorf("expected %q, got %q instead", want, args) 339 | } 340 | } 341 | 342 | func TestSelectJoinClausePlaceholderNumbering(t *testing.T) { 343 | t.Parallel() 344 | subquery := Select("a").Where(Eq{"b": 2}) 345 | 346 | sql, args, err := Select("t1.a"). 347 | From("t1"). 348 | Where(Eq{"a": 1}). 349 | JoinClause(subquery.Prefix("JOIN (").Suffix(") t2 ON (t1.a = t2.a)")). 350 | SQL() 351 | if err != nil { 352 | t.Errorf("unexpected error: %v", err) 353 | } 354 | 355 | want := "SELECT t1.a FROM t1 JOIN ( SELECT a WHERE b = $1 ) t2 ON (t1.a = t2.a) WHERE a = $2" 356 | if want != sql { 357 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 358 | } 359 | if want := []any{2, 1}; !reflect.DeepEqual(args, want) { 360 | t.Errorf("expected %q, got %q instead", want, args) 361 | } 362 | } 363 | 364 | func ExampleSelect() { 365 | Select("id", "created", "first_name").From("users") // ... continue building up your query 366 | 367 | // sql methods in select columns are ok 368 | Select("first_name", "count(*)").From("users") 369 | 370 | // column aliases are ok too 371 | Select("first_name", "count(*) as n_users").From("users") 372 | } 373 | 374 | func ExampleSelectBuilder_From() { 375 | Select("id", "created", "first_name").From("users") // ... continue building up your query 376 | } 377 | 378 | func ExampleSelectBuilder_Where() { 379 | companyId := 20 380 | Select("id", "created", "first_name").From("users").Where("company = ?", companyId) 381 | } 382 | 383 | func ExampleSelectBuilder_Where_helpers() { 384 | companyId := 20 385 | 386 | Select("id", "created", "first_name").From("users").Where(Eq{ 387 | "company": companyId, 388 | }) 389 | 390 | Select("id", "created", "first_name").From("users").Where(GtOrEq{ 391 | "created": time.Now().AddDate(0, 0, -7), 392 | }) 393 | 394 | Select("id", "created", "first_name").From("users").Where(And{ 395 | GtOrEq{ 396 | "created": time.Now().AddDate(0, 0, -7), 397 | }, 398 | Eq{ 399 | "company": companyId, 400 | }, 401 | }) 402 | } 403 | 404 | func ExampleSelectBuilder_Where_multiple() { 405 | companyId := 20 406 | 407 | // multiple where's are ok 408 | 409 | Select("id", "created", "first_name"). 410 | From("users"). 411 | Where("company = ?", companyId). 412 | Where(GtOrEq{ 413 | "created": time.Now().AddDate(0, 0, -7), 414 | }) 415 | } 416 | 417 | func ExampleSelectBuilder_FromSelect() { 418 | usersByCompany := Select("company", "count(*) as n_users").From("users").GroupBy("company") 419 | query := Select("company.id", "company.name", "users_by_company.n_users"). 420 | FromSelect(usersByCompany, "users_by_company"). 421 | Join("company on company.id = users_by_company.company") 422 | 423 | sql, _, _ := query.SQL() 424 | fmt.Println(sql) 425 | 426 | // 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 427 | } 428 | 429 | func ExampleSelectBuilder_Columns() { 430 | query := Select("id").Columns("created", "first_name").From("users") 431 | 432 | sql, _, _ := query.SQL() 433 | fmt.Println(sql) 434 | // Output: SELECT id, created, first_name FROM users 435 | } 436 | 437 | func ExampleSelectBuilder_Columns_order() { 438 | // out of order is ok too 439 | query := Select("id").Columns("created").From("users").Columns("first_name") 440 | 441 | sql, _, _ := query.SQL() 442 | fmt.Println(sql) 443 | // Output: SELECT id, created, first_name FROM users 444 | } 445 | 446 | func TestRemoveColumns(t *testing.T) { 447 | t.Parallel() 448 | query := Select("id"). 449 | From("users"). 450 | RemoveColumns() 451 | query = query.Columns("name") 452 | sql, _, err := query.SQL() 453 | if err != nil { 454 | t.Errorf("unexpected error: %v", err) 455 | } 456 | if want := "SELECT name FROM users"; sql != want { 457 | t.Errorf("expected %q, got %v", want, sql) 458 | } 459 | } 460 | 461 | func TestSelectBuilder_PrefixExpr_NestedUpdateDollar(t *testing.T) { 462 | t.Parallel() 463 | nestedBuilder := Update("foo").Prefix("WITH updated AS ("). 464 | Set("x", 42).Where("x = ?", 41).Returning("*").Suffix(")") 465 | outerSQL, _, err := Select("*"). 466 | From("updated").Where("y = ?", 11).PrefixExpr(nestedBuilder).SQL() 467 | 468 | if err != nil { 469 | t.Errorf("unexpected error: %v", err) 470 | } 471 | want := "WITH updated AS ( UPDATE foo SET x = $1 WHERE x = $2 RETURNING * ) SELECT * FROM updated WHERE y = $3" 472 | if outerSQL != want { 473 | t.Errorf("expected %q, got %v", want, outerSQL) 474 | } 475 | } 476 | 477 | func TestSelectBuilder_PrefixExpr_NestedDeleteDollar(t *testing.T) { 478 | t.Parallel() 479 | nestedBuilder := Delete("foo").Prefix("WITH deleted AS ("). 480 | Where("x = ?", 41).Returning("*").Suffix(")") 481 | outerSQL, _, err := Select("*"). 482 | From("deleted").Where("y = ?", 11).PrefixExpr(nestedBuilder).SQL() 483 | 484 | if err != nil { 485 | t.Errorf("unexpected error: %v", err) 486 | } 487 | want := "WITH deleted AS ( DELETE FROM foo WHERE x = $1 RETURNING * ) SELECT * FROM deleted WHERE y = $2" 488 | if outerSQL != want { 489 | t.Errorf("expected %q, got %v", want, outerSQL) 490 | } 491 | } 492 | -------------------------------------------------------------------------------- /statement.go: -------------------------------------------------------------------------------- 1 | package pgq 2 | 3 | // StatementBuilder for WHERE parts. 4 | type StatementBuilder struct { 5 | whereParts []SQLizer 6 | } 7 | 8 | // Select returns a SelectBuilder for this StatementBuilder. 9 | func (b StatementBuilder) Select(columns ...string) SelectBuilder { 10 | builder := SelectBuilder{}.Columns(columns...) 11 | builder.whereParts = b.whereParts 12 | return builder 13 | } 14 | 15 | // Update returns a UpdateBuilder for this StatementBuilder. 16 | func (b StatementBuilder) Update(table string) UpdateBuilder { 17 | builder := UpdateBuilder{}.Table(table) 18 | builder.whereParts = b.whereParts 19 | return builder 20 | } 21 | 22 | // Delete returns a DeleteBuilder for this StatementBuilder. 23 | func (b StatementBuilder) Delete(from string) DeleteBuilder { 24 | builder := DeleteBuilder{}.From(from) 25 | builder.whereParts = b.whereParts 26 | return builder 27 | } 28 | 29 | // Where adds WHERE expressions to the query. 30 | // 31 | // See SelectBuilder.Where for more information. 32 | func (b StatementBuilder) Where(pred any, args ...any) StatementBuilder { 33 | b.whereParts = []SQLizer{newWherePart(pred, args...)} 34 | return b 35 | } 36 | 37 | // Statement returns a new StatementBuilder, which can be used to create SQL WHERE parts. 38 | func Statement() StatementBuilder { 39 | return StatementBuilder{} 40 | } 41 | 42 | // Select returns a new SelectBuilder, optionally setting some result columns. 43 | // 44 | // See SelectBuilder.Columns. 45 | func Select(columns ...string) SelectBuilder { 46 | return SelectBuilder{}.Columns(columns...) 47 | } 48 | 49 | // Insert returns a new InsertBuilder with the given table name. 50 | // 51 | // See InsertBuilder.Into. 52 | func Insert(into string) InsertBuilder { 53 | return InsertBuilder{into: into} 54 | } 55 | 56 | // Replace returns a new InsertBuilder with the statement keyword set to 57 | // "REPLACE" and with the given table name. 58 | // 59 | // See InsertBuilder.Into. 60 | func Replace(into string) InsertBuilder { 61 | builder := InsertBuilder{} 62 | builder.verb = "REPLACE" 63 | return builder.Into(into) 64 | } 65 | 66 | // Update returns a new UpdateBuilder with the given table name. 67 | // 68 | // See UpdateBuilder.Table. 69 | func Update(table string) UpdateBuilder { 70 | return UpdateBuilder{table: table} 71 | } 72 | 73 | // Delete returns a new DeleteBuilder with the given table name. 74 | // 75 | // See DeleteBuilder.Table. 76 | func Delete(from string) DeleteBuilder { 77 | return DeleteBuilder{from: from} 78 | } 79 | 80 | // Case returns a new CaseBuilder 81 | // "what" represents case value 82 | func Case(what ...any) CaseBuilder { 83 | b := CaseBuilder{} 84 | 85 | switch len(what) { 86 | case 0: 87 | case 1: 88 | b = b.what(what[0]) 89 | default: 90 | b = b.what(newPart(what[0], what[1:]...)) 91 | 92 | } 93 | return b 94 | } 95 | -------------------------------------------------------------------------------- /statement_test.go: -------------------------------------------------------------------------------- 1 | package pgq 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestStatementBuilderWhere(t *testing.T) { 9 | t.Parallel() 10 | sb := Statement().Where("x = ?", 1) 11 | 12 | sql, args, err := sb.Select("test").Where("y = ?", 2).SQL() 13 | if err != nil { 14 | t.Errorf("unexpected error: %v", err) 15 | } 16 | 17 | want := "SELECT test WHERE x = $1 AND y = $2" 18 | if want != sql { 19 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 20 | } 21 | 22 | expectedArgs := []any{1, 2} 23 | if !reflect.DeepEqual(expectedArgs, args) { 24 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 25 | } 26 | } 27 | 28 | func TestStatementBuilderUpdate(t *testing.T) { 29 | t.Parallel() 30 | b := Statement().Where("x = ?", "z").Update("foo").Set("a", "b") 31 | want := "UPDATE foo SET a = $1 WHERE x = $2" 32 | sql, args, err := b.SQL() 33 | 34 | if err != nil { 35 | t.Errorf("unexpected error: %v", err) 36 | } 37 | if sql != want { 38 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 39 | } 40 | expectedArgs := []any{"b", "z"} 41 | if !reflect.DeepEqual(args, expectedArgs) { 42 | t.Errorf("expected arguments to be %q, got %q instead", expectedArgs, args) 43 | } 44 | } 45 | 46 | func TestStatementBuilderDelete(t *testing.T) { 47 | t.Parallel() 48 | b := Statement().Where("x = ?", "z").Delete("foo") 49 | want := "DELETE FROM foo WHERE x = $1" 50 | sql, args, err := b.SQL() 51 | 52 | if err != nil { 53 | t.Errorf("unexpected error: %v", err) 54 | } 55 | if sql != want { 56 | t.Errorf("expected SQL to be %q, got %q instead", want, sql) 57 | } 58 | expectedArgs := []any{"z"} 59 | if !reflect.DeepEqual(args, expectedArgs) { 60 | t.Errorf("expected arguments to be %q, got %q instead", expectedArgs, args) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /update.go: -------------------------------------------------------------------------------- 1 | package pgq 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "sort" 7 | "strings" 8 | ) 9 | 10 | // UpdateBuilder builds SQL UPDATE statements. 11 | type UpdateBuilder struct { 12 | prefixes []SQLizer 13 | table string 14 | setClauses []setClause 15 | fromParts []SQLizer 16 | whereParts []SQLizer 17 | orderBys []string 18 | returning []SQLizer 19 | suffixes []SQLizer 20 | } 21 | 22 | type setClause struct { 23 | column string 24 | value any 25 | } 26 | 27 | func (b UpdateBuilder) SQL() (sqlStr string, args []any, err error) { 28 | sqlStr, args, err = b.unfinalizedSQL() 29 | if err != nil { 30 | return 31 | } 32 | 33 | sqlStr, err = dollarPlaceholder(sqlStr) 34 | return 35 | } 36 | 37 | func (b UpdateBuilder) unfinalizedSQL() (sqlStr string, args []any, err error) { 38 | if b.table == "" { 39 | err = fmt.Errorf("update statements must specify a table") 40 | return 41 | } 42 | if len(b.setClauses) == 0 { 43 | err = fmt.Errorf("update statements must have at least one Set clause") 44 | return 45 | } 46 | 47 | sql := &bytes.Buffer{} 48 | 49 | if len(b.prefixes) > 0 { 50 | args, err = appendSQL(b.prefixes, sql, " ", args) 51 | if err != nil { 52 | return 53 | } 54 | 55 | sql.WriteString(" ") 56 | } 57 | 58 | sql.WriteString("UPDATE ") 59 | sql.WriteString(b.table) 60 | 61 | sql.WriteString(" SET ") 62 | setSQLs := make([]string, len(b.setClauses)) 63 | for i, setClause := range b.setClauses { 64 | var valSQL string 65 | if vs, ok := setClause.value.(SQLizer); ok { 66 | vsql, vargs, err := vs.SQL() 67 | if err != nil { 68 | return "", nil, err 69 | } 70 | if _, ok := vs.(SelectBuilder); ok { 71 | valSQL = fmt.Sprintf("(%s)", vsql) 72 | } else { 73 | valSQL = vsql 74 | } 75 | args = append(args, vargs...) 76 | } else { 77 | valSQL = "?" 78 | args = append(args, setClause.value) 79 | } 80 | setSQLs[i] = fmt.Sprintf("%s = %s", setClause.column, valSQL) 81 | } 82 | sql.WriteString(strings.Join(setSQLs, ", ")) 83 | 84 | if len(b.fromParts) > 0 { 85 | sql.WriteString(" FROM ") 86 | args, err = appendSQL(b.fromParts, sql, ", ", args) 87 | if err != nil { 88 | return 89 | } 90 | } 91 | 92 | if len(b.whereParts) > 0 { 93 | sql.WriteString(" WHERE ") 94 | args, err = appendSQL(b.whereParts, sql, " AND ", args) 95 | if err != nil { 96 | return 97 | } 98 | } 99 | 100 | if len(b.orderBys) > 0 { 101 | sql.WriteString(" ORDER BY ") 102 | sql.WriteString(strings.Join(b.orderBys, ", ")) 103 | } 104 | 105 | if len(b.returning) > 0 { 106 | sql.WriteString(" RETURNING ") 107 | args, err = appendSQL(b.returning, sql, ", ", args) 108 | if err != nil { 109 | return 110 | } 111 | } 112 | 113 | if len(b.suffixes) > 0 { 114 | sql.WriteString(" ") 115 | args, err = appendSQL(b.suffixes, sql, " ", args) 116 | if err != nil { 117 | return 118 | } 119 | } 120 | 121 | sqlStr = sql.String() 122 | return 123 | } 124 | 125 | // MustSQL builds the query into a SQL string and bound args. 126 | // It panics if there are any errors. 127 | func (b UpdateBuilder) MustSQL() (string, []any) { 128 | sql, args, err := b.SQL() 129 | if err != nil { 130 | panic(err) 131 | } 132 | return sql, args 133 | } 134 | 135 | // Prefix adds an expression to the beginning of the query 136 | func (b UpdateBuilder) Prefix(sql string, args ...any) UpdateBuilder { 137 | return b.PrefixExpr(Expr(sql, args...)) 138 | } 139 | 140 | // PrefixExpr adds an expression to the very beginning of the query 141 | func (b UpdateBuilder) PrefixExpr(expr SQLizer) UpdateBuilder { 142 | b.prefixes = append(b.prefixes, expr) 143 | return b 144 | } 145 | 146 | // Table sets the table to be updated. 147 | func (b UpdateBuilder) Table(table string) UpdateBuilder { 148 | b.table = table 149 | return b 150 | } 151 | 152 | // Set adds SET clauses to the query. 153 | func (b UpdateBuilder) Set(column string, value any) UpdateBuilder { 154 | b.setClauses = append(b.setClauses, setClause{column: column, value: value}) 155 | return b 156 | } 157 | 158 | // SetMap is a convenience method which calls .Set for each key/value pair in clauses. 159 | func (b UpdateBuilder) SetMap(clauses map[string]any) UpdateBuilder { 160 | keys := make([]string, len(clauses)) 161 | i := 0 162 | for key := range clauses { 163 | keys[i] = key 164 | i++ 165 | } 166 | sort.Strings(keys) 167 | for _, key := range keys { 168 | if val, ok := clauses[key]; ok { 169 | b = b.Set(key, val) 170 | } 171 | } 172 | return b 173 | } 174 | 175 | // From adds FROM expressions to the query. 176 | // 177 | // A table expression allowing columns from other tables to appear in the WHERE condition and update expressions. 178 | // This uses the same syntax as the FROM clause of a SELECT statement. 179 | // Do not repeat the target table unless you intend a self-join (in which case, you must use an alias). 180 | func (b UpdateBuilder) From(items ...string) UpdateBuilder { 181 | parts := make([]SQLizer, 0, len(items)) 182 | for _, str := range items { 183 | parts = append(parts, newPart(str)) 184 | } 185 | b.fromParts = append(b.fromParts, parts...) 186 | return b 187 | } 188 | 189 | // FromSelect adds FROM expressions to the query similar to From, but takes a Select statement. 190 | func (b UpdateBuilder) FromSelect(from SelectBuilder, alias string) UpdateBuilder { 191 | b.fromParts = append(b.fromParts, Alias{Expr: from, As: alias}) 192 | return b 193 | } 194 | 195 | // Where adds WHERE expressions to the query. 196 | // 197 | // See SelectBuilder.Where for more information. 198 | func (b UpdateBuilder) Where(pred any, args ...any) UpdateBuilder { 199 | b.whereParts = append(b.whereParts, newWherePart(pred, args...)) 200 | return b 201 | } 202 | 203 | // OrderBy adds ORDER BY expressions to the query. 204 | func (b UpdateBuilder) OrderBy(orderBys ...string) UpdateBuilder { 205 | b.orderBys = append(b.orderBys, orderBys...) 206 | return b 207 | } 208 | 209 | // Returning adds RETURNING expressions to the query. 210 | func (b UpdateBuilder) Returning(columns ...string) UpdateBuilder { 211 | parts := make([]SQLizer, 0, len(columns)) 212 | for _, col := range columns { 213 | parts = append(parts, newPart(col)) 214 | } 215 | b.returning = append(b.returning, parts...) 216 | return b 217 | } 218 | 219 | // ReturningSelect adds a RETURNING expressions to the query similar to Using, but takes a Select statement. 220 | func (b UpdateBuilder) ReturningSelect(from SelectBuilder, alias string) UpdateBuilder { 221 | b.returning = append(b.returning, Alias{Expr: from, As: alias}) 222 | return b 223 | } 224 | 225 | // Suffix adds an expression to the end of the query 226 | func (b UpdateBuilder) Suffix(sql string, args ...any) UpdateBuilder { 227 | return b.SuffixExpr(Expr(sql, args...)) 228 | } 229 | 230 | // SuffixExpr adds an expression to the end of the query 231 | func (b UpdateBuilder) SuffixExpr(expr SQLizer) UpdateBuilder { 232 | b.suffixes = append(b.suffixes, expr) 233 | return b 234 | } 235 | -------------------------------------------------------------------------------- /update_test.go: -------------------------------------------------------------------------------- 1 | package pgq 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestUpdateBuilderSQL(t *testing.T) { 9 | t.Parallel() 10 | beginning := Update(""). 11 | Prefix("WITH prefix AS ?", 0). 12 | Table("a"). 13 | Set("b", Expr("? + 1", 1)). 14 | SetMap(Eq{"c": 2}). 15 | Set("c1", Case("status").When("1", "2").When("2", "1")). 16 | Set("c2", Case().When("a = 2", Expr("?", "foo")).When("a = 3", Expr("?", "bar"))). 17 | Set("c3", Select("a").From("b")). 18 | Where("d = ?", 3). 19 | OrderBy("e") 20 | 21 | testCases := []struct { 22 | name string 23 | b UpdateBuilder 24 | wantSQL string 25 | wantArgs []any 26 | wantErr error 27 | }{ 28 | { 29 | name: "with_suffix", 30 | b: beginning.Suffix("RETURNING ?", 6), 31 | wantSQL: "WITH prefix AS $1 " + 32 | "UPDATE a SET b = $2 + 1, c = $3, " + 33 | "c1 = CASE status WHEN 1 THEN 2 WHEN 2 THEN 1 END, " + 34 | "c2 = CASE WHEN a = 2 THEN $4 WHEN a = 3 THEN $5 END, " + 35 | "c3 = (SELECT a FROM b) " + 36 | "WHERE d = $6 " + 37 | "ORDER BY e " + 38 | "RETURNING $7", 39 | wantArgs: []any{0, 1, 2, "foo", "bar", 3, 6}, 40 | }, 41 | { 42 | name: "returning", 43 | b: beginning.Returning("x"), 44 | wantSQL: "WITH prefix AS $1 " + 45 | "UPDATE a SET b = $2 + 1, c = $3, " + 46 | "c1 = CASE status WHEN 1 THEN 2 WHEN 2 THEN 1 END, " + 47 | "c2 = CASE WHEN a = 2 THEN $4 WHEN a = 3 THEN $5 END, " + 48 | "c3 = (SELECT a FROM b) " + 49 | "WHERE d = $6 " + 50 | "ORDER BY e " + 51 | "RETURNING x", 52 | wantArgs: []any{0, 1, 2, "foo", "bar", 3}, 53 | }, 54 | { 55 | name: "returning_2", 56 | b: beginning.Returning("x", "y"), 57 | wantSQL: "WITH prefix AS $1 " + 58 | "UPDATE a SET b = $2 + 1, c = $3, " + 59 | "c1 = CASE status WHEN 1 THEN 2 WHEN 2 THEN 1 END, " + 60 | "c2 = CASE WHEN a = 2 THEN $4 WHEN a = 3 THEN $5 END, " + 61 | "c3 = (SELECT a FROM b) " + 62 | "WHERE d = $6 " + 63 | "ORDER BY e " + 64 | "RETURNING x, y", 65 | wantArgs: []any{0, 1, 2, "foo", "bar", 3}, 66 | }, 67 | { 68 | name: "returning_3", 69 | b: beginning.Returning("x", "y", "z"), 70 | wantSQL: "WITH prefix AS $1 " + 71 | "UPDATE a SET b = $2 + 1, c = $3, " + 72 | "c1 = CASE status WHEN 1 THEN 2 WHEN 2 THEN 1 END, " + 73 | "c2 = CASE WHEN a = 2 THEN $4 WHEN a = 3 THEN $5 END, " + 74 | "c3 = (SELECT a FROM b) " + 75 | "WHERE d = $6 " + 76 | "ORDER BY e " + 77 | "RETURNING x, y, z", 78 | wantArgs: []any{0, 1, 2, "foo", "bar", 3}, 79 | }, 80 | { 81 | name: "returning_3_multi_calls", 82 | b: beginning.Returning("x", "y").Returning("z"), 83 | wantSQL: "WITH prefix AS $1 " + 84 | "UPDATE a SET b = $2 + 1, c = $3, " + 85 | "c1 = CASE status WHEN 1 THEN 2 WHEN 2 THEN 1 END, " + 86 | "c2 = CASE WHEN a = 2 THEN $4 WHEN a = 3 THEN $5 END, " + 87 | "c3 = (SELECT a FROM b) " + 88 | "WHERE d = $6 " + 89 | "ORDER BY e " + 90 | "RETURNING x, y, z", 91 | wantArgs: []any{0, 1, 2, "foo", "bar", 3}, 92 | }, 93 | { 94 | name: "returning_select", 95 | b: beginning.ReturningSelect(Select("abc").From("atable"), "something"), 96 | wantSQL: "WITH prefix AS $1 " + 97 | "UPDATE a SET b = $2 + 1, c = $3, " + 98 | "c1 = CASE status WHEN 1 THEN 2 WHEN 2 THEN 1 END, " + 99 | "c2 = CASE WHEN a = 2 THEN $4 WHEN a = 3 THEN $5 END, " + 100 | "c3 = (SELECT a FROM b) " + 101 | "WHERE d = $6 " + 102 | "ORDER BY e " + 103 | "RETURNING (SELECT abc FROM atable) AS something", 104 | wantArgs: []any{0, 1, 2, "foo", "bar", 3}, 105 | }, 106 | { 107 | name: "from", 108 | b: Update("employees").Set("sales_count", Expr("sales_count + 1")).From("accounts"). 109 | Where("accounts.name = ?", "Acme Corporation"). 110 | Where("employees.id = accounts.sales_person"), 111 | wantSQL: "UPDATE employees SET sales_count = sales_count + 1 FROM accounts " + 112 | "WHERE accounts.name = $1 " + 113 | "AND employees.id = accounts.sales_person", 114 | wantArgs: []any{"Acme Corporation"}, 115 | }, 116 | { 117 | name: "from_select", 118 | b: Update("employees").Set("sales_count", Expr("sales_count + 1")).FromSelect( 119 | Select("name").From("accounts"), "acc", 120 | ). 121 | Where("acc.name = ?", "Acme Corporation"). 122 | Where("employees.id = acc.sales_person"), 123 | wantSQL: "UPDATE employees SET sales_count = sales_count + 1 " + 124 | "FROM (SELECT name FROM accounts) " + 125 | "AS acc WHERE acc.name = $1 AND employees.id = acc.sales_person", 126 | wantArgs: []any{"Acme Corporation"}, 127 | }, 128 | } 129 | 130 | for _, tc := range testCases { 131 | tc := tc 132 | t.Run(tc.name, func(t *testing.T) { 133 | t.Parallel() 134 | sql, args, err := tc.b.SQL() 135 | if err != tc.wantErr { 136 | t.Errorf("expected error to be %v, got %v instead", tc.wantErr, err) 137 | } 138 | if sql != tc.wantSQL { 139 | t.Errorf("expected SQL to be %q, got %q instead", tc.wantSQL, sql) 140 | } 141 | if !reflect.DeepEqual(args, tc.wantArgs) { 142 | t.Errorf("wanted %v, got %v instead", tc.wantArgs, args) 143 | } 144 | }) 145 | } 146 | } 147 | 148 | func TestUpdateBuilderSQLErr(t *testing.T) { 149 | t.Parallel() 150 | _, _, err := Update("").Set("x", 1).SQL() 151 | if want := "update statements must specify a table"; err.Error() != want { 152 | t.Errorf("expected error to be %q, got %q instead", want, err) 153 | } 154 | 155 | _, _, err = Update("x").SQL() 156 | if want := "update statements must have at least one Set clause"; err.Error() != want { 157 | t.Errorf("expected error to be %q, got %q instead", want, err) 158 | } 159 | } 160 | 161 | func TestUpdateBuilderMustSQL(t *testing.T) { 162 | t.Parallel() 163 | defer func() { 164 | if r := recover(); r == nil { 165 | t.Errorf("TestUpdateBuilderMustSQL should have panicked!") 166 | } 167 | }() 168 | Update("").MustSQL() 169 | } 170 | 171 | func TestUpdateBuilderPlaceholders(t *testing.T) { 172 | t.Parallel() 173 | b := Update("test").SetMap(Eq{"x": 1, "y": 2}) 174 | 175 | sql, _, err := b.SQL() 176 | if err != nil { 177 | t.Errorf("unexpected error: %v", err) 178 | } 179 | if want := "UPDATE test SET x = $1, y = $2"; sql != want { 180 | t.Errorf("expected %q, got %q instead", want, sql) 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /where.go: -------------------------------------------------------------------------------- 1 | package pgq 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type wherePart part 8 | 9 | func newWherePart(pred any, args ...any) SQLizer { 10 | return &wherePart{pred: pred, args: args} 11 | } 12 | 13 | func (p wherePart) SQL() (sql string, args []any, err error) { 14 | switch pred := p.pred.(type) { 15 | case nil: 16 | // no-op 17 | case rawSQLizer: 18 | return pred.unfinalizedSQL() 19 | case SQLizer: 20 | return pred.SQL() 21 | case map[string]any: 22 | return Eq(pred).SQL() 23 | case string: 24 | sql = pred 25 | args = p.args 26 | default: 27 | err = fmt.Errorf("expected string-keyed map or string, not %T", pred) 28 | } 29 | return 30 | } 31 | -------------------------------------------------------------------------------- /where_test.go: -------------------------------------------------------------------------------- 1 | package pgq 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | 7 | "bytes" 8 | ) 9 | 10 | func TestWherePartsAppendSQL(t *testing.T) { 11 | t.Parallel() 12 | parts := []SQLizer{ 13 | newWherePart("x = ?", 1), 14 | newWherePart(nil), 15 | newWherePart(Eq{"y": 2}), 16 | } 17 | sql := &bytes.Buffer{} 18 | args, err := appendSQL(parts, sql, " AND ", []any{}) 19 | if err != nil { 20 | t.Errorf("unexpected error: %v", err) 21 | } 22 | if want, got := "x = ? AND y = ?", sql.String(); want != got { 23 | t.Errorf("expected %q, got %q instead", want, got) 24 | } 25 | expectedArgs := []any{1, 2} 26 | if !reflect.DeepEqual(expectedArgs, args) { 27 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 28 | } 29 | } 30 | 31 | func TestWherePartsAppendSQLErr(t *testing.T) { 32 | t.Parallel() 33 | parts := []SQLizer{newWherePart(1)} 34 | _, err := appendSQL(parts, &bytes.Buffer{}, "", []any{}) 35 | if want := "expected string-keyed map or string, not int"; err.Error() != want { 36 | t.Errorf("expected error to be %q, got %q instead", want, err) 37 | } 38 | } 39 | 40 | func TestWherePartNil(t *testing.T) { 41 | t.Parallel() 42 | sql, _, err := newWherePart(nil).SQL() 43 | if err != nil { 44 | t.Errorf("unexpected error: %v", err) 45 | } 46 | if sql != "" { 47 | t.Errorf("expected WHERE to be empty") 48 | } 49 | } 50 | 51 | func TestWherePartErr(t *testing.T) { 52 | t.Parallel() 53 | _, _, err := newWherePart(1).SQL() 54 | 55 | if want := "expected string-keyed map or string, not int"; err.Error() != want { 56 | t.Errorf("expected error to be %q, got %q instead", want, err) 57 | } 58 | } 59 | 60 | func TestWherePartString(t *testing.T) { 61 | t.Parallel() 62 | sql, args, err := newWherePart("x = ?", 1).SQL() 63 | if err != nil { 64 | t.Errorf("unexpected error: %v", err) 65 | } 66 | if want := "x = ?"; sql != want { 67 | t.Errorf("expected %q, got %q instead", want, sql) 68 | } 69 | expectedArgs := []any{1} 70 | if !reflect.DeepEqual(expectedArgs, args) { 71 | t.Errorf("wanted %v, got %v instead", args, expectedArgs) 72 | } 73 | } 74 | 75 | func TestWherePartMap(t *testing.T) { 76 | t.Parallel() 77 | test := func(pred any) { 78 | sql, _, err := newWherePart(pred).SQL() 79 | if err != nil { 80 | t.Errorf("unexpected error: %v", err) 81 | } 82 | expect := []string{"x = ? AND y = ?", "y = ? AND x = ?"} 83 | if sql != expect[0] && sql != expect[1] { 84 | t.Errorf("expected one of %#v, got %#v", expect, sql) 85 | } 86 | } 87 | m := map[string]any{"x": 1, "y": 2} 88 | test(m) 89 | test(Eq(m)) 90 | } 91 | --------------------------------------------------------------------------------