Skip to content

Commit 2045ba4

Browse files
committed
Introduce DB#InsertObtainID() function
1 parent 715b56e commit 2045ba4

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

database/contracts.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
package database
22

3+
import (
4+
"context"
5+
"github.com/jmoiron/sqlx"
6+
)
7+
38
// Entity is implemented by each type that works with the database package.
49
type Entity interface {
510
Fingerprinter
@@ -54,3 +59,10 @@ type PgsqlOnConflictConstrainter interface {
5459
// PgsqlOnConflictConstraint returns the primary or unique key constraint name of the PostgreSQL table.
5560
PgsqlOnConflictConstraint() string
5661
}
62+
63+
// TxOrDB is just a helper interface that can represent a *[sqlx.Tx] or *[DB] instance.
64+
type TxOrDB interface {
65+
sqlx.ExtContext
66+
67+
PrepareNamedContext(ctx context.Context, query string) (*sqlx.NamedStmt, error)
68+
}

database/db.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -804,3 +804,9 @@ func (db *DB) Log(ctx context.Context, query string, counter *com.Counter) perio
804804
db.logger.Debugf("Finished executing %q with %d rows in %s", query, counter.Total(), tick.Elapsed)
805805
}))
806806
}
807+
808+
var (
809+
// Assert TxOrDB interface compliance of the DB and sqlx.Tx types.
810+
_ TxOrDB = (*DB)(nil)
811+
_ TxOrDB = (*sqlx.Tx)(nil)
812+
)

database/utils.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"github.com/icinga/icinga-go-library/com"
88
"github.com/icinga/icinga-go-library/strcase"
99
"github.com/icinga/icinga-go-library/types"
10+
"github.com/jmoiron/sqlx"
1011
"github.com/pkg/errors"
1112
"strconv"
1213
)
@@ -44,6 +45,42 @@ func SplitOnDupId[T IDer]() com.BulkChunkSplitPolicy[T] {
4445
}
4546
}
4647

48+
// InsertObtainID executes the given query and fetches the last inserted ID.
49+
//
50+
// Using this method for database tables that don't define an auto-incrementing ID, or none at all,
51+
// will not work. The only supported column that can be retrieved with this method is id.
52+
//
53+
// This function expects [TxOrDB] as an executor of the provided query, and is usually a *[sqlx.Tx] or *[DB] instance.
54+
//
55+
// Returns the retrieved ID on success and error on any database inserting/retrieving failure.
56+
func InsertObtainID(ctx context.Context, conn TxOrDB, stmt string, arg any) (int64, error) {
57+
var resultID int64
58+
switch conn.DriverName() {
59+
case PostgreSQL:
60+
stmt = stmt + " RETURNING id"
61+
query, args, err := conn.BindNamed(stmt, arg)
62+
if err != nil {
63+
return 0, errors.Wrapf(err, "cannot bind named query %q", stmt)
64+
}
65+
66+
if err := sqlx.GetContext(ctx, conn, &resultID, query, args...); err != nil {
67+
return 0, CantPerformQuery(err, query)
68+
}
69+
default:
70+
result, err := sqlx.NamedExecContext(ctx, conn, stmt, arg)
71+
if err != nil {
72+
return 0, CantPerformQuery(err, stmt)
73+
}
74+
75+
resultID, err = result.LastInsertId()
76+
if err != nil {
77+
return 0, errors.Wrap(err, "cannot retrieve last inserted ID")
78+
}
79+
}
80+
81+
return resultID, nil
82+
}
83+
4784
// setGaleraOpts sets the "wsrep_sync_wait" variable for each session ensures that causality checks are performed
4885
// before execution and that each statement is executed on a fully synchronized node. Doing so prevents foreign key
4986
// violation when inserting into dependent tables on different MariaDB/MySQL nodes. When using MySQL single nodes,

0 commit comments

Comments
 (0)