From deb603caacaad3776196476493db410bd7df57d4 Mon Sep 17 00:00:00 2001 From: Dmitry Anderson <4nd3r5z0n@gmail.com> Date: Wed, 13 Nov 2024 17:54:19 +0100 Subject: [PATCH] new pg utils features --- lecense.txt => license.txt | 0 pg/pg.go | 61 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) rename lecense.txt => license.txt (100%) diff --git a/lecense.txt b/license.txt similarity index 100% rename from lecense.txt rename to license.txt diff --git a/pg/pg.go b/pg/pg.go index 3d92b49..517a31b 100644 --- a/pg/pg.go +++ b/pg/pg.go @@ -2,13 +2,18 @@ package pgUtils import ( "context" + "fmt" "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgxpool" "github.com/matchsystems/werr" + "strings" ) type PgxQuerier interface { Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) + QueryRow(ctx context.Context, sql string, args ...any) pgx.Row + Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) } // Query executes query on a provided querier and tries to parse db response @@ -48,3 +53,59 @@ func Tx(ctx context.Context, db *pgxpool.Pool, exec func(ctx context.Context, tx } return tx.Commit(ctx) } + +// SqlInsertMultiple Returns an SQL query to insert multiple items into a table +func SqlInsertMultiple(tableName string, columnNames []string, itemsCount int) string { + columnsCount := len(columnNames) + query := strings.Builder{} + query.WriteString("INSERT INTO ") + query.WriteString(tableName) + query.WriteString(" (") + query.WriteString(strings.Join(columnNames, ",")) + query.WriteString(") VALUES ") + + for item := 0; item < itemsCount; item++ { + query.WriteByte('(') + for column := 0; column < columnsCount; column++ { + query.WriteString(fmt.Sprintf("$%d", item*columnsCount+column)) + if column != columnsCount-1 { + query.WriteString(", ") + } + } + query.WriteByte(')') + if item != itemsCount-1 { + query.WriteByte(',') + } + } + + return query.String() +} + +// InsertMultiple Inserts multiple items into a specified table +func InsertMultiple(ctx context.Context, db PgxQuerier, tableName string, columnNames []string, items [][]any) (pgconn.CommandTag, error) { + query := SqlInsertMultiple(tableName, columnNames, len(items)) + itemsJoined := make([]any, 0) + for _, item := range items { + itemsJoined = append(itemsJoined, item...) + } + return db.Exec(ctx, query, itemsJoined...) +} + +// SqlOrder returns "ASC" | "DESC" +// depending on asc param +func SqlOrder(asc bool) string { + if asc { + return "ASC" + } + return "DESC" +} + +func SqlOrderLimit(orderBy string, asc bool, limit int64, offset int64) string { + query := strings.Builder{} + query.WriteString("ORDER BY ") + query.WriteString(orderBy) + query.WriteByte(' ') + query.WriteString(SqlOrder(asc)) + query.WriteString(fmt.Sprintf("LIMIT %d OFFSET %d", limit, offset)) + return query.String() +}