Skip to content

Commit 9cb2383

Browse files
committed
Add and implement QueryBuilder.InsertStatement()
1 parent 733a530 commit 9cb2383

File tree

1 file changed

+43
-1
lines changed

1 file changed

+43
-1
lines changed

database/query_builder.go

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,18 @@
11
package database
22

33
import (
4+
"fmt"
45
"github.com/icinga/icinga-go-library/strcase"
56
"github.com/jmoiron/sqlx/reflectx"
7+
"slices"
8+
"strings"
69
)
710

8-
type QueryBuilder interface{}
11+
type QueryBuilder interface {
12+
InsertStatement(stmt InsertStatement) string
13+
14+
BuildColumns(entity Entity, columns []string, excludedColumns []string) []string
15+
}
916

1017
func NewQueryBuilder(driver string) QueryBuilder {
1118
return &queryBuilder{
@@ -18,3 +25,38 @@ type queryBuilder struct {
1825
driver string
1926
columnMap ColumnMap
2027
}
28+
29+
func (qb *queryBuilder) InsertStatement(stmt InsertStatement) string {
30+
columns := qb.BuildColumns(stmt.Entity(), stmt.Columns(), stmt.ExcludedColumns())
31+
into := stmt.Table()
32+
if into == "" {
33+
into = TableName(stmt.Entity())
34+
}
35+
36+
return fmt.Sprintf(
37+
`INSERT INTO "%s" ("%s") VALUES (%s)`,
38+
into,
39+
strings.Join(columns, `", "`),
40+
fmt.Sprintf(":%s", strings.Join(columns, ", :")),
41+
)
42+
}
43+
44+
func (qb *queryBuilder) BuildColumns(entity Entity, columns []string, excludedColumns []string) []string {
45+
var deltaColumns []string
46+
if len(columns) > 0 {
47+
deltaColumns = columns
48+
} else {
49+
deltaColumns = qb.columnMap.Columns(entity)
50+
}
51+
52+
if len(excludedColumns) > 0 {
53+
deltaColumns = slices.DeleteFunc(
54+
deltaColumns,
55+
func(column string) bool {
56+
return slices.Contains(excludedColumns, column)
57+
},
58+
)
59+
}
60+
61+
return deltaColumns[:len(deltaColumns):len(deltaColumns)]
62+
}

0 commit comments

Comments
 (0)