* Support $1, $n queries like in PostgresSQL

* Added tests for it
* Small formatting update
This commit is contained in:
Dmitriy Seredenko
2017-06-08 09:18:30 +02:00
parent 02def5bf9a
commit 830b6ef350
3 changed files with 40 additions and 5 deletions
+15 -3
View File
@@ -4,6 +4,8 @@ import (
"context"
"database/sql/driver"
"errors"
"log"
"regexp"
"strings"
"sync"
)
@@ -66,9 +68,19 @@ func (c *FakeConn) Prepare(query string) (driver.Stmt, error) {
// context is for the preparation of the statement,
// it must not store the context within the statement itself.
func (c *FakeConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
var firstStmt = &FakeStmt{q: query, connection: c} // Create statement
firstStmt.placeholders = len(strings.Split(query, "?")) - 1 // Checking how many placeholders do we have
queryParts := strings.Split(query, " ") // By First statement define the query type
var firstStmt = &FakeStmt{q: query, connection: c}
// Checking how many placeholders do we have
if strings.Contains(query, "$1") {
r, err := regexp.Compile(`[$]\d+`)
if err != nil {
log.Fatalf(`Cant't compile regexp with err [%v]`, err)
}
firstStmt.placeholders = len(strings.Split(r.ReplaceAllString(query, `$$$`), "$$")) - 1 // Postgres notation
} else {
firstStmt.placeholders = len(strings.Split(query, "?")) - 1 // Postgres notation
}
queryParts := strings.Split(query, " ") // By First statement define the query type
firstStmt.command = strings.ToUpper(queryParts[0])
return firstStmt, nil
}
+2 -1
View File
@@ -1,13 +1,14 @@
package go_mocket
import (
"database/sql"
"database/sql/driver"
"fmt"
"log"
"reflect"
"strings"
"database/sql"
)
const (
DRIVER_NAME = "MOCK_FAKE_DRIVER"
)
+23 -1
View File
@@ -43,7 +43,7 @@ func CreateUsersWithError(db *sql.DB) error {
return err
}
func InsertRecord(db *sql.DB) int64 {
func InsertRecord(db *sql.DB) int64 {
res, err := db.Exec(`INSERT INTO foo VALUES("bar", ?))`, "value")
if err != nil {
return 0
@@ -143,4 +143,26 @@ func TestResponses(t *testing.T) {
t.Fatalf("Last insert id not returned. Expected: [%v] , Got: [%v]", mockedId, returnedId)
}
})
t.Run(`Recognise both ? and $1 Postgres placeholders for raw query`, func(t *testing.T) {
t.Run("Question mark", func(t *testing.T) {
testFunc := func(db *sql.DB) string {
var name string
err := db.QueryRow(`SELECT * FROM foo a = $1 AND b = $2 AND c = $3`, "value", "value2", "value3").Scan(&name)
if err != nil {
t.Fatalf("Test function failed [%v]", err)
return ""
}
return name
}
Catcher.Reset().NewMock().WithQuery("SELECT * FROM foo ").WithReply([]map[string]interface{}{{"name": "full_name"}})
returnedName := testFunc(DB)
if returnedName != "full_name" {
t.Fatalf("Returned name mismatches. Expected: [%v] , Got: [%v]", "full_name", returnedName)
}
})
})
}