sql

package
v1.63.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 4, 2026 License: Apache-2.0 Imports: 25 Imported by: 1

Documentation

Overview

Package sql provides functionalities to interact with SQL databases using the database/sql package.This package includes a wrapper around sql.DB and sql.Tx to provide additional features such as query logging, metrics recording, and error handling.

Package sql is a generated GoMock package.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DeleteByQuery added in v1.6.0

func DeleteByQuery(dialect, tableName, field string) string

func InsertQuery added in v1.6.0

func InsertQuery(dialect, tableName string, fieldNames []string, values []any,
	constraints map[string]FieldConstraints) (string, error)

func IsSupabaseDialect added in v1.40.0

func IsSupabaseDialect(dialect string) bool

IsSupabaseDialect checks if the provided dialect is the Supabase dialect. Returns true if the dialect is "supabase", false otherwise.

func NewSQLMocks added in v1.3.0

func NewSQLMocks(t *testing.T) (*DB, sqlmock.Sqlmock, *MockMetrics)

func NewSQLMocksWithConfig added in v1.5.0

func NewSQLMocksWithConfig(t *testing.T, config *DBConfig) (*DB, sqlmock.Sqlmock, *MockMetrics)

func SelectByQuery added in v1.6.0

func SelectByQuery(dialect, tableName, field string) string

func SelectQuery added in v1.6.0

func SelectQuery(dialect, tableName string) string

func ToSnakeCase

func ToSnakeCase(str string) string

func UpdateByQuery added in v1.6.0

func UpdateByQuery(dialect, tableName string, fieldNames []string, field string) string

Types

type BindVarType added in v1.5.0

type BindVarType uint

BindVarType represents different type of bindvars in SQL queries.

const (
	UNKNOWN BindVarType = iota + 1
	QUESTION
	DOLLAR
)

type DB

type DB struct {
	// contains unexported or private fields
	*sql.DB
	// contains filtered or unexported fields
}

DB is a wrapper around sql.DB which provides some more features.

func NewSQL added in v0.2.0

func NewSQL(configs config.Config, logger datasource.Logger, metrics Metrics) *DB

func NewSQLFromConnector added in v1.57.0

func NewSQLFromConnector(connector driver.Connector, conf config.Config,
	logger datasource.Logger, metrics Metrics, cleanup func() error) *DB

NewSQLFromConnector wraps a driver.Connector in gofr's SQL datasource. It opens the connection with otelsql (so queries are traced, exactly as NewSQL does) and then shares the standard post-open path — query logging, metrics, health checks and the background retry/metrics goroutines — via NewSQLFromDB's finalize logic.

This is the seam for pluggable, connector-based SQL providers where credentials or routing are owned by the connector rather than a DSN: GCP Cloud SQL with IAM auth supplies a Cloud SQL connector; AWS RDS/Aurora IAM and Azure Entra ID can supply a token-minting connector the same way. Each such provider lives in its own module and constructs only the driver.Connector, so its cloud SDK stays out of core; core does the wrapping here. See gofr.dev/pkg/gofr/datasource/cloudsql.

conf supplies the dialect plus the labels and pool sizing used in logs, metrics and health output. cleanup, if non-nil, is run on Close to tear down resources database/sql does not own (for Cloud SQL, the connector's dialer and its background credential refresh). A nil connector returns nil.

func NewSQLFromDB added in v1.57.0

func NewSQLFromDB(db *sql.DB, conf *DBConfig, logger datasource.Logger, metrics Metrics) *DB

NewSQLFromDB wraps an already-opened *database/sql.DB in gofr's SQL datasource, adding query logging, metrics, health checks and the same background connection-retry/metrics goroutines used by NewSQL. Driver registration, DSN building and sql.Open are the caller's responsibility; this is the entry point for pluggable SQL datasources (for example GCP Cloud SQL with IAM auth) that are wired in via App.AddSQLDB.

conf supplies the dialect plus the labels and pool sizing used in logs, metrics and health output. A nil conf or db returns nil.

DB_REDACT_ARGS applies only to the SQL datasource GoFr creates from config; a connection passed to NewSQLFromDB does not have its query arguments redacted.

Because it accepts any opened *sql.DB, this is the provider-agnostic seam for managed-database authentication: GCP Cloud SQL passes a connector-backed handle, while AWS RDS/Aurora IAM and Azure Entra ID modules pass a sql.OpenDB(connector) whose connector mints a fresh short-lived token per connection. Each such provider lives in its own published module so its cloud SDK stays out of core. See gofr.dev/pkg/gofr/datasource/cloudsql for the reference implementation.

func NewSupabaseSQL added in v1.40.0

func NewSupabaseSQL(configs config.Config, logger datasource.Logger, metrics Metrics) *DB

NewSupabaseSQL creates a new DB instance configured for Supabase connectivity. It initializes a DB with Supabase-specific settings based on the provided configs. If Supabase dialect is not specified, it returns nil.

func (*DB) Begin

func (d *DB) Begin() (*Tx, error)

func (*DB) Close added in v1.16.0

func (d *DB) Close() error

Close stops the background connection-retry and metrics goroutines, waits for them to exit, then closes the pool and runs the datasource cleanup. An in-flight background ping is canceled, but a driver may ignore cancellation while connecting (lib/pq does), so the wait is bounded by closeWaitTimeout: Close always returns within it, logging a warning if a background connection attempt did not stop, and closes the pool regardless. That attempt then fails on the closed pool and exits. Only the first Close waits; a later one returns without waiting again.

func (*DB) Dialect added in v1.4.1

func (d *DB) Dialect() string

func (*DB) Exec

func (d *DB) Exec(query string, args ...any) (sql.Result, error)

func (*DB) ExecContext added in v1.1.1

func (d *DB) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)

func (*DB) HealthCheck

func (d *DB) HealthCheck() *datasource.Health

func (*DB) Prepare

func (d *DB) Prepare(query string) (*sql.Stmt, error)

func (*DB) Query

func (d *DB) Query(query string, args ...any) (*sql.Rows, error)

func (*DB) QueryContext added in v1.8.1

func (d *DB) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)

func (*DB) QueryRow

func (d *DB) QueryRow(query string, args ...any) *sql.Row

func (*DB) QueryRowContext

func (d *DB) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row

func (*DB) Select

func (d *DB) Select(ctx context.Context, data any, query string, args ...any)

Select runs a query with args and binds the result of the query to the data. data should be a point to a slice, struct or any type. Slice will return multiple objects whereas struct will return a single object.

Example Usages:

  1. Get multiple rows with only one column ids := make([]int, 0) db.Select(ctx, &ids, "select id from users")

  2. Get a single object from database type user struct { Name string ID int Image string } u := user{} db.Select(ctx, &u, "select * from users where id=?", 1)

  3. Get array of objects from multiple rows type user struct { Name string ID int Image string `db:"image_url"` } users := []user{} db.Select(ctx, &users, "select * from users")

type DBConfig

type DBConfig struct {
	Dialect     string
	HostName    string
	User        string
	Password    string
	Port        string
	Database    string
	SSLMode     string
	MaxIdleConn int
	MaxOpenConn int
	Charset     string
	// contains filtered or unexported fields
}

DBConfig has those members which are necessary variables while connecting to database.

func (DBConfig) GoString added in v1.57.0

func (c DBConfig) GoString() string

GoString implements fmt.GoStringer so that the %#v verb — which bypasses Stringer and would otherwise print the raw struct, password included — also redacts the password. It mirrors String's redaction so no formatting verb leaks the secret.

func (DBConfig) String added in v1.57.0

func (c DBConfig) String() string

String implements fmt.Stringer so that logging a DBConfig — directly or as part of a larger struct, with %v or %+v — never leaks the raw password. The Password field is redacted to a fixed mask while every other field is preserved, keeping the output useful for diagnosing connection issues.

type DBStats added in v0.2.0

type DBStats struct {
	MaxOpenConnections int `json:"maxOpenConnections"` // Maximum number of open connections to the database.

	// Pool Status
	OpenConnections int `json:"openConnections"` // The number of established connections both in use and idle.
	InUse           int `json:"inUse"`           // The number of connections currently in use.
	Idle            int `json:"idle"`            // The number of idle connections.

	// Counters
	WaitCount         int64         `json:"waitCount"`         // The total number of connections waited for.
	WaitDuration      time.Duration `json:"waitDuration"`      // The total time blocked waiting for a new connection.
	MaxIdleClosed     int64         `json:"maxIdleClosed"`     // The total number of connections closed due to SetMaxIdleConns.
	MaxIdleTimeClosed int64         `json:"maxIdleTimeClosed"` // The total number of connections closed due to SetConnMaxIdleTime.
	MaxLifetimeClosed int64         `json:"maxLifetimeClosed"` // The total number of connections closed due to SetConnMaxLifetime.
}

type FieldConstraints added in v1.18.0

type FieldConstraints struct {
	AutoIncrement bool
	NotNull       bool
}

type Log

type Log struct {
	Type     string `json:"type"`
	Query    string `json:"query"`
	Duration int64  `json:"duration"`
	Args     []any  `json:"args,omitempty"`
}

func (*Log) PrettyPrint added in v1.4.0

func (l *Log) PrettyPrint(writer io.Writer)

type Metrics added in v0.3.0

type Metrics interface {
	RecordHistogram(ctx context.Context, name string, value float64, labels ...string)
	SetGauge(name string, value float64, labels ...string)
}

type MockMetrics added in v1.1.1

type MockMetrics struct {
	// contains filtered or unexported fields
}

MockMetrics is a mock of Metrics interface.

func NewMockMetrics added in v1.1.1

func NewMockMetrics(ctrl *gomock.Controller) *MockMetrics

NewMockMetrics creates a new mock instance.

func (*MockMetrics) EXPECT added in v1.1.1

func (m *MockMetrics) EXPECT() *MockMetricsMockRecorder

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockMetrics) RecordHistogram added in v1.1.1

func (m *MockMetrics) RecordHistogram(ctx context.Context, name string, value float64, labels ...string)

RecordHistogram mocks base method.

func (*MockMetrics) SetGauge added in v1.1.1

func (m *MockMetrics) SetGauge(name string, value float64, labels ...string)

SetGauge mocks base method.

type MockMetricsMockRecorder added in v1.1.1

type MockMetricsMockRecorder struct {
	// contains filtered or unexported fields
}

MockMetricsMockRecorder is the mock recorder for MockMetrics.

func (*MockMetricsMockRecorder) RecordHistogram added in v1.1.1

func (mr *MockMetricsMockRecorder) RecordHistogram(ctx, name, value any, labels ...any) *gomock.Call

RecordHistogram indicates an expected call of RecordHistogram.

func (*MockMetricsMockRecorder) SetGauge added in v1.1.1

func (mr *MockMetricsMockRecorder) SetGauge(name, value any, labels ...any) *gomock.Call

SetGauge indicates an expected call of SetGauge.

type SupabaseConfig added in v1.40.0

type SupabaseConfig struct {
	*DBConfig
	ConnectionType string // direct, session, transaction
	ProjectRef     string // Supabase project reference
	Region         string // Supabase region
}

SupabaseConfig extends DBConfig to include Supabase-specific configuration.

func GetSupabaseConfig added in v1.40.0

func GetSupabaseConfig(configs config.Config) *SupabaseConfig

GetSupabaseConfig builds a Supabase configuration from general config. It extracts Supabase-specific settings from the provided configs object. If the database dialect is not supabase, it returns nil.

type Tx

type Tx struct {
	*sql.Tx
	// contains filtered or unexported fields
}

func (*Tx) Commit

func (t *Tx) Commit() error

func (*Tx) Exec

func (t *Tx) Exec(query string, args ...any) (sql.Result, error)

func (*Tx) ExecContext added in v1.1.1

func (t *Tx) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)

func (*Tx) Prepare

func (t *Tx) Prepare(query string) (*sql.Stmt, error)

func (*Tx) Query

func (t *Tx) Query(query string, args ...any) (*sql.Rows, error)

func (*Tx) QueryRow

func (t *Tx) QueryRow(query string, args ...any) *sql.Row

func (*Tx) QueryRowContext

func (t *Tx) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row

func (*Tx) Rollback

func (t *Tx) Rollback() error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址