dbh

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2024 License: MIT Imports: 23 Imported by: 5

README

DBH

This is a set of database helpers for doing things like running migrations, scanning into an array of integers, etc.

Documentation

Index

Constants

View Source
const DriverPostgres = "postgres"
View Source
const DriverSqlite = "sqlite3"

Variables

View Source
var DBNotExistRegex *regexp.Regexp

Functions

func ApplyPostLoadFlags

func ApplyPostLoadFlags(db *sql.DB, log logs.Log, dbc DBConfig, flags DBConnectFlags) error

func DropAllTables

func DropAllTables(log logs.Log, dbc DBConfig) error

DropAllTables delete all tables in the given database. If the database does not exist, returns nil. This function is intended to be used by unit tests.

func IDListToSQLSet

func IDListToSQLSet(ids []int64) string

Returns a set of IDs with parens, e.g. "(1,2,3)" Note that the SQL drivers don't accept an SQL set as a positional argument (eg $1 or ?), so you need to bake it into your query string. See https://stackoverflow.com/questions/4788724/sqlite-bind-list-of-values-to-where-col-in-prm for an explanation of why it's not possible with SQLite, but presumably similar principles apply to other SQL interfaces.

func IsKeyViolation

func IsKeyViolation(err error) bool

func IsKeyViolationOnIndex

func IsKeyViolationOnIndex(err error, indexName string) bool

func MakeMigrationFromFunc

func MakeMigrationFromFunc(log logs.Log, migrationNumber *int, f migration.Migrator) migration.Migrator

MakeMigrationFromFunc wraps a migration function with another migration that logs to our logfile

func MakeMigrationFromSQL

func MakeMigrationFromSQL(log logs.Log, migrationNumber *int, sql string) migration.Migrator

MakeMigrationFromSQL turns an SQL string into a burntsushi migration

func MakeMigrations

func MakeMigrations(log logs.Log, sql []string) []migration.Migrator

MakeMigrations turns a sequence of SQL expression into burntsushi migrations.

func OpenDB

func OpenDB(log logs.Log, dbc DBConfig, migrations []migration.Migrator, flags DBConnectFlags) (*gorm.DB, error)

OpenDB creates a new DB, or opens an existing one, and runs all the migrations before returning.

func PGByteArrayLiteral

func PGByteArrayLiteral(b []byte) string

Escape a byte array as a string literal, and return the entire literal, with quotes. eg. '\xDEADBEAF'

func SQLCleanIDList

func SQLCleanIDList(raw string) string

SQLCleanIDList turns a string such as "10,34" into the string "(10,34)", so that it can be used inside an IN clause. It is acceptable for the raw string to end with an extra trailing comma

func SQLFormatIDArray

func SQLFormatIDArray[T constraints.Integer](ids []T) string

Turn an array such as [1,2] into the string "(1,2)"

func SanitizeIDList

func SanitizeIDList(s string) string

func ScanArray

func ScanArray[T any](r *sql.Rows, queryErr error) ([]T, error)

ScanArray takes the result of db.Query() and returns an array of the given type. This is for queries that return a single column.

func StringToIDList

func StringToIDList(s string) []int64

Types

type DBConfig

type DBConfig struct {
	Driver      string `json:"driver"`
	Host        string `json:"host"`
	Port        int    `json:"port"`
	Database    string `json:"database"`
	Username    string `json:"username"`
	Password    string `json:"password"`
	SSLCert     string `json:"ssl_cert"`
	SSLKey      string `json:"-"`
	SSLRootCert string `json:"ssl_root_cert"`
}

DBConfig describes a database connection.

func MakeSqliteConfig

func MakeSqliteConfig(filename string) DBConfig

func (*DBConfig) DSN

func (db *DBConfig) DSN() string

DSN returns a database connection string (built for Postgres and Sqlite only).

func (*DBConfig) LogSafeDescription

func (db *DBConfig) LogSafeDescription() string

LogSafeDescription seturn a string that is useful for debugging connection issues, but doesn't leak secrets

type DBConnectFlags

type DBConnectFlags int

DBConnectFlags are flags passed to OpenDB.

const (
	// DBConnectFlagWipeDB causes the entire DB to erased, and re-initialized from scratch (useful for unit tests).
	DBConnectFlagWipeDB DBConnectFlags = 1 << iota
	DBConnectFlagSqliteWAL
	DBConnectFlagWaitForDB // Wait up to 15 seconds for the database to start up
)

type IntTime

type IntTime int64

IntTime is time in milliseconds UTC (aka unix milliseconds). IntTime makes it easy to save Int64 milliseconds into SQLite database with gorm. In addition, it marshals nicely into JSON, and supports omitempty. By using milliseconds in JSON, you can write "new Date(x)" in Javascript, to deserialize, and x.getTime() to serialize. One important downside is that the zero value means nil, so we are unable to represent the date 1970-01-01 00:00:00.000.

func MakeIntTime

func MakeIntTime(v time.Time) IntTime

Return a new IntTime from a time.Time

func MakeIntTimeMilli

func MakeIntTimeMilli(unixMilli int64) IntTime

Return a new IntTime from unix milliseconds

func (IntTime) Get

func (t IntTime) Get() time.Time

Get time.Time

func (IntTime) IsZero

func (t IntTime) IsZero() bool

Yes, this seems silly. But it's nice to have it show up in your IDE after pressing '.'

func (*IntTime) Scan

func (i *IntTime) Scan(src any) error

func (*IntTime) Set

func (t *IntTime) Set(v time.Time)

Set IntTime to time.Time

func (IntTime) Value

func (i IntTime) Value() (driver.Value, error)

type JSONField

type JSONField[T any] struct {
	Data T
}

JSONField wraps an arbitrary struct so that it can be included in a GORM model, for use in a JSON/JSONB field

func MakeJSONField

func MakeJSONField[T any](data T) *JSONField[T]

Return a copy of 'data', wrapped in a JSONField object

func (JSONField[T]) MarshalJSON

func (j JSONField[T]) MarshalJSON() ([]byte, error)

func (*JSONField[T]) Scan

func (j *JSONField[T]) Scan(src any) error

func (*JSONField[T]) UnmarshalJSON

func (j *JSONField[T]) UnmarshalJSON(b []byte) error

func (JSONField[T]) Value

func (j JSONField[T]) Value() (driver.Value, error)

type MilliTime

type MilliTime struct {
	// Embedding time.Time is better than making MilliTime an alias of time.Time, because embedding
	// brings in all the methods of time.Time, whereas an alias won't have any time-based methods on it.
	time.Time
}

MilliTime serializes to JSON as unix milliseconds. Unfortunately it doesn't support JSON 'omitempty'. We use this for Postgres, because Postgres has proper time.Time support.

func Milli

func Milli(t time.Time) MilliTime

func (MilliTime) MarshalJSON

func (i MilliTime) MarshalJSON() ([]byte, error)

func (*MilliTime) Scan

func (i *MilliTime) Scan(src any) error

func (*MilliTime) UnmarshalJSON

func (i *MilliTime) UnmarshalJSON(b []byte) error

func (MilliTime) Value

func (i MilliTime) Value() (driver.Value, error)

Jump to

Keyboard shortcuts

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