@@ -3,28 +3,20 @@ package dbutil
33import (
44 "context"
55 "database/sql"
6- "regexp"
76 "strings"
87 "time"
98
109 sq "github.com/irees/squirrel"
1110
1211 "github.com/interline-io/log"
12+ "github.com/interline-io/transitland-lib/internal/tags"
13+ "github.com/interline-io/transitland-lib/tldb/querylogger"
1314 "github.com/jackc/pgx/v5/pgxpool"
1415 "github.com/jackc/pgx/v5/stdlib"
1516 "github.com/jmoiron/sqlx"
1617 "github.com/jmoiron/sqlx/reflectx"
1718)
1819
19- var matchFirstCap = regexp .MustCompile ("(.)([A-Z][a-z]+)" )
20- var matchAllCap = regexp .MustCompile ("([a-z0-9])([A-Z])" )
21-
22- func toSnakeCase (str string ) string {
23- snake := matchFirstCap .ReplaceAllString (str , "${1}_${2}" )
24- snake = matchAllCap .ReplaceAllString (snake , "${1}_${2}" )
25- return strings .ToLower (snake )
26- }
27-
2820// ConfigureDB sets up common database configuration
2921func ConfigureDB (sqlDb * sql.DB ) (* sqlx.DB , error ) {
3022 db := sqlx .NewDb (sqlDb , "pgx" )
@@ -35,7 +27,7 @@ func ConfigureDB(sqlDb *sql.DB) (*sqlx.DB, error) {
3527 log .Error ().Err (err ).Msgf ("could not connect to database" )
3628 return nil , err
3729 }
38- db .Mapper = reflectx .NewMapperFunc ("db" , toSnakeCase )
30+ db .Mapper = reflectx .NewMapperFunc ("db" , tags . ToSnakeCase )
3931 return db .Unsafe (), nil
4032}
4133
@@ -72,6 +64,18 @@ func OpenDB(url string) (*sqlx.DB, error) {
7264 return ConfigureDB (db .DB )
7365}
7466
67+ // WithQueryLogger wraps a database connection with a QueryLogger.
68+ // If the connection is already a QueryLogger, its settings are updated in place
69+ // and it is returned as-is (no additional wrapping layer).
70+ func WithQueryLogger (db querylogger.Ext , trace bool , longQueryDuration time.Duration ) * querylogger.QueryLogger {
71+ if ql , ok := db .(* querylogger.QueryLogger ); ok {
72+ ql .Trace = trace
73+ ql .LongQueryDuration = longQueryDuration
74+ return ql
75+ }
76+ return & querylogger.QueryLogger {Ext : db , Trace : trace , LongQueryDuration : longQueryDuration }
77+ }
78+
7579// Select runs a query and reads results into dest.
7680func Select (ctx context.Context , db sqlx.Ext , q sq.SelectBuilder , dest interface {}) error {
7781 q = q .PlaceholderFormat (sq .Dollar )
0 commit comments