Documentation
¶
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ExecQuery ¶
ExecQuery executes a single Query against the database. This function handles both raw SQL strings and query builder objects.
Parameters:
- ctx: Context for cancellation and timeout
- db: Database connection to execute the query against
- query: The Query to execute (string or sqlizer)
Returns:
- error: Non-nil if the query execution fails
func Use ¶
Use connects to a database environment and returns the database connection. This is a simple convenience function that calls the environment's Connect method, applies any provided options, and wraps any error with additional context.
This function is suitable for production code where you need to manage the connection lifecycle manually. For testing, consider using UseForTesting which provides automatic cleanup.
Parameters:
- ctx: Context for cancellation and timeout
- env: Database environment to connect to
- opts: Optional configuration functions to apply after connection
Returns:
- *sql.DB: Database connection ready to use
- error: Non-nil if connection or any option fails
Example:
// Connect to environment
db, err := Use(ctx, env)
if err != nil {
return fmt.Errorf("connect: %w", err)
}
defer db.Close()
// Use database...
rows, err := db.QueryContext(ctx, "SELECT * FROM users")
Example with options:
// Connect with migrations
db, err := Use(ctx, env,
Queries("CREATE TABLE users (id SERIAL PRIMARY KEY)"),
)
if err != nil {
return err
}
defer db.Close()
Example with timeout:
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
db, err := Use(ctx, env)
if err != nil {
return err
}
defer db.Close()
func UseForTesting ¶
UseForTesting connects to a database environment for use in tests. This function is designed specifically for testing scenarios and provides automatic connection cleanup.
Key features:
- Calls t.Helper() to improve error reporting
- Automatically closes the database connection when the test completes
- Fails the test immediately if connection fails
- Reports cleanup errors to the test log
- Applies any provided options after connection
Parameters:
- t: Testing context (must not be nil)
- env: Database environment to connect to
- opts: Optional configuration functions to apply after connection
Returns:
- *sql.DB: Database connection ready to use (automatically closed after test)
The function will call t.Fatal if connection fails, which immediately stops the test execution.
Example:
func TestDatabase(t *testing.T) {
t.Parallel()
// Create environment
env := createTestEnvironment()
// Get database connection - automatically closed after test
db := UseForTesting(t, env)
// Use database in test
var count int
err := db.QueryRow("SELECT COUNT(*) FROM users").Scan(&count)
require.NoError(t, err)
assert.Equal(t, 0, count)
}
Example with options:
func TestWithMigrations(t *testing.T) {
t.Parallel()
// Create environment
env := postgresenv.New(...)
// Connect with migrations - automatically closed after test
db := UseForTesting(t, env,
Queries("CREATE TABLE users (id SERIAL PRIMARY KEY)"),
)
// Database now has users table
_, err := db.Exec("INSERT INTO users DEFAULT VALUES")
require.NoError(t, err)
}
Note: The database connection is closed using t.Cleanup(), which runs after the test completes. If you need to close the connection earlier, use Use() instead and manage the lifecycle manually.
Types ¶
type Environment ¶
type Environment interface {
// Connect establishes a connection to the database environment.
//
// The connection returned is ready to use and may have additional
// setup applied (e.g., connection pool configuration).
//
// The caller is responsible for closing the connection when done.
//
// Parameters:
// - ctx: Context for cancellation and timeout
//
// Returns:
// - *sql.DB: Database connection ready to use
// - error: Non-nil if connection fails
Connect(ctx context.Context) (*sql.DB, error)
}
type Option ¶
Option is a function that configures a database connection after it's established. Options are applied in order and can be used for tasks like:
- Applying database migrations
- Running initialization queries
- Configuring connection settings
The option receives the context and the established database connection, and returns an error if the configuration fails.
Common option creators:
- Queries: For SQL-based initialization
- migrations.Up: For applying migrations.Migrations interface
Example:
// Custom option that sets up a schema
func WithSchema(schema string) dbenv.Option {
return func(ctx context.Context, db *sql.DB) error {
_, err := db.ExecContext(ctx, "CREATE SCHEMA IF NOT EXISTS "+schema)
return err
}
}
func Queries ¶
Queries creates an Option from a variadic list of Query values. This is the primary constructor for creating query-based options that are applied after establishing a database connection.
The function accepts any number of Query values, which can be:
- Raw SQL strings
- Query builder objects (implementing sqlizer)
- Slices of queries (nested structures)
- Mixed types
Example:
// Using raw SQL strings
opt := Queries(
"CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT)",
"CREATE INDEX idx_users_name ON users(name)",
)
// Using query builders (e.g., squirrel)
opt := Queries(
squirrel.Insert("users").Columns("name").Values("Alice"),
squirrel.Insert("users").Columns("name").Values("Bob"),
)
// Mixed types
opt := Queries(
"CREATE TABLE users (id SERIAL PRIMARY KEY)",
[]string{
"INSERT INTO users (name) VALUES ('Alice')",
"INSERT INTO users (name) VALUES ('Bob')",
},
squirrel.Update("users").Set("active", true),
)
// Use with Use or UseForTesting
db, err := Use(ctx, env, opt)
db := UseForTesting(t, env, opt)
type Query ¶
type Query any
Query represents a database query that can be executed as part of an Option. It can be one of the following types:
- string: A raw SQL query
- sqlizer: An object that implements the ToSql() method (e.g., squirrel.QueryBuilder)
- []Query: A slice of queries to execute in sequence
- []string: A slice of raw SQL queries
- []any: A slice of queries of mixed types
This flexible type allows options to use various query construction methods while maintaining a consistent execution interface.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package migrations provides utilities for managing database migrations in test environments.
|
Package migrations provides utilities for managing database migrations in test environments. |
|
goose
Package goosemigrations provides a goose-based migration adapter for the migrations package.
|
Package goosemigrations provides a goose-based migration adapter for the migrations package. |