Skip to content

Commit

Permalink
Rename to sq and remove runner methods
Browse files Browse the repository at this point in the history
  • Loading branch information
silas committed Mar 15, 2024
1 parent d823874 commit d042b72
Show file tree
Hide file tree
Showing 49 changed files with 59 additions and 1,929 deletions.
36 changes: 2 additions & 34 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,30 +12,13 @@ concurrency:
cancel-in-progress: true

jobs:
squirrel:
name: Squirrel
test:
name: Test
runs-on: ubuntu-latest
strategy:
matrix:
go-version: ["1.22"]

services:
mysql:
image: mysql:8
env:
MYSQL_DATABASE: squirrel
MYSQL_ROOT_PASSWORD: root
ports:
- 3306:3306
postgres:
image: postgres:14
env:
POSTGRES_DB: squirrel
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
ports:
- 5432:5432

steps:
- name: Checkout
uses: actions/checkout@v4
Expand All @@ -49,21 +32,6 @@ jobs:
run: |
go test
- name: Integration (sqlite3)
run: |
CGO_ENABLED=1 go test -args -driver sqlite3
working-directory: integration

- name: Integration (mysql)
run: |
go test -args -driver mysql -dataSource root:root@/squirrel
working-directory: integration

- name: Integration (postgres)
run: |
go test -args -driver postgres -dataSource 'postgres://postgres:[email protected]/squirrel?sslmode=disable'
working-directory: integration

golangci:
name: GolangCI
runs-on: ubuntu-latest
Expand Down
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1 @@
squirrel.test
squirrel.test
2 changes: 1 addition & 1 deletion .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ linters-settings:
sections:
- standard
- default
- prefix(github.com/userhubdev/squirrel)
- prefix(github.com/userhubdev/sq)
- blank
- dot
custom-order: true
Expand Down
92 changes: 2 additions & 90 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
# Squirrel - fluent SQL generator for Go

```go
import "github.com/userhubdev/squirrel"
import "github.com/userhubdev/sq"
```

[![GoDoc](https://pkg.go.dev/badge/github.com/userhubdev/squirrel)](https://pkg.go.dev/github.com/userhubdev/squirrel)
Expand All @@ -16,7 +16,7 @@ import "github.com/userhubdev/squirrel"
Squirrel helps you build SQL queries from composable parts:

```go
import sq "github.com/userhubdev/squirrel"
import "github.com/userhubdev/sq"

users := sq.Select("*").From("users").Join("emails USING (email_id)")

Expand All @@ -36,18 +36,6 @@ sql, args, err := sq.
sql == "INSERT INTO users (name,age) VALUES (?,?),(?,? + 5)"
```

Squirrel can also execute queries directly:

```go
stooges := users.Where(sq.Eq{"username": []string{"moe", "larry", "curly", "shemp"}})
three_stooges := stooges.Limit(3)
rows, err := three_stooges.RunWith(db).Query()

// Behaves like:
rows, err := db.Query("SELECT * FROM users WHERE username IN (?,?,?,?) LIMIT 3",
"moe", "larry", "curly", "shemp")
```

Squirrel makes conditional query building a breeze:

```go
Expand All @@ -56,82 +44,6 @@ if len(q) > 0 {
}
```

Squirrel wants to make your life easier:

```go
// StmtCache caches Prepared Stmts for you
dbCache := sq.NewStmtCache(db)

// StatementBuilder keeps your syntax neat
mydb := sq.StatementBuilder.RunWith(dbCache)
select_users := mydb.Select("*").From("users")
```

Squirrel loves PostgreSQL:

```go
psql := sq.StatementBuilder.PlaceholderFormat(sq.Dollar)

// You use question marks for placeholders...
sql, _, _ := psql.Select("*").From("elephants").Where("name IN (?,?)", "Dumbo", "Verna").ToSql()

/// ...squirrel replaces them using PlaceholderFormat.
sql == "SELECT * FROM elephants WHERE name IN ($1,$2)"


/// You can retrieve id ...
query := sq.Insert("nodes").
Columns("uuid", "type", "data").
Values(node.Uuid, node.Type, node.Data).
Suffix("RETURNING \"id\"").
RunWith(m.db).
PlaceholderFormat(sq.Dollar)

query.QueryRow().Scan(&node.id)
```

You can escape question marks by inserting two question marks:

```sql
SELECT * FROM nodes WHERE meta->'format' ??| array[?,?]
```

will generate with the Dollar Placeholder:

```sql
SELECT * FROM nodes WHERE meta->'format' ?| array[$1,$2]
```

## FAQ

* **How can I build an IN query on composite keys / tuples, e.g. `WHERE (col1, col2) IN ((1,2),(3,4))`? ([#104](https://github.com/Masterminds/squirrel/issues/104))**

Squirrel does not explicitly support tuples, but you can get the same effect with e.g.:

```go
sq.Or{
sq.Eq{"col1": 1, "col2": 2},
sq.Eq{"col1": 3, "col2": 4}}
```

```sql
WHERE (col1 = 1 AND col2 = 2) OR (col1 = 3 AND col2 = 4)
```

(which should produce the same query plan as the tuple version)

* **Why doesn't `Eq{"mynumber": []uint8{1,2,3}}` turn into an `IN` query? ([#114](https://github.com/Masterminds/squirrel/issues/114))**
Values of type `[]byte` are handled specially by `database/sql`. In Go, [`byte` is just an alias of `uint8`](https://golang.org/pkg/builtin/#byte), so there is no way to distinguish `[]uint8` from `[]byte`.
* **Some features are poorly documented!**
This isn't a frequent complaints section!

* **Some features are poorly documented?**

Yes. The tests should be considered a part of the documentation; take a look at those for ideas on how to express more complex queries.

## License

Squirrel is released under the
Expand Down
14 changes: 2 additions & 12 deletions case.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package squirrel
package sq

import (
"bytes"
"errors"

"github.com/userhubdev/squirrel/internal/builder"
"github.com/userhubdev/sq/internal/builder"
)

func init() {
Expand Down Expand Up @@ -100,16 +100,6 @@ func (b CaseBuilder) ToSql() (string, []any, error) {
return data.ToSql()
}

// MustSql builds the query into a SQL string and bound args.
// It panics if there are any errors.
func (b CaseBuilder) MustSql() (string, []any) {
sql, args, err := b.ToSql()
if err != nil {
panic(err)
}
return sql, args
}

// what sets optional value for CASE construct "CASE [value] ..."
func (b CaseBuilder) what(expr any) CaseBuilder {
return builder.Set(b, "What", newPart(expr)).(CaseBuilder)
Expand Down
11 changes: 1 addition & 10 deletions case_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package squirrel
package sq

import (
"testing"
Expand Down Expand Up @@ -139,12 +139,3 @@ func TestCaseWithNoWhenClause(t *testing.T) {

require.Equal(t, "case expression must contain at lease one WHEN clause", err.Error())
}

func TestCaseBuilderMustSql(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Errorf("TestCaseBuilderMustSql should have panicked!")
}
}()
Case("").MustSql()
}
48 changes: 2 additions & 46 deletions delete.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
package squirrel
package sq

import (
"bytes"
"database/sql"
"fmt"
"strings"

"github.com/userhubdev/squirrel/internal/builder"
"github.com/userhubdev/sq/internal/builder"
)

type deleteData struct {
PlaceholderFormat PlaceholderFormat
RunWith BaseRunner
Prefixes []Sqlizer
From string
WhereParts []Sqlizer
Expand All @@ -21,13 +19,6 @@ type deleteData struct {
Suffixes []Sqlizer
}

func (d *deleteData) Exec() (sql.Result, error) {
if d.RunWith == nil {
return nil, RunnerNotSet
}
return ExecWith(d.RunWith, d)
}

func (d *deleteData) ToSql() (sqlStr string, args []any, err error) {
if len(d.From) == 0 {
err = fmt.Errorf("delete statements must specify a From table")
Expand Down Expand Up @@ -100,19 +91,6 @@ func (b DeleteBuilder) PlaceholderFormat(f PlaceholderFormat) DeleteBuilder {
return builder.Set(b, "PlaceholderFormat", f).(DeleteBuilder)
}

// Runner methods

// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec.
func (b DeleteBuilder) RunWith(runner BaseRunner) DeleteBuilder {
return setRunWith(b, runner).(DeleteBuilder)
}

// Exec builds and Execs the query with the Runner set by RunWith.
func (b DeleteBuilder) Exec() (sql.Result, error) {
data := builder.GetStruct(b).(deleteData)
return data.Exec()
}

// SQL methods

// ToSql builds the query into a SQL string and bound args.
Expand All @@ -121,16 +99,6 @@ func (b DeleteBuilder) ToSql() (string, []any, error) {
return data.ToSql()
}

// MustSql builds the query into a SQL string and bound args.
// It panics if there are any errors.
func (b DeleteBuilder) MustSql() (string, []any) {
sql, args, err := b.ToSql()
if err != nil {
panic(err)
}
return sql, args
}

// Prefix adds an expression to the beginning of the query
func (b DeleteBuilder) Prefix(sql string, args ...any) DeleteBuilder {
return b.PrefixExpr(Expr(sql, args...))
Expand Down Expand Up @@ -177,15 +145,3 @@ func (b DeleteBuilder) Suffix(sql string, args ...any) DeleteBuilder {
func (b DeleteBuilder) SuffixExpr(expr Sqlizer) DeleteBuilder {
return builder.Append(b, "Suffixes", expr).(DeleteBuilder)
}

func (b DeleteBuilder) Query() (*sql.Rows, error) {
data := builder.GetStruct(b).(deleteData)
return data.Query()
}

func (d *deleteData) Query() (*sql.Rows, error) {
if d.RunWith == nil {
return nil, RunnerNotSet
}
return QueryWith(d.RunWith, d)
}
67 changes: 0 additions & 67 deletions delete_ctx.go

This file was deleted.

Loading

0 comments on commit d042b72

Please sign in to comment.