- Most functions now live directly in the dbx package - dbxp and dbxm are now ONLY the few functions that cannot be shared
93 lines
2.2 KiB
Go
93 lines
2.2 KiB
Go
package dbxp
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"slices"
|
|
"strings"
|
|
|
|
"gitea.auvem.com/go-toolkit/dbx"
|
|
"gitea.auvem.com/go-toolkit/dbx/internal/dbxshared"
|
|
"github.com/fatih/color"
|
|
"github.com/go-jet/jet/v2/postgres"
|
|
)
|
|
|
|
func init() {
|
|
dbxshared.RegisterLogger(dbx.DialectPostgres, &_postgresLogger{})
|
|
}
|
|
|
|
// SoftDelete sets the deleted_at column to the current time
|
|
func SoftDelete(sqlo dbx.Executable, tbl postgres.Table, conds postgres.BoolExpression) (int64, error) {
|
|
stmt := tbl.UPDATE().WHERE(conds)
|
|
query := stmt.DebugSql()
|
|
|
|
lines := strings.Split(query, "\n")
|
|
for i, line := range lines {
|
|
fmt.Println(i, line)
|
|
}
|
|
|
|
lines = slices.Insert(lines, 2, "SET deleted_at = NOW()")
|
|
query = strings.Join(lines, "\n")
|
|
|
|
res, err := sqlo.Exec(query)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
return res.RowsAffected()
|
|
}
|
|
|
|
// NormalCols processes a list of columns and strips out any that implement any of
|
|
// postgres.ColumnTimestamp, postgres.ColumnTime, or postgres.ColumnDate
|
|
func NormalCols(cols ...postgres.Column) postgres.ColumnList {
|
|
res := make(postgres.ColumnList, 0)
|
|
|
|
for _, col := range cols {
|
|
_, ok := col.(postgres.ColumnTimestamp)
|
|
|
|
if !ok {
|
|
_, ok = col.(postgres.ColumnTime)
|
|
}
|
|
if !ok {
|
|
_, ok = col.(postgres.ColumnDate)
|
|
}
|
|
|
|
if !ok {
|
|
res = append(res, col)
|
|
}
|
|
}
|
|
|
|
return res
|
|
}
|
|
|
|
// ContainsCol checks if a column list contains a specific column.
|
|
func ContainsCol(cols postgres.ColumnList, col postgres.Column) bool {
|
|
return slices.Contains(cols, col)
|
|
}
|
|
|
|
// DestName returns the name of the type passed as `destTypeStruct` as a string,
|
|
// normalized for compatibility with the Jet QRM.
|
|
func DestName(destTypeStruct any, path ...string) string {
|
|
return dbxshared.DestName(destTypeStruct, path...)
|
|
}
|
|
|
|
type _postgresLogger struct{}
|
|
|
|
func (_postgresLogger) InitLogger() {
|
|
postgres.SetQueryLogger(func(ctx context.Context, queryInfo postgres.QueryInfo) {
|
|
_, args := queryInfo.Statement.Sql()
|
|
dbx.ModuleDB().Logger().Debug(
|
|
"Executed SQL query",
|
|
"args", args,
|
|
"duration", queryInfo.Duration,
|
|
"rows", queryInfo.RowsProcessed,
|
|
"err", queryInfo.Err,
|
|
)
|
|
|
|
lines := strings.Split(queryInfo.Statement.DebugSql(), "\n")
|
|
for i, line := range lines {
|
|
fmt.Printf("%s\t%s\n", color.CyanString(fmt.Sprintf("%03d", i)), line)
|
|
}
|
|
})
|
|
}
|