sqlc

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2025 License: MIT Imports: 5 Imported by: 0

README

Things-Kit SQLC

Database Connection Pool for Things-Kit

Lifecycle-managed database connection pool with automatic migration support.

Installation

go get github.com/things-kit/things-kit-sqlc

Features

  • Automatic database connection lifecycle management
  • Connection pool configuration
  • Integration with sqlc for type-safe SQL
  • Startup functions for migrations
  • Graceful connection and shutdown

Quick Start

package main

import (
    "database/sql"
    "github.com/things-kit/things-kit/app"
    "github.com/things-kit/things-kit/logging"
    "github.com/things-kit/things-kit/viperconfig"
    "github.com/things-kit/things-kit-sqlc"
)

func main() {
    app.New(
        viperconfig.Module,
        logging.Module,
        sqlc.Module,
        fx.Invoke(UseDatabase),
    ).Run()
}

func UseDatabase(db *sql.DB) {
    // Use the database connection
    var count int
    db.QueryRow("SELECT COUNT(*) FROM users").Scan(&count)
}

Configuration

Via config.yaml:

db:
  dsn: "postgres://user:password@localhost:5432/mydb?sslmode=disable"
  max_open_conns: 25
  max_idle_conns: 5
  conn_max_lifetime: 5m

Or environment variable:

export DB_DSN="postgres://user:password@localhost:5432/mydb?sslmode=disable"

With Migrations

Run migrations at startup:

func RunMigrations(ctx context.Context, db *sql.DB, logger log.Logger) error {
    logger.InfoC(ctx, "Running migrations...")
    // Your migration logic
    return nil
}

app.New(
    viperconfig.Module,
    logging.Module,
    sqlc.Module,
    app.AsStartupFunc(RunMigrations), // Runs before server starts
).Run()

With SQLC

Use with sqlc for type-safe SQL:

import "your/package/db" // generated by sqlc

func NewQueries(database *sql.DB) *db.Queries {
    return db.New(database)
}

app.New(
    viperconfig.Module,
    logging.Module,
    sqlc.Module,
    fx.Provide(NewQueries),
    fx.Invoke(UseQueries),
).Run()

func UseQueries(q *db.Queries) {
    users, err := q.ListUsers(ctx)
}

License

MIT License - see LICENSE file for details

Documentation

Overview

Package sqlc provides a lifecycle-managed SQL database connection pool.

Index

Constants

This section is empty.

Variables

View Source
var Module = fx.Module("sqlc",
	fx.Provide(NewConfig, NewDB),
)

Module provides the SQL database module to the application.

Functions

func NewDB

func NewDB(lc fx.Lifecycle, cfg *Config) (*sql.DB, error)

NewDB creates a new database connection pool.

Types

type Config

type Config struct {
	DSN string `mapstructure:"dsn"` // Data Source Name
}

Config holds the database configuration.

func NewConfig

func NewConfig(v *viper.Viper) *Config

NewConfig creates a new database configuration from Viper.

Jump to

Keyboard shortcuts

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