Skip to content

Commit

Permalink
fix: add InsertQuery.ColumnExpr to specify columns
Browse files Browse the repository at this point in the history
  • Loading branch information
vmihailenco committed Oct 13, 2021
1 parent 8a7934d commit 60ffe29
Show file tree
Hide file tree
Showing 7 changed files with 25 additions and 1 deletion.
3 changes: 3 additions & 0 deletions internal/dbtest/query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -564,6 +564,9 @@ func TestQuery(t *testing.T) {
}
return db.NewInsert().Model(&Model{ID: 123, Time: time.Unix(0, 0)})
},
func(db *bun.DB) schema.QueryAppender {
return db.NewInsert().ColumnExpr("id, name").Table("dest").Table("src")
},
}

timeRE := regexp.MustCompile(`'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+(\+\d{2}:\d{2})?'`)
Expand Down
1 change: 1 addition & 0 deletions internal/dbtest/testdata/snapshots/TestQuery-mysql5-89
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
INSERT INTO `dest` (id, name) SELECT id, name FROM `src`
1 change: 1 addition & 0 deletions internal/dbtest/testdata/snapshots/TestQuery-mysql8-89
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
INSERT INTO `dest` (id, name) SELECT id, name FROM `src`
1 change: 1 addition & 0 deletions internal/dbtest/testdata/snapshots/TestQuery-pg-89
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
INSERT INTO "dest" (id, name) SELECT id, name FROM "src"
1 change: 1 addition & 0 deletions internal/dbtest/testdata/snapshots/TestQuery-pgx-89
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
INSERT INTO "dest" (id, name) SELECT id, name FROM "src"
1 change: 1 addition & 0 deletions internal/dbtest/testdata/snapshots/TestQuery-sqlite-89
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
INSERT INTO "dest" (id, name) SELECT id, name FROM "src"
18 changes: 17 additions & 1 deletion query_insert.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,11 @@ func (q *InsertQuery) Column(columns ...string) *InsertQuery {
return q
}

func (q *InsertQuery) ColumnExpr(query string, args ...interface{}) *InsertQuery {
q.addColumn(schema.SafeQuery(query, args))
return q
}

func (q *InsertQuery) ExcludeColumn(columns ...string) *InsertQuery {
q.excludeColumn(columns)
return q
Expand Down Expand Up @@ -209,7 +214,18 @@ func (q *InsertQuery) appendColumnsValues(
b = append(b, ")"...)
}

b = append(b, " SELECT * FROM "...)
b = append(b, " SELECT "...)

if q.columns != nil {
b, err = q.appendColumns(fmter, b)
if err != nil {
return nil, err
}
} else {
b = append(b, "*"...)
}

b = append(b, " FROM "...)
b, err = q.appendOtherTables(fmter, b)
if err != nil {
return nil, err
Expand Down

0 comments on commit 60ffe29

Please sign in to comment.