2020-08-06 20:58:47 +03:00
|
|
|
// Package postgres implements the sq driver for postgres.
|
|
|
|
package postgres
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"database/sql"
|
|
|
|
"fmt"
|
2023-08-12 21:54:14 +03:00
|
|
|
"log/slog"
|
2020-08-06 20:58:47 +03:00
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
|
2023-11-20 04:06:36 +03:00
|
|
|
pgx "github.com/jackc/pgx/v5"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"github.com/jackc/pgx/v5/stdlib"
|
2023-11-19 03:05:48 +03:00
|
|
|
"github.com/xo/dburl"
|
|
|
|
|
|
|
|
"github.com/neilotoole/sq/libsq/ast"
|
2023-04-07 11:00:49 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/ast/render"
|
2020-08-23 13:42:15 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/core/errz"
|
2023-11-20 04:06:36 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/core/jointype"
|
2020-08-23 13:42:15 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/core/kind"
|
2023-11-20 04:06:36 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/core/lg"
|
|
|
|
"github.com/neilotoole/sq/libsq/core/lg/lga"
|
|
|
|
"github.com/neilotoole/sq/libsq/core/lg/lgm"
|
|
|
|
"github.com/neilotoole/sq/libsq/core/options"
|
|
|
|
"github.com/neilotoole/sq/libsq/core/record"
|
|
|
|
"github.com/neilotoole/sq/libsq/core/retry"
|
2020-08-23 22:00:13 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/core/sqlmodel"
|
2020-08-23 13:42:15 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/core/sqlz"
|
|
|
|
"github.com/neilotoole/sq/libsq/core/stringz"
|
2023-11-20 04:06:36 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/core/tablefq"
|
2020-08-06 20:58:47 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/driver"
|
2023-11-20 04:06:36 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/driver/dialect"
|
2020-08-06 20:58:47 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/source"
|
2023-11-21 00:42:38 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/source/drivertype"
|
|
|
|
"github.com/neilotoole/sq/libsq/source/metadata"
|
2020-08-06 20:58:47 +03:00
|
|
|
)
|
|
|
|
|
2023-11-19 03:05:48 +03:00
|
|
|
// Type is the postgres source driver type.
|
2023-11-21 00:42:38 +03:00
|
|
|
const Type = drivertype.Type("postgres")
|
2020-08-06 20:58:47 +03:00
|
|
|
|
|
|
|
// Provider is the postgres implementation of driver.Provider.
|
|
|
|
type Provider struct {
|
2023-04-30 17:18:56 +03:00
|
|
|
Log *slog.Logger
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// DriverFor implements driver.Provider.
|
2023-11-21 00:42:38 +03:00
|
|
|
func (p *Provider) DriverFor(typ drivertype.Type) (driver.Driver, error) {
|
2020-08-06 20:58:47 +03:00
|
|
|
if typ != Type {
|
2023-04-02 22:49:45 +03:00
|
|
|
return nil, errz.Errorf("unsupported driver type {%s}", typ)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2023-04-30 17:18:56 +03:00
|
|
|
return &driveri{log: p.Log}, nil
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2023-06-13 19:06:18 +03:00
|
|
|
var _ driver.SQLDriver = (*driveri)(nil)
|
|
|
|
|
2020-08-13 06:40:03 +03:00
|
|
|
// driveri is the postgres implementation of driver.Driver.
|
|
|
|
type driveri struct {
|
2023-04-30 17:18:56 +03:00
|
|
|
log *slog.Logger
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2023-06-13 19:06:18 +03:00
|
|
|
// ConnParams implements driver.SQLDriver.
|
|
|
|
func (d *driveri) ConnParams() map[string][]string {
|
|
|
|
// https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS
|
|
|
|
return map[string][]string{
|
|
|
|
"channel_binding": {"prefer", "require", "disable"},
|
|
|
|
"connect_timeout": {"2"},
|
|
|
|
"application_name": nil,
|
|
|
|
"fallback_application_name": nil,
|
|
|
|
"gssencmode": {"disable", "prefer", "require"},
|
|
|
|
"sslmode": {"disable", "allow", "prefer", "require", "verify-ca", "verify-full"},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-22 18:08:14 +03:00
|
|
|
// ErrWrapFunc implements driver.SQLDriver.
|
|
|
|
func (d *driveri) ErrWrapFunc() func(error) error {
|
|
|
|
return errw
|
|
|
|
}
|
|
|
|
|
2020-08-06 20:58:47 +03:00
|
|
|
// DriverMetadata implements driver.Driver.
|
2020-08-13 06:40:03 +03:00
|
|
|
func (d *driveri) DriverMetadata() driver.Metadata {
|
2020-08-06 20:58:47 +03:00
|
|
|
return driver.Metadata{
|
|
|
|
Type: Type,
|
|
|
|
Description: "PostgreSQL",
|
|
|
|
Doc: "https://github.com/jackc/pgx",
|
|
|
|
IsSQL: true,
|
2023-06-13 19:06:18 +03:00
|
|
|
DefaultPort: 5432,
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Dialect implements driver.SQLDriver.
|
2023-04-07 11:00:49 +03:00
|
|
|
func (d *driveri) Dialect() dialect.Dialect {
|
|
|
|
return dialect.Dialect{
|
2020-08-12 21:24:01 +03:00
|
|
|
Type: Type,
|
|
|
|
Placeholders: placeholders,
|
2023-04-07 11:00:49 +03:00
|
|
|
Enquote: stringz.DoubleQuote,
|
2020-08-12 21:24:01 +03:00
|
|
|
MaxBatchValues: 1000,
|
2023-04-07 11:00:49 +03:00
|
|
|
Ops: dialect.DefaultOps(),
|
2023-07-03 18:34:19 +03:00
|
|
|
Joins: jointype.All(),
|
2023-11-19 03:05:48 +03:00
|
|
|
Catalog: true,
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-12 21:24:01 +03:00
|
|
|
func placeholders(numCols, numRows int) string {
|
|
|
|
rows := make([]string, numRows)
|
2020-08-06 20:58:47 +03:00
|
|
|
|
2020-08-12 21:24:01 +03:00
|
|
|
n := 1
|
2020-08-06 20:58:47 +03:00
|
|
|
var sb strings.Builder
|
2020-08-12 21:24:01 +03:00
|
|
|
for i := 0; i < numRows; i++ {
|
|
|
|
sb.Reset()
|
|
|
|
sb.WriteRune('(')
|
|
|
|
for j := 1; j <= numCols; j++ {
|
|
|
|
sb.WriteRune('$')
|
|
|
|
sb.WriteString(strconv.Itoa(n))
|
|
|
|
n++
|
|
|
|
if j < numCols {
|
|
|
|
sb.WriteString(driver.Comma)
|
|
|
|
}
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
2020-08-12 21:24:01 +03:00
|
|
|
sb.WriteRune(')')
|
|
|
|
rows[i] = sb.String()
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
2020-08-12 21:24:01 +03:00
|
|
|
|
|
|
|
return strings.Join(rows, driver.Comma)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2023-04-07 11:00:49 +03:00
|
|
|
// Renderer implements driver.SQLDriver.
|
|
|
|
func (d *driveri) Renderer() *render.Renderer {
|
2023-11-19 03:05:48 +03:00
|
|
|
r := render.NewDefaultRenderer()
|
|
|
|
r.FunctionNames[ast.FuncNameSchema] = "current_schema"
|
|
|
|
r.FunctionNames[ast.FuncNameCatalog] = "current_database"
|
|
|
|
return r
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2024-01-15 04:45:34 +03:00
|
|
|
// Open implements driver.Driver.
|
|
|
|
func (d *driveri) Open(ctx context.Context, src *source.Source) (driver.Grip, error) {
|
2023-05-03 15:36:10 +03:00
|
|
|
lg.FromContext(ctx).Debug(lgm.OpenSrc, lga.Src, src)
|
2023-04-30 17:18:56 +03:00
|
|
|
|
|
|
|
db, err := d.doOpen(ctx, src)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2023-05-22 18:08:14 +03:00
|
|
|
if err = driver.OpeningPing(ctx, src, db); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2024-01-15 04:45:34 +03:00
|
|
|
return &grip{log: d.log, db: db, src: src, drvr: d}, nil
|
2023-04-30 17:18:56 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (d *driveri) doOpen(ctx context.Context, src *source.Source) (*sql.DB, error) {
|
2023-11-19 03:05:48 +03:00
|
|
|
log := lg.FromContext(ctx)
|
2023-05-03 15:36:10 +03:00
|
|
|
ctx = options.NewContext(ctx, src.Options)
|
2023-04-08 21:09:27 +03:00
|
|
|
dbCfg, err := pgxpool.ParseConfig(src.Location)
|
2020-08-06 20:58:47 +03:00
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2023-11-19 03:05:48 +03:00
|
|
|
if src.Catalog != "" && src.Catalog != dbCfg.ConnConfig.Database {
|
|
|
|
// The catalog differs from the database in the connection string.
|
|
|
|
// OOTB, Postgres doesn't support cross-database references. So,
|
|
|
|
// we'll need to change the connection string to use the catalog
|
|
|
|
// as the database. Note that we don't modify src.Location, but it's
|
|
|
|
// not entirely clear if that's the correct approach. Are there any
|
|
|
|
// downsides to modifying it (as long as the modified Location is not
|
|
|
|
// persisted back to config)?
|
|
|
|
var u *dburl.URL
|
|
|
|
if u, err = dburl.Parse(src.Location); err != nil {
|
|
|
|
return nil, errw(err)
|
|
|
|
}
|
2023-04-30 17:18:56 +03:00
|
|
|
|
2023-11-19 03:05:48 +03:00
|
|
|
u.Path = src.Catalog
|
|
|
|
connStr := u.String()
|
|
|
|
dbCfg, err = pgxpool.ParseConfig(connStr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errw(err)
|
2023-04-30 17:18:56 +03:00
|
|
|
}
|
2023-11-19 03:05:48 +03:00
|
|
|
log.Debug("Using catalog as database in connection string",
|
|
|
|
lga.Src, src,
|
|
|
|
lga.Catalog, src.Catalog,
|
|
|
|
lga.Conn, source.RedactLocation(connStr),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
var opts []stdlib.OptionOpenDB
|
|
|
|
if src.Schema != "" {
|
|
|
|
opts = append(opts, stdlib.OptionAfterConnect(func(ctx context.Context, conn *pgx.Conn) error {
|
|
|
|
var oldSearchPath string
|
|
|
|
if err = conn.QueryRow(ctx, "SHOW search_path").Scan(&oldSearchPath); err != nil {
|
|
|
|
return errw(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
newSearchPath := stringz.DoubleQuote(src.Schema)
|
|
|
|
if oldSearchPath != "" {
|
|
|
|
newSearchPath += ", " + oldSearchPath
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Debug("Setting default schema (search_path) on Postgres DB connection",
|
|
|
|
lga.Src, src,
|
|
|
|
lga.Conn, source.RedactLocation(dbCfg.ConnString()),
|
|
|
|
lga.Catalog, src.Catalog,
|
|
|
|
lga.Schema, src.Schema,
|
|
|
|
lga.Old, oldSearchPath,
|
|
|
|
lga.New, newSearchPath)
|
|
|
|
|
|
|
|
_, err = conn.Exec(ctx, "SET search_path TO "+newSearchPath)
|
|
|
|
return errw(err)
|
|
|
|
}))
|
2023-04-08 21:09:27 +03:00
|
|
|
}
|
|
|
|
|
2024-01-15 04:45:34 +03:00
|
|
|
dbCfg.ConnConfig.ConnectTimeout = driver.OptConnOpenTimeout.Get(src.Options)
|
|
|
|
|
2023-11-19 03:05:48 +03:00
|
|
|
db := stdlib.OpenDB(*dbCfg.ConnConfig, opts...)
|
2023-04-30 17:18:56 +03:00
|
|
|
driver.ConfigureDB(ctx, db, src.Options)
|
2023-11-19 03:05:48 +03:00
|
|
|
|
2023-04-30 17:18:56 +03:00
|
|
|
return db, nil
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// ValidateSource implements driver.Driver.
|
2020-08-13 06:40:03 +03:00
|
|
|
func (d *driveri) ValidateSource(src *source.Source) (*source.Source, error) {
|
2020-08-06 20:58:47 +03:00
|
|
|
if src.Type != Type {
|
2023-04-22 06:36:32 +03:00
|
|
|
return nil, errz.Errorf("expected driver type {%s} but got {%s}", Type, src.Type)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
return src, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ping implements driver.Driver.
|
2020-08-13 06:40:03 +03:00
|
|
|
func (d *driveri) Ping(ctx context.Context, src *source.Source) error {
|
2023-05-22 18:08:14 +03:00
|
|
|
db, err := d.doOpen(ctx, src)
|
2020-08-06 20:58:47 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-05-22 18:08:14 +03:00
|
|
|
defer lg.WarnIfCloseError(d.log, lgm.CloseDB, db)
|
2020-08-06 20:58:47 +03:00
|
|
|
|
2023-05-22 18:08:14 +03:00
|
|
|
return errz.Wrapf(db.PingContext(ctx), "ping %s", src.Handle)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2023-05-19 17:24:18 +03:00
|
|
|
// DBProperties implements driver.SQLDriver.
|
|
|
|
func (d *driveri) DBProperties(ctx context.Context, db sqlz.DB) (map[string]any, error) {
|
|
|
|
return getPgSettings(ctx, db)
|
|
|
|
}
|
|
|
|
|
2020-08-06 20:58:47 +03:00
|
|
|
// Truncate implements driver.Driver.
|
2020-11-25 08:12:15 +03:00
|
|
|
// Note that Truncate makes a separate query to determine the
|
|
|
|
// row count of tbl before executing TRUNCATE. This row count
|
|
|
|
// query is not part of a transaction with TRUNCATE, although
|
|
|
|
// possibly it should be, as the number of rows may have changed.
|
2022-12-18 05:43:53 +03:00
|
|
|
func (d *driveri) Truncate(ctx context.Context, src *source.Source, tbl string, reset bool) (affected int64,
|
2022-12-18 11:35:59 +03:00
|
|
|
err error,
|
|
|
|
) {
|
2020-08-06 20:58:47 +03:00
|
|
|
// https://www.postgresql.org/docs/9.1/sql-truncate.html
|
|
|
|
|
|
|
|
// RESTART IDENTITY and CASCADE/RESTRICT are from pg 8.2 onwards
|
2022-12-18 08:16:10 +03:00
|
|
|
// FIXME: should first check the pg version for < pg8.2 support
|
2023-04-30 17:18:56 +03:00
|
|
|
db, err := d.doOpen(ctx, src)
|
2020-08-06 20:58:47 +03:00
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return affected, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2022-12-18 08:16:10 +03:00
|
|
|
affectedQuery := "SELECT COUNT(*) FROM " + idSanitize(tbl)
|
2020-11-25 08:12:15 +03:00
|
|
|
err = db.QueryRowContext(ctx, affectedQuery).Scan(&affected)
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return 0, errw(err)
|
2020-11-25 08:12:15 +03:00
|
|
|
}
|
|
|
|
|
2022-12-18 08:16:10 +03:00
|
|
|
truncateQuery := "TRUNCATE TABLE " + idSanitize(tbl)
|
|
|
|
if reset {
|
|
|
|
// if reset & src.DBVersion >= 8.2
|
|
|
|
truncateQuery += " RESTART IDENTITY" // default is CONTINUE IDENTITY
|
|
|
|
}
|
|
|
|
// We could add RESTRICT here; alternative is CASCADE
|
2020-11-25 08:12:15 +03:00
|
|
|
_, err = db.ExecContext(ctx, truncateQuery)
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return 0, errw(err)
|
2020-11-25 08:12:15 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return affected, nil
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2022-12-18 08:16:10 +03:00
|
|
|
// idSanitize sanitizes an identifier (such as table name). It will
|
|
|
|
// add surrounding quotes. For example:
|
|
|
|
//
|
|
|
|
// table_name --> "table_name"
|
|
|
|
func idSanitize(s string) string {
|
|
|
|
return pgx.Identifier([]string{s}).Sanitize()
|
|
|
|
}
|
|
|
|
|
2023-11-19 03:05:48 +03:00
|
|
|
// CreateSchema implements driver.SQLDriver.
|
|
|
|
func (d *driveri) CreateSchema(ctx context.Context, db sqlz.DB, schemaName string) error {
|
|
|
|
stmt := `CREATE SCHEMA ` + idSanitize(schemaName)
|
|
|
|
_, err := db.ExecContext(ctx, stmt)
|
|
|
|
return errz.Wrapf(err, "failed to create schema {%s}", schemaName)
|
|
|
|
}
|
|
|
|
|
|
|
|
// DropSchema implements driver.SQLDriver.
|
|
|
|
func (d *driveri) DropSchema(ctx context.Context, db sqlz.DB, schemaName string) error {
|
|
|
|
stmt := `DROP SCHEMA ` + idSanitize(schemaName) + ` CASCADE`
|
|
|
|
_, err := db.ExecContext(ctx, stmt)
|
|
|
|
return errz.Wrapf(err, "failed to drop schema {%s}", schemaName)
|
|
|
|
}
|
|
|
|
|
2020-08-06 20:58:47 +03:00
|
|
|
// CreateTable implements driver.SQLDriver.
|
2020-08-13 06:40:03 +03:00
|
|
|
func (d *driveri) CreateTable(ctx context.Context, db sqlz.DB, tblDef *sqlmodel.TableDef) error {
|
2020-08-06 20:58:47 +03:00
|
|
|
stmt := buildCreateTableStmt(tblDef)
|
|
|
|
|
|
|
|
_, err := db.ExecContext(ctx, stmt)
|
2023-05-22 18:08:14 +03:00
|
|
|
return errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2023-03-22 09:17:34 +03:00
|
|
|
// CurrentSchema implements driver.SQLDriver.
|
|
|
|
func (d *driveri) CurrentSchema(ctx context.Context, db sqlz.DB) (string, error) {
|
|
|
|
var name string
|
|
|
|
if err := db.QueryRowContext(ctx, `SELECT CURRENT_SCHEMA()`).Scan(&name); err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return "", errw(err)
|
2023-03-22 09:17:34 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return name, nil
|
|
|
|
}
|
|
|
|
|
2023-11-21 00:42:38 +03:00
|
|
|
// ListSchemas implements driver.SQLDriver. Some system schemas are
|
|
|
|
// excluded, e.g. pg_toast and pg_temp schemas.
|
2023-11-19 03:05:48 +03:00
|
|
|
func (d *driveri) ListSchemas(ctx context.Context, db sqlz.DB) ([]string, error) {
|
|
|
|
log := lg.FromContext(ctx)
|
|
|
|
|
2023-11-21 00:42:38 +03:00
|
|
|
const q = `SELECT schema_name FROM information_schema.schemata
|
|
|
|
WHERE schema_name NOT LIKE 'pg_toast%' AND schema_name NOT LIKE 'pg_temp%'
|
|
|
|
ORDER BY schema_name`
|
2023-11-19 03:05:48 +03:00
|
|
|
var schemas []string
|
|
|
|
rows, err := db.QueryContext(ctx, q)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errw(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
defer lg.WarnIfCloseError(log, lgm.CloseDBRows, rows)
|
|
|
|
|
|
|
|
for rows.Next() {
|
|
|
|
var schema string
|
|
|
|
if err = rows.Scan(&schema); err != nil {
|
|
|
|
return nil, errw(err)
|
|
|
|
}
|
|
|
|
schemas = append(schemas, schema)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err = rows.Err(); err != nil {
|
|
|
|
return nil, errw(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return schemas, nil
|
|
|
|
}
|
|
|
|
|
2023-11-21 00:42:38 +03:00
|
|
|
// ListSchemaMetadata implements driver.SQLDriver. Some system schemas are
|
|
|
|
// excluded, e.g. pg_toast and pg_temp schemas.
|
|
|
|
func (d *driveri) ListSchemaMetadata(ctx context.Context, db sqlz.DB) ([]*metadata.Schema, error) {
|
|
|
|
log := lg.FromContext(ctx)
|
|
|
|
|
|
|
|
const q = `SELECT schema_name, catalog_name, schema_owner FROM information_schema.schemata
|
|
|
|
WHERE catalog_name = current_database()
|
|
|
|
AND schema_name NOT LIKE 'pg_toast%' AND schema_name NOT LIKE 'pg_temp%'
|
|
|
|
ORDER BY schema_name`
|
|
|
|
var schemas []*metadata.Schema
|
|
|
|
rows, err := db.QueryContext(ctx, q)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errw(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
defer lg.WarnIfCloseError(log, lgm.CloseDBRows, rows)
|
|
|
|
|
|
|
|
var name string
|
|
|
|
var catalog, owner sql.NullString
|
|
|
|
|
|
|
|
for rows.Next() {
|
|
|
|
if err = rows.Scan(&name, &catalog, &owner); err != nil {
|
|
|
|
return nil, errw(err)
|
|
|
|
}
|
|
|
|
s := &metadata.Schema{
|
|
|
|
Name: name,
|
|
|
|
Catalog: catalog.String,
|
|
|
|
Owner: owner.String,
|
|
|
|
}
|
|
|
|
|
|
|
|
schemas = append(schemas, s)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err = rows.Err(); err != nil {
|
|
|
|
return nil, errw(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return schemas, nil
|
|
|
|
}
|
|
|
|
|
2023-11-19 03:05:48 +03:00
|
|
|
// CurrentCatalog implements driver.SQLDriver.
|
|
|
|
func (d *driveri) CurrentCatalog(ctx context.Context, db sqlz.DB) (string, error) {
|
|
|
|
var name string
|
|
|
|
if err := db.QueryRowContext(ctx, `SELECT CURRENT_DATABASE()`).Scan(&name); err != nil {
|
|
|
|
return "", errw(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return name, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// ListCatalogs implements driver.SQLDriver.
|
|
|
|
func (d *driveri) ListCatalogs(ctx context.Context, db sqlz.DB) ([]string, error) {
|
|
|
|
catalogs := make([]string, 1, 3)
|
|
|
|
if err := db.QueryRowContext(ctx, `SELECT CURRENT_DATABASE()`).Scan(&catalogs[0]); err != nil {
|
|
|
|
return nil, errw(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
const q = `SELECT datname FROM pg_catalog.pg_database
|
|
|
|
WHERE datistemplate = FALSE AND datallowconn = TRUE AND datname != CURRENT_DATABASE()
|
|
|
|
ORDER BY datname`
|
|
|
|
|
|
|
|
rows, err := db.QueryContext(ctx, q)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errw(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
defer lg.WarnIfCloseError(lg.FromContext(ctx), lgm.CloseDBRows, rows)
|
|
|
|
|
|
|
|
for rows.Next() {
|
|
|
|
var catalog string
|
|
|
|
if err = rows.Scan(&catalog); err != nil {
|
|
|
|
return nil, errw(err)
|
|
|
|
}
|
|
|
|
catalogs = append(catalogs, catalog)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err = rows.Err(); err != nil {
|
|
|
|
return nil, errw(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return catalogs, nil
|
|
|
|
}
|
|
|
|
|
2023-03-22 09:17:34 +03:00
|
|
|
// AlterTableRename implements driver.SQLDriver.
|
|
|
|
func (d *driveri) AlterTableRename(ctx context.Context, db sqlz.DB, tbl, newName string) error {
|
|
|
|
q := fmt.Sprintf(`ALTER TABLE %q RENAME TO %q`, tbl, newName)
|
|
|
|
_, err := db.ExecContext(ctx, q)
|
2023-05-22 18:08:14 +03:00
|
|
|
return errz.Wrapf(errw(err), "alter table: failed to rename table {%s} to {%s}", tbl, newName)
|
2023-03-22 09:17:34 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// AlterTableRenameColumn implements driver.SQLDriver.
|
|
|
|
func (d *driveri) AlterTableRenameColumn(ctx context.Context, db sqlz.DB, tbl, col, newName string) error {
|
|
|
|
q := fmt.Sprintf("ALTER TABLE %q RENAME COLUMN %q TO %q", tbl, col, newName)
|
|
|
|
_, err := db.ExecContext(ctx, q)
|
2023-05-22 18:08:14 +03:00
|
|
|
return errz.Wrapf(errw(err), "alter table: failed to rename column {%s.%s} to {%s}", tbl, col, newName)
|
2023-03-22 09:17:34 +03:00
|
|
|
}
|
|
|
|
|
2020-08-21 06:08:59 +03:00
|
|
|
// AlterTableAddColumn implements driver.SQLDriver.
|
2023-03-22 09:17:34 +03:00
|
|
|
func (d *driveri) AlterTableAddColumn(ctx context.Context, db sqlz.DB, tbl, col string, knd kind.Kind) error {
|
2020-11-25 08:12:15 +03:00
|
|
|
q := fmt.Sprintf("ALTER TABLE %q ADD COLUMN %q ", tbl, col) + dbTypeNameFromKind(knd)
|
2020-08-21 06:08:59 +03:00
|
|
|
|
|
|
|
_, err := db.ExecContext(ctx, q)
|
|
|
|
if err != nil {
|
2023-04-02 22:49:45 +03:00
|
|
|
return errz.Wrapf(err, "alter table: failed to add column {%s} to table {%s}", col, tbl)
|
2020-08-21 06:08:59 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-08-06 20:58:47 +03:00
|
|
|
// PrepareInsertStmt implements driver.SQLDriver.
|
2022-12-18 05:43:53 +03:00
|
|
|
func (d *driveri) PrepareInsertStmt(ctx context.Context, db sqlz.DB, destTbl string, destColNames []string,
|
2022-12-18 11:35:59 +03:00
|
|
|
numRows int,
|
|
|
|
) (*driver.StmtExecer, error) {
|
2020-08-06 20:58:47 +03:00
|
|
|
// Note that the pgx driver doesn't support res.LastInsertId.
|
|
|
|
// https://github.com/jackc/pgx/issues/411
|
|
|
|
|
|
|
|
destColsMeta, err := d.getTableRecordMeta(ctx, db, destTbl, destColNames)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2020-08-12 21:24:01 +03:00
|
|
|
stmt, err := driver.PrepareInsertStmt(ctx, d, db, destTbl, destColsMeta.Names(), numRows)
|
2020-08-06 20:58:47 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2022-12-18 05:43:53 +03:00
|
|
|
execer := driver.NewStmtExecer(stmt, driver.DefaultInsertMungeFunc(destTbl, destColsMeta), newStmtExecFunc(stmt),
|
|
|
|
destColsMeta)
|
2020-08-06 20:58:47 +03:00
|
|
|
return execer, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// PrepareUpdateStmt implements driver.SQLDriver.
|
2022-12-18 05:43:53 +03:00
|
|
|
func (d *driveri) PrepareUpdateStmt(ctx context.Context, db sqlz.DB, destTbl string, destColNames []string,
|
2022-12-18 11:35:59 +03:00
|
|
|
where string,
|
|
|
|
) (*driver.StmtExecer, error) {
|
2020-08-06 20:58:47 +03:00
|
|
|
destColsMeta, err := d.getTableRecordMeta(ctx, db, destTbl, destColNames)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
query, err := buildUpdateStmt(destTbl, destColNames, where)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
stmt, err := db.PrepareContext(ctx, query)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2022-12-18 05:43:53 +03:00
|
|
|
execer := driver.NewStmtExecer(stmt, driver.DefaultInsertMungeFunc(destTbl, destColsMeta), newStmtExecFunc(stmt),
|
|
|
|
destColsMeta)
|
2020-08-06 20:58:47 +03:00
|
|
|
return execer, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func newStmtExecFunc(stmt *sql.Stmt) driver.StmtExecFunc {
|
2022-12-17 02:34:33 +03:00
|
|
|
return func(ctx context.Context, args ...any) (int64, error) {
|
2020-08-06 20:58:47 +03:00
|
|
|
res, err := stmt.ExecContext(ctx, args...)
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return 0, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
affected, err := res.RowsAffected()
|
2023-05-22 18:08:14 +03:00
|
|
|
return affected, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// CopyTable implements driver.SQLDriver.
|
2023-11-19 03:05:48 +03:00
|
|
|
func (d *driveri) CopyTable(ctx context.Context, db sqlz.DB,
|
|
|
|
fromTable, toTable tablefq.T, copyData bool,
|
|
|
|
) (int64, error) {
|
|
|
|
stmt := fmt.Sprintf(
|
|
|
|
"CREATE TABLE %s AS TABLE %s",
|
|
|
|
tblfmt(toTable),
|
|
|
|
tblfmt(fromTable),
|
|
|
|
)
|
2020-08-06 20:58:47 +03:00
|
|
|
|
|
|
|
if !copyData {
|
|
|
|
stmt += " WITH NO DATA"
|
|
|
|
}
|
|
|
|
|
2021-02-22 10:37:00 +03:00
|
|
|
affected, err := sqlz.ExecAffected(ctx, db, stmt)
|
2020-08-06 20:58:47 +03:00
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return 0, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return affected, nil
|
|
|
|
}
|
|
|
|
|
2021-01-04 05:56:22 +03:00
|
|
|
// TableExists implements driver.SQLDriver.
|
|
|
|
func (d *driveri) TableExists(ctx context.Context, db sqlz.DB, tbl string) (bool, error) {
|
|
|
|
const query = `SELECT COUNT(*) FROM information_schema.tables
|
|
|
|
WHERE table_name = $1`
|
|
|
|
|
|
|
|
var count int64
|
|
|
|
err := db.QueryRowContext(ctx, query, tbl).Scan(&count)
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return false, errw(err)
|
2021-01-04 05:56:22 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return count == 1, nil
|
|
|
|
}
|
|
|
|
|
2020-08-06 20:58:47 +03:00
|
|
|
// DropTable implements driver.SQLDriver.
|
2023-11-19 03:05:48 +03:00
|
|
|
func (d *driveri) DropTable(ctx context.Context, db sqlz.DB, tbl tablefq.T, ifExists bool) error {
|
2020-08-06 20:58:47 +03:00
|
|
|
var stmt string
|
|
|
|
|
|
|
|
if ifExists {
|
2023-11-19 03:05:48 +03:00
|
|
|
stmt = fmt.Sprintf("DROP TABLE IF EXISTS %s RESTRICT", tblfmt(tbl))
|
2020-08-06 20:58:47 +03:00
|
|
|
} else {
|
2023-11-19 03:05:48 +03:00
|
|
|
stmt = fmt.Sprintf("DROP TABLE %s RESTRICT", tblfmt(tbl))
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
_, err := db.ExecContext(ctx, stmt)
|
2023-05-22 18:08:14 +03:00
|
|
|
return errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// TableColumnTypes implements driver.SQLDriver.
|
2022-12-18 05:43:53 +03:00
|
|
|
func (d *driveri) TableColumnTypes(ctx context.Context, db sqlz.DB, tblName string,
|
2022-12-18 11:35:59 +03:00
|
|
|
colNames []string,
|
|
|
|
) ([]*sql.ColumnType, error) {
|
2020-08-06 20:58:47 +03:00
|
|
|
// We have to do some funky stuff to get the column types
|
|
|
|
// from when the table has no rows.
|
|
|
|
// https://stackoverflow.com/questions/8098795/return-a-value-if-no-record-is-found
|
|
|
|
|
|
|
|
// If tblName is "person" and we want cols "username"
|
|
|
|
// and "email", the query will look like:
|
|
|
|
//
|
|
|
|
// SELECT
|
|
|
|
// (SELECT username FROM person LIMIT 1) AS username,
|
|
|
|
// (SELECT email FROM person LIMIT 1) AS email
|
|
|
|
// LIMIT 1;
|
2023-07-03 18:34:19 +03:00
|
|
|
|
|
|
|
enquote := d.Dialect().Enquote
|
|
|
|
tblNameQuoted := enquote(tblName)
|
2020-08-06 20:58:47 +03:00
|
|
|
|
|
|
|
var query string
|
|
|
|
|
|
|
|
if len(colNames) == 0 {
|
|
|
|
// When the table is empty, and colNames are not provided,
|
|
|
|
// then we need to fetch the table col names independently.
|
|
|
|
var err error
|
2023-04-02 22:49:45 +03:00
|
|
|
colNames, err = getTableColumnNames(ctx, db, tblName)
|
2020-08-06 20:58:47 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var sb strings.Builder
|
|
|
|
sb.WriteString("SELECT\n")
|
|
|
|
for i, colName := range colNames {
|
2023-07-03 18:34:19 +03:00
|
|
|
colNameQuoted := enquote(colName)
|
2020-08-06 20:58:47 +03:00
|
|
|
sb.WriteString(fmt.Sprintf(" (SELECT %s FROM %s LIMIT 1) AS %s", colNameQuoted, tblNameQuoted, colNameQuoted))
|
|
|
|
if i < len(colNames)-1 {
|
|
|
|
sb.WriteRune(',')
|
|
|
|
}
|
|
|
|
sb.WriteString("\n")
|
|
|
|
}
|
|
|
|
sb.WriteString("LIMIT 1")
|
|
|
|
query = sb.String()
|
|
|
|
|
|
|
|
rows, err := db.QueryContext(ctx, query)
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
colTypes, err := rows.ColumnTypes()
|
|
|
|
if err != nil {
|
2023-04-02 22:49:45 +03:00
|
|
|
lg.WarnIfFuncError(d.log, lgm.CloseDBRows, rows.Close)
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
err = rows.Err()
|
|
|
|
if err != nil {
|
2023-04-02 22:49:45 +03:00
|
|
|
lg.WarnIfFuncError(d.log, lgm.CloseDBRows, rows.Close)
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
err = rows.Close()
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return colTypes, nil
|
|
|
|
}
|
|
|
|
|
2023-07-09 04:34:53 +03:00
|
|
|
func (d *driveri) getTableRecordMeta(ctx context.Context, db sqlz.DB, tblName string, colNames []string) (
|
|
|
|
record.Meta, error,
|
|
|
|
) {
|
2020-08-06 20:58:47 +03:00
|
|
|
colTypes, err := d.TableColumnTypes(ctx, db, tblName, colNames)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2023-07-03 18:34:19 +03:00
|
|
|
destCols, _, err := d.RecordMeta(ctx, colTypes)
|
2020-08-06 20:58:47 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return destCols, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// getTableColumnNames consults postgres's information_schema.columns table,
|
2023-04-02 22:49:45 +03:00
|
|
|
// returning the names of the table's columns in ordinal order.
|
|
|
|
func getTableColumnNames(ctx context.Context, db sqlz.DB, tblName string) ([]string, error) {
|
2023-05-03 15:36:10 +03:00
|
|
|
log := lg.FromContext(ctx)
|
2020-08-06 20:58:47 +03:00
|
|
|
const query = `SELECT column_name FROM information_schema.columns
|
2023-03-22 09:17:34 +03:00
|
|
|
WHERE table_schema = CURRENT_SCHEMA()
|
2020-08-06 20:58:47 +03:00
|
|
|
AND table_name = $1
|
|
|
|
ORDER BY ordinal_position`
|
|
|
|
|
|
|
|
rows, err := db.QueryContext(ctx, query, tblName)
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
var colNames []string
|
|
|
|
var colName string
|
|
|
|
|
|
|
|
for rows.Next() {
|
|
|
|
err = rows.Scan(&colName)
|
|
|
|
if err != nil {
|
2023-04-02 22:49:45 +03:00
|
|
|
lg.WarnIfCloseError(log, lgm.CloseDBRows, rows)
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
colNames = append(colNames, colName)
|
|
|
|
}
|
|
|
|
|
|
|
|
if rows.Err() != nil {
|
2023-04-02 22:49:45 +03:00
|
|
|
lg.WarnIfCloseError(log, lgm.CloseDBRows, rows)
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
err = rows.Close()
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return colNames, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// RecordMeta implements driver.SQLDriver.
|
2023-07-09 04:34:53 +03:00
|
|
|
func (d *driveri) RecordMeta(ctx context.Context, colTypes []*sql.ColumnType) (
|
|
|
|
record.Meta, driver.NewRecordFunc, error,
|
2023-07-03 18:34:19 +03:00
|
|
|
) {
|
2020-08-06 20:58:47 +03:00
|
|
|
// The jackc/pgx driver doesn't report nullability (sql.ColumnType)
|
|
|
|
// Apparently this is due to what postgres sends over the wire.
|
|
|
|
// See https://github.com/jackc/pgx/issues/276#issuecomment-526831493
|
|
|
|
// So, we'll set the scan type for each column to the nullable
|
|
|
|
// version below.
|
|
|
|
|
2023-07-03 18:34:19 +03:00
|
|
|
sColTypeData := make([]*record.ColumnTypeData, len(colTypes))
|
|
|
|
ogColNames := make([]string, len(colTypes))
|
2020-08-06 20:58:47 +03:00
|
|
|
for i, colType := range colTypes {
|
2020-11-25 08:12:15 +03:00
|
|
|
knd := kindFromDBTypeName(d.log, colType.Name(), colType.DatabaseTypeName())
|
2023-05-22 18:08:14 +03:00
|
|
|
colTypeData := record.NewColumnTypeData(colType, knd)
|
2020-11-25 08:12:15 +03:00
|
|
|
setScanType(d.log, colTypeData, knd)
|
2023-07-03 18:34:19 +03:00
|
|
|
sColTypeData[i] = colTypeData
|
|
|
|
ogColNames[i] = colTypeData.Name
|
|
|
|
}
|
|
|
|
|
2023-07-04 20:31:47 +03:00
|
|
|
mungedColNames, err := driver.MungeResultColNames(ctx, ogColNames)
|
2023-07-03 18:34:19 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
recMeta := make(record.Meta, len(colTypes))
|
|
|
|
for i := range sColTypeData {
|
2023-07-09 04:34:53 +03:00
|
|
|
recMeta[i] = record.NewFieldMeta(sColTypeData[i], mungedColNames[i])
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2023-05-22 18:08:14 +03:00
|
|
|
mungeFn := func(vals []any) (record.Record, error) {
|
2020-08-06 20:58:47 +03:00
|
|
|
// postgres doesn't need to do any special munging, so we
|
|
|
|
// just use the default munging.
|
|
|
|
rec, skipped := driver.NewRecordFromScanRow(recMeta, vals, nil)
|
|
|
|
if len(skipped) > 0 {
|
|
|
|
var skippedDetails []string
|
|
|
|
|
|
|
|
for _, skip := range skipped {
|
|
|
|
meta := recMeta[skip]
|
|
|
|
skippedDetails = append(skippedDetails,
|
|
|
|
fmt.Sprintf("[%d] %s: db(%s) --> kind(%s) --> scan(%s)",
|
|
|
|
skip, meta.Name(), meta.DatabaseTypeName(), meta.Kind(), meta.ScanType()))
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, errz.Errorf("expected zero skipped cols but have %d:\n %s",
|
|
|
|
skipped, strings.Join(skippedDetails, "\n "))
|
|
|
|
}
|
|
|
|
return rec, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return recMeta, mungeFn, nil
|
|
|
|
}
|
|
|
|
|
2023-04-08 21:09:27 +03:00
|
|
|
// doRetry executes fn with retry on isErrTooManyConnections.
|
|
|
|
func doRetry(ctx context.Context, fn func() error) error {
|
2023-05-03 15:36:10 +03:00
|
|
|
maxRetryInterval := driver.OptMaxRetryInterval.Get(options.FromContext(ctx))
|
|
|
|
return retry.Do(ctx, maxRetryInterval, fn, isErrTooManyConnections)
|
2023-04-08 21:09:27 +03:00
|
|
|
}
|
2023-11-19 03:05:48 +03:00
|
|
|
|
|
|
|
// tblfmt formats a table name for use in a query. The arg can be a string,
|
|
|
|
// or a tablefq.T.
|
|
|
|
func tblfmt[T string | tablefq.T](tbl T) string {
|
|
|
|
tfq := tablefq.From(tbl)
|
|
|
|
return tfq.Render(stringz.DoubleQuote)
|
|
|
|
}
|