Skip to content

Commit 6cad7ac

Browse files
author
Mario L Gutierrez
committed
try delete cache key on error; bug in remapPlaceholders
1 parent 78b33d2 commit 6cad7ac

17 files changed

Lines changed: 217 additions & 228 deletions

CHANGES.md

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,14 @@
1-
# Changes from legacy to v1
1+
## v1.1.0
2+
3+
* [Caching](https://github.com/mgutz/dat#caching) - caching with Redis or (in-memory for testing)
4+
* [LogQueriesThreshold](https://github.com/mgutz/dat#tracing-sql) - log slow queries
5+
* dat.Null* creators
6+
* fix resource cleanup
7+
* fix duplicate error logging
8+
* include RFC339Nano in NullTime parsing
9+
* HUGE BUG in remapPlaceholders
10+
11+
## v1.0.0
212

313
* Original dat moved to legacy branch.
414

Gododir/generate.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,15 +35,15 @@ package dat
3535
func generateTasks(p *do.Project) {
3636
p.Task("builder-boilerplate", nil, func(c *do.Context) {
3737
context := do.M{
38-
"builders": []string{"DeleteBuilder", "InsectBuilder",
38+
"builders": []string{"CallBuilder", "DeleteBuilder", "InsectBuilder",
3939
"InsertBuilder", "RawBuilder", "SelectBuilder", "SelectDocBuilder",
4040
"UpdateBuilder", "UpsertBuilder"},
4141
}
4242

4343
s, err := util.StrTemplate(builderTemplate, context)
4444
c.Check(err, "Unalbe ")
4545

46-
ioutil.WriteFile("v1/builders_generated.go", []byte(s), 0644)
47-
c.Run("go fmt v1/builders_generated.go")
46+
ioutil.WriteFile("builders_generated.go", []byte(s), 0644)
47+
c.Run("go fmt builders_generated.go")
4848
}).Desc("Generates builder boilerplate code")
4949
}

Gododir/main.go

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package main
22

33
import (
4+
"fmt"
5+
46
_ "github.com/lib/pq"
57
do "gopkg.in/godo.v2"
68
)
@@ -16,9 +18,16 @@ func tasks(p *do.Project) {
1618
p.Task("createdb", nil, createdb).Description("Creates test database")
1719

1820
p.Task("test", nil, func(c *do.Context) {
21+
c.Run(`go test -race`)
22+
c.Run(`go test -race`, do.M{"$in": "sqlx-runner"})
23+
}).Src("**/*.go").
24+
Desc("test with -race flag")
25+
26+
p.Task("test-fast", nil, func(c *do.Context) {
1927
c.Run(`go test`)
2028
c.Run(`go test`, do.M{"$in": "sqlx-runner"})
21-
}).Src("**/*.go")
29+
}).Src("**/*.go").
30+
Desc("fater test without -race flag")
2231

2332
p.Task("test-dir", nil, func(c *do.Context) {
2433
dir := c.Args.NonFlags()[0]
@@ -36,6 +45,10 @@ func tasks(p *do.Project) {
3645
`)
3746
})
3847

48+
p.Task("hello", nil, func(*do.Context) {
49+
fmt.Println("hello?")
50+
})
51+
3952
p.Task("bench", nil, func(c *do.Context) {
4053
// Bash("go test -bench . -benchmem 2>/dev/null | column -t")
4154
// Bash("go test -bench . -benchmem 2>/dev/null | column -t", In{"sqlx-runner"})
@@ -62,6 +75,33 @@ func tasks(p *do.Project) {
6275

6376
p.Task("example", nil, func(c *do.Context) {
6477
})
78+
79+
p.Task("lint", nil, func(c *do.Context) {
80+
c.Bash(`
81+
echo Directory=.
82+
golint
83+
84+
cd sqlx-runner
85+
echo
86+
echo Directory=sqlx-runner
87+
golint
88+
89+
cd ../kvs
90+
echo
91+
echo Directory=kvs
92+
golint
93+
94+
cd ../postgres
95+
echo
96+
echo Directory=postgres
97+
golint
98+
`)
99+
})
100+
101+
p.Task("mocks", nil, func(c *do.Context) {
102+
// go get github.com/vektra/mockery
103+
c.Run("mockery --dir=kvs --all")
104+
})
65105
}
66106

67107
func main() {

README.md

Lines changed: 54 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ library for Go.
2323
DB.SQL(`SELECT * FROM people LIMIT 10`).QueryStructs(&people)
2424
```
2525

26-
* JSON Document retrieval (single trip to Postgres!, requires Postgres 9.3+)
26+
* JSON Document retrieval (single trip to Postgres, requires Postgres 9.3+)
2727

2828
```go
2929
DB.SelectDoc("id", "user_name", "avatar").
@@ -140,7 +140,7 @@ func init() {
140140
panic("Could not ping database")
141141
}
142142
143-
// set to reasonable values
143+
// set to reasonable values for production
144144
db.SetMaxIdleConns(4)
145145
db.SetMaxOpenConns(16)
146146
@@ -163,7 +163,7 @@ type Post struct {
163163
Body string `db:"body"`
164164
UserID int64 `db:"user_id"`
165165
State string `db:"state"`
166-
UpdatedAt dat.Nulltime `db:"updated_at"`
166+
UpdatedAt dat.NullTime `db:"updated_at"`
167167
CreatedAt dat.NullTime `db:"created_at"`
168168
}
169169
@@ -260,7 +260,6 @@ DB.InsertInto("payments").
260260
// ensure session user can only update his information
261261
DB.Update("users").
262262
SetWhitelist(user, "user_name", "avatar", "quote").
263-
Record(userData).
264263
Where("id = $1", session.UserID).
265264
Exec()
266265
```
@@ -282,7 +281,7 @@ b.MustInterpolate() == "SELECT * FROM posts WHERE id IN (10,20,30,40,50)"
282281
`dat` uses [logxi](https://github.com/mgutz/logxi) for logging. By default,
283282
*logxi* logs all warnings and errors to the console. `dat` logs the
284283
SQL and its arguments on any error. In addition, `dat` logs slow queries
285-
as warnings if `LogQueriesThreshold > 0`
284+
as warnings if `runner.LogQueriesThreshold > 0`
286285

287286
To trace all SQL, set environment variable
288287

@@ -298,7 +297,7 @@ Use `Returning` and `QueryStruct` to insert and update struct fields in one
298297
trip
299298

300299
```go
301-
post := Post{Title: "Swith to Postgres", State: "open"}
300+
var post Post
302301
303302
err := DB.
304303
InsertInto("posts").
@@ -316,15 +315,15 @@ post := Post{Title: "Go is awesome", State: "open"}
316315
err := DB.
317316
InsertInto("posts").
318317
Blacklist("id", "user_id", "created_at", "updated_at").
319-
Record(post).
318+
Record(&post).
320319
Returning("id", "created_at", "updated_at").
321320
QueryStruct(&post)
322321
323322
// use wildcard to include all columns
324323
err := DB.
325324
InsertInto("posts").
326325
Whitelist("*").
327-
Record(post).
326+
Record(&post).
328327
Returning("id", "created_at", "updated_at").
329328
QueryStruct(&post)
330329
@@ -491,7 +490,7 @@ result, err = DB.
491490

492491
### Joins
493492

494-
Define JOINs as arguments to `From`
493+
Define JOINs in argument to `From`
495494

496495
``` go
497496
err = DB.
@@ -594,6 +593,52 @@ func getUsers(conn runner.Connection) ([]*dto.Users, error) {
594593
}
595594
```
596595
596+
#### Nested Transactions
597+
598+
Nested transaction logic is as follows:
599+
600+
* If `Commit` is called in a nested transaction, the operation results in no operation (NOOP).
601+
Only the top level `Commit` commits the transaction to the database.
602+
603+
* If `Rollback` is called in a nested transaction, then the entire
604+
transaction is rolled back. `Tx.IsRollbacked` is set to true.
605+
606+
* Either `defer Tx.AutoCommit()` or `defer Tx.AutoRollback()` **MUST BE CALLED**
607+
for each corresponding `Begin`. The internal state of nested transactions is
608+
tracked in these two methods.
609+
610+
```go
611+
func nested(conn runner.Connection) error {
612+
tx, err := conn.Begin()
613+
if err != nil {
614+
return err
615+
}
616+
defer tx.AutoRollback()
617+
618+
_, err := tx.SQL(`INSERT INTO users (email) values $1`, 'me@home.com').Exec()
619+
if err != nil {
620+
return err
621+
}
622+
// prevents AutoRollback
623+
tx.Commit()
624+
}
625+
626+
func top() {
627+
tx, err := DB.Begin()
628+
if err != nil {
629+
logger.Fatal("Could not create transaction")
630+
}
631+
defer tx.AutoRollback()
632+
633+
err := nested(tx)
634+
if err != nil {
635+
return
636+
}
637+
// top level commits the transaction
638+
tx.Commit()
639+
}
640+
```
641+
597642
### Dates
598643
599644
Use `dat.NullTime` type to properly handle nullable dates
@@ -661,80 +706,6 @@ err := DB.
661706
QueryStruct(&post)
662707
```
663708
664-
### Transactions
665-
666-
```go
667-
// Start transaction
668-
tx, err := DB.Begin()
669-
if err != nil {
670-
return err
671-
}
672-
// safe to call tx.Rollback() or tx.Commit() later
673-
defer tx.AutoRollback()
674-
675-
// Issue statements that might cause errors
676-
res, err := tx.
677-
Update("posts").
678-
Set("state", "deleted").
679-
Where("deleted_at IS NOT NULL").
680-
Exec()
681-
682-
if err != nil {
683-
// AutoRollback will rollback the transaction
684-
return err
685-
}
686-
687-
// commit to prevent AutoRollback from rolling back the transaction
688-
tx.Commit()
689-
return nil
690-
```
691-
692-
#### Nested Transactions
693-
694-
Nested transaction logic is as follows:
695-
696-
* If `Commit` is called in a nested transaction, the operation results in no operatoin (NOOP).
697-
Only the top level `Commit` commits the transaction to the database.
698-
699-
* If `Rollback` is called in a nested transaction, then the entire
700-
transaction is rolled back. `Tx.IsRollbacked` is set to true.
701-
702-
* Either `defer Tx.AutoCommit()` or `defer Tx.AutoRollback()` **MUST BE CALLED**
703-
for each corresponding `Begin`. The internal state of nested transactions is
704-
tracked in these two methods.
705-
706-
```go
707-
func nested(conn runner.Connection) error {
708-
tx, err := conn.Begin()
709-
if err != nil {
710-
return err
711-
}
712-
defer tx.AutoRollback()
713-
714-
_, err := tx.SQL(`INSERT INTO users (email) values $1`, 'me@home.com').Exec()
715-
if err != nil {
716-
return err
717-
}
718-
// prevents AutoRollback
719-
tx.Commit()
720-
}
721-
722-
func top() {
723-
tx, err := DB.Begin()
724-
if err != nil {
725-
logger.Fatal("Could not create transaction")
726-
}
727-
defer tx.AutoRollback()
728-
729-
err := nested(tx)
730-
if err != nil {
731-
return
732-
}
733-
// top level commits the transaction
734-
tx.Commit()
735-
}
736-
```
737-
738709
### Caching
739710
740711
dat implements caching backed by an in-memory or Redis store. The in-memory store

builder.go

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,5 @@
11
package dat
22

3-
import "time"
4-
5-
// Cacher caches query results.
6-
type Cacher interface {
7-
// Cache caches the result of a Select or SelectDoc. If id is not provided, an FNV checksum
8-
// of the SQL is used as the id. (If interpolation is set, arguments are hashed). Use invalidate to
9-
// immediately invalidate the cache to force setting its value.
10-
Cache(id string, duration time.Duration, invalidate bool)
11-
}
12-
133
// Builder interface is used to tie SQL generators to executors.
144
type Builder interface {
155
// ToSQL builds the SQL and arguments from builder.

execer.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ var nullExecer = &panicExecer{}
2727

2828
// panicExecer is the execer assigned when a builder is first created.
2929
// panicExecer raises a panic if any of the Execer methods are called
30-
// directly from dat. Runners override the execer to communicate with a live
30+
// directly from dat. Runners override the execer to work with a live
3131
// database.
3232
type panicExecer struct{}
3333

generate.go

Lines changed: 0 additions & 5 deletions
This file was deleted.

insert.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ func (b *InsertBuilder) Blacklist(columns ...string) *InsertBuilder {
4343
}
4444

4545
// Whitelist defines a whitelist of columns to be inserted. To
46-
// specify all columsn of a record use "*".
46+
// specify all columns of a record use "*".
4747
func (b *InsertBuilder) Whitelist(columns ...string) *InsertBuilder {
4848
b.cols = columns
4949
return b

interpolate.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ func Interpolate(sql string, vals []interface{}) (string, []interface{}, error)
6363
// Args with a blank query is an error
6464
if sql == "" {
6565
if lenVals != 0 {
66-
return "", nil, ErrArgumentMismatch
66+
return "", nil, logger.Error("Interpolation error", "err", ErrArgumentMismatch, "sql", sql, "args", vals)
6767
}
6868
return "", nil, nil
6969
}
@@ -75,13 +75,13 @@ func Interpolate(sql string, vals []interface{}) (string, []interface{}, error)
7575
// No args for a query with place holders is an error
7676
if lenVals == 0 {
7777
if hasPlaceholders {
78-
return "", nil, ErrArgumentMismatch
78+
return "", nil, logger.Error("Interpolation error", "err", ErrArgumentMismatch, "sql", sql, "args", vals)
7979
}
8080
return sql, nil, nil
8181
}
8282

8383
if lenVals > 0 && !hasPlaceholders {
84-
return "", nil, ErrArgumentMismatch
84+
return "", nil, logger.Error("Interpolation error", "err", ErrArgumentMismatch, "sql", sql, "args", vals)
8585
}
8686

8787
if !hasPlaceholders {

interpolate_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,9 @@ func TestInterpolateInts(t *testing.T) {
6161
uint64(10),
6262
}
6363

64-
str, _, err := Interpolate("SELECT * FROM x WHERE a = $1 AND b = $2 AND c = $3 AND d = $4 AND e = $5 AND f = $6 AND g = $7 AND h = $8 AND i = $9 AND j = $10", args)
64+
str, _, err := Interpolate("SELECT * FROM x WHERE a = $1 AND b = $2 AND c = $3 AND d = $4 AND e = $5 AND f = $6 AND g = $7 AND h = $8 AND i = $9 AND j = $1", args)
6565
assert.NoError(t, err)
66-
assert.Equal(t, str, "SELECT * FROM x WHERE a = 1 AND b = -2 AND c = 3 AND d = 4 AND e = 5 AND f = 6 AND g = 7 AND h = 8 AND i = 9 AND j = 10")
66+
assert.Equal(t, str, "SELECT * FROM x WHERE a = 1 AND b = -2 AND c = 3 AND d = 4 AND e = 5 AND f = 6 AND g = 7 AND h = 8 AND i = 9 AND j = 1")
6767
}
6868

6969
func TestInterpolateBools(t *testing.T) {

0 commit comments

Comments
 (0)