|
| 1 | +package utils |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "github.com/icinga/icingadb/pkg/driver" |
| 6 | + "github.com/icinga/icingadb/pkg/icingadb" |
| 7 | + "github.com/icinga/icingadb/pkg/utils" |
| 8 | + "strings" |
| 9 | +) |
| 10 | + |
| 11 | +// BuildInsertStmtWithout builds an insert stmt without the provided column. |
| 12 | +func BuildInsertStmtWithout(db *icingadb.DB, into interface{}, withoutColumn string) string { |
| 13 | + columns := db.BuildColumns(into) |
| 14 | + for i, column := range columns { |
| 15 | + if column == withoutColumn { |
| 16 | + // Event id is auto incremented, so just erase it from our insert columns |
| 17 | + columns = append(columns[:i], columns[i+1:]...) |
| 18 | + break |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + return fmt.Sprintf( |
| 23 | + `INSERT INTO "%s" ("%s") VALUES (%s)`, |
| 24 | + utils.TableName(into), strings.Join(columns, `", "`), |
| 25 | + fmt.Sprintf(":%s", strings.Join(columns, ", :")), |
| 26 | + ) |
| 27 | +} |
| 28 | + |
| 29 | +// InsertAndFetchId executes the given query and fetches the last inserted ID. |
| 30 | +func InsertAndFetchId(db *icingadb.DB, stmt string, args any) (int64, error) { |
| 31 | + var lastInsertId int64 |
| 32 | + if db.DriverName() == driver.PostgreSQL { |
| 33 | + preparedStmt, err := db.PrepareNamed(stmt + " RETURNING id") |
| 34 | + if err != nil { |
| 35 | + return 0, err |
| 36 | + } |
| 37 | + defer preparedStmt.Close() |
| 38 | + |
| 39 | + err = preparedStmt.Get(&lastInsertId, args) |
| 40 | + if err != nil { |
| 41 | + return 0, fmt.Errorf("failed to insert entry for type %T: %s", args, err) |
| 42 | + } |
| 43 | + } else { |
| 44 | + result, err := db.NamedExec(stmt, args) |
| 45 | + if err != nil { |
| 46 | + return 0, fmt.Errorf("failed to insert entry for type %T: %s", args, err) |
| 47 | + } |
| 48 | + |
| 49 | + lastInsertId, err = result.LastInsertId() |
| 50 | + if err != nil { |
| 51 | + return 0, fmt.Errorf("failed to fetch last insert id for type %T: %s", args, err) |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + return lastInsertId, nil |
| 56 | +} |
0 commit comments