From 840afbbb0bd57c4c961058e8d88fd84e6a8946ec Mon Sep 17 00:00:00 2001 From: Viacheslav Poturaev Date: Wed, 4 Jan 2023 04:26:24 +0100 Subject: [PATCH] Add simple ToSql implementations (#14) --- storage.go | 20 ++++++++++++++++++++ storage_test.go | 14 ++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/storage.go b/storage.go index c9bcd63..b31c824 100644 --- a/storage.go +++ b/storage.go @@ -19,11 +19,31 @@ type ToSQL interface { // StringStatement is a plain string statement. type StringStatement string +// Plain is a plain string statement. +type Plain = StringStatement + // ToSql implements query builder result. func (s StringStatement) ToSql() (string, []interface{}, error) { //nolint // Method name matches ext. implementation. return string(s), nil, nil } +type stmt struct { + query string + args []interface{} +} + +func (s stmt) ToSql() (string, []interface{}, error) { //nolint // Method name matches ext. implementation. + return s.query, s.args, nil +} + +// Stmt is a statement with placeholder arguments. +func Stmt(query string, args ...interface{}) ToSQL { + return stmt{ + query: query, + args: args, + } +} + // Open opens a database specified by its database driver name and a // driver-specific data source name, usually consisting of at least a // database name and connection information. diff --git a/storage_test.go b/storage_test.go index 19bcd61..8537ffe 100644 --- a/storage_test.go +++ b/storage_test.go @@ -347,3 +347,17 @@ func TestStorage_DB(t *testing.T) { assert.Equal(t, dbx, st.DB()) } + +func TestStmt_ToSql(t *testing.T) { + s, a, err := sqluct.Stmt("SELECT * FROM foo WHERE id=? AND name=?", 1, "bar").ToSql() + assert.Equal(t, "SELECT * FROM foo WHERE id=? AND name=?", s) + assert.Equal(t, []interface{}{1, "bar"}, a) + assert.NoError(t, err) +} + +func TestPlain_ToSql(t *testing.T) { + s, a, err := sqluct.Plain("SELECT * FROM foo WHERE id=1 AND name='bar'").ToSql() + assert.Equal(t, "SELECT * FROM foo WHERE id=1 AND name='bar'", s) + assert.Nil(t, a) + assert.NoError(t, err) +}