Merge pull request #87 from zhongr3n/zhongr3n/fix-insert-ignore

Add insert ignore support for postgres and sqlite
This commit is contained in:
Huan Du
2022-09-17 18:42:12 +08:00
committed by GitHub
3 changed files with 57 additions and 3 deletions
+24
View File
@@ -131,3 +131,27 @@ func (f Flavor) Quote(name string) string {
return name
}
// PrepareInsertIgnore prepares the insert builder to build insert ignore SQL statement based on the sql flavor
func (f Flavor) PrepareInsertIgnore(table string, ib *InsertBuilder) {
switch ib.args.Flavor {
case MySQL:
ib.verb = "INSERT IGNORE"
case PostgreSQL:
// see https://www.postgresql.org/docs/current/sql-insert.html
ib.verb = "INSERT"
// add sql statement at the end after values, i.e. INSERT INTO ... ON CONFLICT DO NOTHING
ib.marker = insertMarkerAfterValues
ib.SQL("ON CONFLICT DO NOTHING")
case SQLite:
// see https://www.sqlite.org/lang_insert.html
ib.verb = "INSERT OR IGNORE"
default:
// panic if the db flavor is not supported
panic(fmt.Errorf("unsupported db flavor: %s", ib.args.Flavor.String()))
}
// Set the table and reset the marker right after insert into
ib.table = Escape(table)
ib.marker = insertMarkerAfterInsertInto
}
+1 -3
View File
@@ -64,9 +64,7 @@ func InsertIgnoreInto(table string) *InsertBuilder {
// InsertIgnoreInto sets table name in INSERT IGNORE.
func (ib *InsertBuilder) InsertIgnoreInto(table string) *InsertBuilder {
ib.verb = "INSERT IGNORE"
ib.table = Escape(table)
ib.marker = insertMarkerAfterInsertInto
ib.args.Flavor.PrepareInsertIgnore(table, ib)
return ib
}
+32
View File
@@ -81,6 +81,38 @@ func ExampleInsertBuilder_insertIgnore() {
// [1 Huan Du 1 2 Charmy Liu 1 1234567890]
}
func ExampleInsertBuilder_insertIgnore_postgres() {
ib := PostgreSQL.NewInsertBuilder()
ib.InsertIgnoreInto("demo.user")
ib.Cols("id", "name", "status", "created_at")
ib.Values(1, "Huan Du", 1, Raw("UNIX_TIMESTAMP(NOW())"))
ib.Values(2, "Charmy Liu", 1, 1234567890)
sql, args := ib.Build()
fmt.Println(sql)
fmt.Println(args)
// Output:
// INSERT INTO demo.user (id, name, status, created_at) VALUES ($1, $2, $3, UNIX_TIMESTAMP(NOW())), ($4, $5, $6, $7) ON CONFLICT DO NOTHING
// [1 Huan Du 1 2 Charmy Liu 1 1234567890]
}
func ExampleInsertBuilder_insertIgnore_sqlite() {
ib := SQLite.NewInsertBuilder()
ib.InsertIgnoreInto("demo.user")
ib.Cols("id", "name", "status", "created_at")
ib.Values(1, "Huan Du", 1, Raw("UNIX_TIMESTAMP(NOW())"))
ib.Values(2, "Charmy Liu", 1, 1234567890)
sql, args := ib.Build()
fmt.Println(sql)
fmt.Println(args)
// Output:
// INSERT OR IGNORE INTO demo.user (id, name, status, created_at) VALUES (?, ?, ?, UNIX_TIMESTAMP(NOW())), (?, ?, ?, ?)
// [1 Huan Du 1 2 Charmy Liu 1 1234567890]
}
func ExampleInsertBuilder_replaceInto() {
ib := NewInsertBuilder()
ib.ReplaceInto("demo.user")