Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 21 additions & 3 deletions insert.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ package sqlbuilder

// InsertStatement represents a INSERT statement.
type InsertStatement struct {
columns ColumnList
values []literal
into Table
columns ColumnList
values []literal
into Table
returning Column

err error
}
Expand Down Expand Up @@ -72,6 +73,18 @@ func (b *InsertStatement) Set(column Column, value interface{}) *InsertStatement
return b
}

func (b *InsertStatement) Returning(column Column) *InsertStatement {
if b.err != nil {
return b
}
if !b.into.hasColumn(column) {
b.err = newError("column not found in FROM.")
return b
}
b.returning = column
return b
}

// ToSql generates query string, placeholder arguments, and returns err on errors.
func (b *InsertStatement) ToSql() (query string, args []interface{}, err error) {
bldr := newBuilder()
Expand Down Expand Up @@ -119,5 +132,10 @@ func (b *InsertStatement) ToSql() (query string, args []interface{}, err error)
bldr.AppendItems(values, ", ")
bldr.Append(" )")

if b.returning != nil {
bldr.Append(" RETURNING ")
bldr.AppendItem(b.returning)
}

return
}
7 changes: 7 additions & 0 deletions insert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,13 @@ func TestInsert(t *testing.T) {
query: `INSERT INTO "TABLE_A" ( "str", "bool", "float", "date", "bytes" ) VALUES ( ?, ?, ?, ?, ? );`,
args: []interface{}{"hoge", true, 0.1, time.Unix(0, 0).UTC(), []byte{0x01}},
errmsg: "",
}, {
stmt: Insert(table1).
Set(table1.C("str"), "x").
Returning(table1.C("id")),
query: `INSERT INTO "TABLE_A" ( "str" ) VALUES ( ? ) RETURNING "TABLE_A"."id";`,
args: []interface{}{"x"},
errmsg: "",
}, {
stmt: Insert(table1).Values(1, "hoge", true, 0.1, time.Unix(0, 0).UTC(), []byte{0x01}),
query: `INSERT INTO "TABLE_A" ( "id", "str", "bool", "float", "date", "bytes" ) VALUES ( ?, ?, ?, ?, ?, ? );`,
Expand Down