Push the rest
This commit is contained in:
41
backend/analytics/internal/db/mssql.go
Normal file
41
backend/analytics/internal/db/mssql.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
_ "github.com/microsoft/go-mssqldb"
|
||||
)
|
||||
|
||||
// Open creates an MSSQL connection pool and validates connectivity.
|
||||
func Open(ctx context.Context, dsn, name string) (*sql.DB, error) {
|
||||
pool, err := sql.Open("sqlserver", dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open %s: %w", name, err)
|
||||
}
|
||||
pool.SetMaxOpenConns(15)
|
||||
pool.SetMaxIdleConns(5)
|
||||
if err := pool.PingContext(ctx); err != nil {
|
||||
return nil, fmt.Errorf("ping %s: %w", name, err)
|
||||
}
|
||||
slog.Info("mssql connected", "db", name)
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
// QueryFirst runs each SQL query in order, returning rows from the first one
|
||||
// that succeeds. Used for schema-fallback queries.
|
||||
func QueryFirst(ctx context.Context, pool *sql.DB, queries []string) (*sql.Rows, error) {
|
||||
var lastErr error
|
||||
for _, q := range queries {
|
||||
rows, err := pool.QueryContext(ctx, q)
|
||||
if err != nil {
|
||||
slog.Warn("query variant failed, trying next", "err", err)
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
return nil, fmt.Errorf("all query variants failed: %w", lastErr)
|
||||
}
|
||||
28
backend/analytics/internal/db/postgres.go
Normal file
28
backend/analytics/internal/db/postgres.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// OpenPostgres creates a pgx connection pool and validates connectivity.
|
||||
func OpenPostgres(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
|
||||
cfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse postgres DSN: %w", err)
|
||||
}
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create postgres pool: %w", err)
|
||||
}
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping postgres: %w", err)
|
||||
}
|
||||
slog.Info("postgres connected", "max_conns", cfg.MaxConns)
|
||||
return pool, nil
|
||||
}
|
||||
Reference in New Issue
Block a user