Tests clean up.

This commit is contained in:
go-jet 2019-06-11 12:47:35 +02:00
parent ffba8718ca
commit 367602757f
20 changed files with 46932 additions and 178 deletions

View file

@ -2,7 +2,10 @@ package sqlbuilder
import (
"bytes"
"github.com/google/uuid"
"strconv"
"strings"
"time"
)
type serializeOption int
@ -175,6 +178,10 @@ func (q *queryData) reset() {
}
func ArgToString(value interface{}) string {
if isNil(value) {
return "NULL"
}
switch bindVal := value.(type) {
case bool:
if bindVal {
@ -210,11 +217,18 @@ func ArgToString(value interface{}) string {
return strconv.FormatFloat(float64(bindVal), 'f', -1, 64)
case string:
return `'` + bindVal + `'`
return stringQuote(bindVal)
case []byte:
return `'` + string(bindVal) + `'`
//TODO: implement
return stringQuote(string(bindVal))
case uuid.UUID:
return stringQuote(bindVal.String())
case time.Time:
return stringQuote(bindVal.String())
default:
return "[Unknown type]"
}
}
func stringQuote(value string) string {
return `'` + strings.Replace(value, "'", "''", -1) + `'`
}

View file

@ -57,7 +57,7 @@ func (c *columnImpl) defaultAlias() string {
return c.name
}
func (c *columnImpl) serializeAsOrderBy(statement statementType, out *queryData) error {
func (c *columnImpl) serializeForOrderBy(statement statementType, out *queryData) error {
if statement == set_statement {
// set Statement (UNION, EXCEPT ...) can reference only select projections in order by clause
columnRef := ""

View file

@ -141,7 +141,7 @@ func (e *expressionInterfaceImpl) serializeForProjection(statement statementType
return e.parent.serialize(statement, out, NO_WRAP)
}
func (e *expressionInterfaceImpl) serializeAsOrderBy(statement statementType, out *queryData) error {
func (e *expressionInterfaceImpl) serializeForOrderBy(statement statementType, out *queryData) error {
return e.parent.serialize(statement, out, NO_WRAP)
}

View file

@ -7,6 +7,7 @@ import (
func TestExpressionIS_NULL(t *testing.T) {
assertClauseSerialize(t, table2Col3.IS_NULL(), "table2.col3 IS NULL")
assertClauseSerialize(t, table2Col3.ADD(table2Col3).IS_NULL(), "(table2.col3 + table2.col3) IS NULL")
assertClauseSerializeErr(t, table2Col3.ADD(nil), "nil rhs.")
}
func TestExpressionIS_NOT_NULL(t *testing.T) {

View file

@ -14,12 +14,12 @@ type InsertStatement interface {
// Add a row of values to the insert Statement.
VALUES(values ...interface{}) InsertStatement
// Map or stracture mapped to column names
VALUES_MAPPING(data interface{}) InsertStatement
RETURNING(projections ...projection) InsertStatement
// Model structure mapped to column names
MODEL(data interface{}) InsertStatement
QUERY(selectStatement SelectStatement) InsertStatement
RETURNING(projections ...projection) InsertStatement
}
func newInsertStatement(t WritableTable, columns ...Column) InsertStatement {
@ -39,15 +39,14 @@ type insertStatementImpl struct {
errors []string
}
func (s *insertStatementImpl) Query(db execution.Db, destination interface{}) error {
return Query(s, db, destination)
func (i *insertStatementImpl) Query(db execution.Db, destination interface{}) error {
return Query(i, db, destination)
}
func (u *insertStatementImpl) Execute(db execution.Db) (res sql.Result, err error) {
return Execute(u, db)
func (i *insertStatementImpl) Execute(db execution.Db) (res sql.Result, err error) {
return Execute(i, db)
}
// Expression or default keyword
func (i *insertStatementImpl) VALUES(values ...interface{}) InsertStatement {
if len(values) == 0 {
return i
@ -67,20 +66,16 @@ func (i *insertStatementImpl) VALUES(values ...interface{}) InsertStatement {
return i
}
func (i *insertStatementImpl) VALUES_MAPPING(data interface{}) InsertStatement {
func (i *insertStatementImpl) MODEL(data interface{}) InsertStatement {
if data == nil {
i.addError("ADD method data is nil.")
i.addError("MODEL : data is nil.")
return i
}
value := reflect.ValueOf(data)
if value.Kind() == reflect.Ptr {
value = value.Elem()
}
value := reflect.Indirect(reflect.ValueOf(data))
if value.Kind() != reflect.Struct {
i.addError("ADD method data is not struct or pointer to struct.")
i.addError("MODEL : data is not struct or pointer to struct.")
return i
}
@ -93,11 +88,21 @@ func (i *insertStatementImpl) VALUES_MAPPING(data interface{}) InsertStatement {
structField := value.FieldByName(structFieldName)
if !structField.IsValid() {
i.addError("ADD() : Data structure doesn't contain field : " + structFieldName + " for column " + columnName)
i.addError("MODEL : Data structure doesn't contain field for column " + columnName)
return i
}
rowValues = append(rowValues, literal(structField.Interface()))
var field interface{}
fieldValue := reflect.Indirect(structField)
if fieldValue.IsValid() {
field = fieldValue.Interface()
} else {
field = nil
}
rowValues = append(rowValues, literal(field))
}
i.rows = append(i.rows, rowValues)
@ -106,15 +111,12 @@ func (i *insertStatementImpl) VALUES_MAPPING(data interface{}) InsertStatement {
}
func (i *insertStatementImpl) RETURNING(projections ...projection) InsertStatement {
//i.returning = defaultProjectionAliasing(projections)
i.returning = projections
return i
}
func (i *insertStatementImpl) QUERY(selectStatement SelectStatement) InsertStatement {
i.query = selectStatement
return i
}
@ -126,9 +128,9 @@ func (i *insertStatementImpl) DebugSql() (query string, err error) {
return DebugSql(i)
}
func (s *insertStatementImpl) Sql() (sql string, args []interface{}, err error) {
if len(s.errors) > 0 {
return "", nil, errors.New("sql builder errors: " + strings.Join(s.errors, ", "))
func (i *insertStatementImpl) Sql() (sql string, args []interface{}, err error) {
if len(i.errors) > 0 {
return "", nil, errors.New("errors: " + strings.Join(i.errors, ", "))
}
queryData := &queryData{}
@ -136,42 +138,40 @@ func (s *insertStatementImpl) Sql() (sql string, args []interface{}, err error)
queryData.nextLine()
queryData.writeString("INSERT INTO")
if s.table == nil {
return "", nil, errors.New("nil tableName.")
if isNil(i.table) {
return "", nil, errors.New("table is nil")
}
err = s.table.serialize(insert_statement, queryData)
queryData.writeByte(' ')
err = i.table.serialize(insert_statement, queryData)
if err != nil {
return "", nil, err
return
}
if len(s.columns) > 0 {
if len(i.columns) > 0 {
queryData.writeString("(")
err = serializeColumnList(insert_statement, s.columns, queryData)
err = serializeColumnList(insert_statement, i.columns, queryData)
if err != nil {
return "", nil, err
return
}
queryData.writeString(")")
}
if len(s.rows) == 0 && s.query == nil {
return "", nil, errors.New("No row or query specified.")
if len(i.rows) == 0 && i.query == nil {
return "", nil, errors.New("no row values or query specified")
}
if len(s.rows) > 0 && s.query != nil {
return "", nil, errors.New("Only new rows or query has to be specified.")
if len(i.rows) > 0 && i.query != nil {
return "", nil, errors.New("only row values or query has to be specified")
}
if len(s.rows) > 0 {
if len(i.rows) > 0 {
queryData.writeString("VALUES")
for row_i, row := range s.rows {
for row_i, row := range i.rows {
if row_i > 0 {
queryData.writeString(",")
}
@ -180,8 +180,8 @@ func (s *insertStatementImpl) Sql() (sql string, args []interface{}, err error)
queryData.nextLine()
queryData.writeString("(")
if len(row) != len(s.columns) {
return "", nil, errors.New("# of values does not match # of columns.")
if len(row) != len(i.columns) {
return "", nil, errors.New("number of values does not match number of columns")
}
err = serializeClauseList(insert_statement, row, queryData)
@ -195,19 +195,19 @@ func (s *insertStatementImpl) Sql() (sql string, args []interface{}, err error)
}
}
if s.query != nil {
err = s.query.serialize(insert_statement, queryData)
if i.query != nil {
err = i.query.serialize(insert_statement, queryData)
if err != nil {
return
}
}
if len(s.returning) > 0 {
if len(i.returning) > 0 {
queryData.nextLine()
queryData.writeString("RETURNING")
err = queryData.writeProjections(insert_statement, s.returning)
err = queryData.writeProjections(insert_statement, i.returning)
if err != nil {
return

View file

@ -105,28 +105,28 @@ INSERT INTO db.table1 (col1,colFloat) VALUES
func TestInsertValuesFromModel(t *testing.T) {
type Table1Model struct {
Col1 int
Col1 *int
ColFloat float64
}
one := 1
toInsert := Table1Model{
Col1: 1,
Col1: &one,
ColFloat: 1.11,
}
stmt := table1.INSERT(table1Col1, table1ColFloat).
VALUES_MAPPING(toInsert)
MODEL(toInsert).
MODEL(&toInsert)
sql, _, err := stmt.Sql()
assert.NilError(t, err)
fmt.Println(sql)
assert.Equal(t, sql, `
expectedSql := `
INSERT INTO db.table1 (col1,colFloat) VALUES
($1, $2);
`)
($1, $2),
($3, $4);
`
assertQuery(t, stmt, expectedSql, int(1), float64(1.11), int(1), float64(1.11))
}
func TestInsertValuesFromModelColumnMismatch(t *testing.T) {
@ -141,11 +141,11 @@ func TestInsertValuesFromModelColumnMismatch(t *testing.T) {
}
stmt := table1.INSERT(table1Col1, table1ColFloat).
VALUES_MAPPING(toInsert)
MODEL(toInsert)
_, _, err := stmt.Sql()
//fmt.Println(err)
fmt.Println(err)
assert.Assert(t, err != nil)
}

View file

@ -3,7 +3,7 @@ package sqlbuilder
import "errors"
type OrderByClause interface {
serializeAsOrderBy(statement statementType, out *queryData) error
serializeForOrderBy(statement statementType, out *queryData) error
}
type orderByClauseImpl struct {
@ -11,12 +11,12 @@ type orderByClauseImpl struct {
ascent bool
}
func (o *orderByClauseImpl) serializeAsOrderBy(statement statementType, out *queryData) error {
func (o *orderByClauseImpl) serializeForOrderBy(statement statementType, out *queryData) error {
if o.expression == nil {
return errors.New("nil orderBy by clause.")
}
if err := o.expression.serializeAsOrderBy(statement, out); err != nil {
if err := o.expression.serializeForOrderBy(statement, out); err != nil {
return err
}

View file

@ -57,7 +57,7 @@ type setStatementImpl struct {
selects []rowsType
orderBy []OrderByClause
limit, offset int64
// True if results of the union should be deduped.
all bool
}
@ -76,7 +76,6 @@ func newSetStatementImpl(operator string, all bool, selects ...rowsType) SetStat
}
func (us *setStatementImpl) ORDER_BY(orderBy ...OrderByClause) SetStatement {
us.orderBy = orderBy
return us
}
@ -100,7 +99,9 @@ func (s *setStatementImpl) serialize(statement statementType, out *queryData, op
return errors.New("Set expression is nil. ")
}
if s.orderBy != nil || s.limit >= 0 || s.offset >= 0 {
wrap := s.orderBy != nil || s.limit >= 0 || s.offset >= 0
if wrap {
out.writeString("(")
out.increaseIdent()
}
@ -111,7 +112,7 @@ func (s *setStatementImpl) serialize(statement statementType, out *queryData, op
return err
}
if s.orderBy != nil || s.limit >= 0 || s.offset >= 0 {
if wrap {
out.decreaseIdent()
out.nextLine()
out.writeString(")")

View file

@ -162,3 +162,123 @@ func TestUnionInUnion(t *testing.T) {
assert.Equal(t, len(args), 0)
assert.Equal(t, queryStr, expectedSql)
}
func TestUnionALL(t *testing.T) {
query, args, err := UNION_ALL(
table1.SELECT(table1Col1),
table2.SELECT(table2Col3),
).Sql()
assert.NilError(t, err)
fmt.Println(query)
assert.Equal(t, query, `
(
(
SELECT table1.col1 AS "table1.col1"
FROM db.table1
)
UNION ALL
(
SELECT table2.col3 AS "table2.col3"
FROM db.table2
)
);
`)
assert.Equal(t, len(args), 0)
}
func TestINTERSECT(t *testing.T) {
query, args, err := INTERSECT(
table1.SELECT(table1Col1),
table2.SELECT(table2Col3),
).Sql()
assert.NilError(t, err)
fmt.Println(query)
assert.Equal(t, query, `
(
(
SELECT table1.col1 AS "table1.col1"
FROM db.table1
)
INTERSECT
(
SELECT table2.col3 AS "table2.col3"
FROM db.table2
)
);
`)
assert.Equal(t, len(args), 0)
}
func TestINTERSECT_ALL(t *testing.T) {
query, args, err := INTERSECT_ALL(
table1.SELECT(table1Col1),
table2.SELECT(table2Col3),
).Sql()
assert.NilError(t, err)
fmt.Println(query)
assert.Equal(t, query, `
(
(
SELECT table1.col1 AS "table1.col1"
FROM db.table1
)
INTERSECT ALL
(
SELECT table2.col3 AS "table2.col3"
FROM db.table2
)
);
`)
assert.Equal(t, len(args), 0)
}
func TestEXCEPT(t *testing.T) {
query, args, err := EXCEPT(
table1.SELECT(table1Col1),
table2.SELECT(table2Col3),
).Sql()
assert.NilError(t, err)
fmt.Println(query)
assert.Equal(t, query, `
(
(
SELECT table1.col1 AS "table1.col1"
FROM db.table1
)
EXCEPT
(
SELECT table2.col3 AS "table2.col3"
FROM db.table2
)
);
`)
assert.Equal(t, len(args), 0)
}
func TestEXCEPT_ALL(t *testing.T) {
query, args, err := EXCEPT_ALL(
table1.SELECT(table1Col1),
table2.SELECT(table2Col3),
).Sql()
assert.NilError(t, err)
fmt.Println(query)
assert.Equal(t, query, `
(
(
SELECT table1.col1 AS "table1.col1"
FROM db.table1
)
EXCEPT ALL
(
SELECT table2.col3 AS "table2.col3"
FROM db.table2
)
);
`)
assert.Equal(t, len(args), 0)
}

View file

@ -80,3 +80,10 @@ func assertProjectionSerialize(t *testing.T, projection projection, query string
assert.DeepEqual(t, out.buff.String(), query)
assert.DeepEqual(t, out.args, args)
}
func assertQuery(t *testing.T, query Statement, expectedQuery string, expectedArgs ...interface{}) {
queryStr, args, err := query.Sql()
assert.NilError(t, err)
assert.Equal(t, queryStr, expectedQuery)
assert.DeepEqual(t, args, expectedArgs)
}

View file

@ -14,7 +14,7 @@ func serializeOrderByClauseList(statement statementType, orderByClauses []OrderB
out.writeString(", ")
}
err := value.serializeAsOrderBy(statement, out)
err := value.serializeForOrderBy(statement, out)
if err != nil {
return err