goSqlite

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 29, 2026 License: MIT Imports: 5 Imported by: 0

README

[!NOTE] This README was generated by Claude Code, get the ZH version from here.

cover

go-sqlite

pkg license

Lightweight Go SQLite wrapper with read/write connection pool separation and chainable Query Builder.

Table of Contents

Features

  • Read/Write Separation: Independent read and write connection pools optimized for high concurrency
  • WAL Mode: Write-Ahead Logging enabled by default for improved write performance
  • Chainable API: Fluent Query Builder syntax supporting SELECT, INSERT, UPDATE, DELETE
  • Comprehensive Conditions: WHERE, OR WHERE, HAVING, OR HAVING and various condition combinations
  • JOIN Support: INNER JOIN, LEFT JOIN for cross-table queries
  • Aggregate Queries: GROUP BY, HAVING, COUNT and other aggregate operations
  • Conflict Handling: INSERT OR IGNORE/REPLACE/ABORT/FAIL/ROLLBACK
  • Batch Insert: InsertBatch for inserting multiple records in one operation
  • Context Support: All operations support context.Context propagation
  • Auto Checkpoint: Background WAL checkpoint execution to maintain database performance

Installation

go get github.com/pardnchiu/go-sqlite

Usage

Initialize Connection
import (
    goSqlite "github.com/pardnchiu/go-sqlite"
    "github.com/pardnchiu/go-sqlite/core"
)

conn, err := goSqlite.New(core.Config{
    Path:         "./data.db",
    MaxOpenConns: 50,  // Read connection pool limit
    MaxIdleConns: 25,  // Idle connection limit
    Lifetime:     120, // Connection lifetime in seconds
})
if err != nil {
    log.Fatal(err)
}
defer conn.Close()
Create Table
err := conn.Write.Table("users").Create(
    core.Column{Name: "id", Type: "INTEGER", IsPrimary: true, AutoIncrease: true},
    core.Column{Name: "name", Type: "TEXT", IsNullable: false},
    core.Column{Name: "email", Type: "TEXT", IsUnique: true},
    core.Column{Name: "age", Type: "INTEGER", Default: 0},
)
INSERT
// Single insert
id, err := conn.Write.Table("users").Insert(map[string]any{
    "name":  "Alice",
    "email": "alice@example.com",
})

// With conflict handling
id, err := conn.Write.Table("users").
    Conflict(core.Replace).
    Insert(map[string]any{"name": "Bob"})

// Batch insert
affected, err := conn.Write.Table("users").InsertBatch([]map[string]any{
    {"name": "User1", "email": "u1@example.com"},
    {"name": "User2", "email": "u2@example.com"},
})
SELECT
// Select all
rows, err := conn.Read.Table("users").Get()

// With columns and conditions
rows, err := conn.Read.Table("users").
    Select("id", "name", "email").
    WhereEq("status", 1).
    WhereGt("age", 18).
    OrderBy("created_at", core.Desc).
    Limit(10).
    Get()

// Single row
row, err := conn.Read.Table("users").WhereEq("id", 1).First()

// Count
count, err := conn.Read.Table("users").WhereEq("status", 1).Count()

// Paginated query with total count
rows, err := conn.Read.Table("users").
    Total().
    Limit(20, 10). // offset=20, limit=10
    Get()
UPDATE
// Basic update
affected, err := conn.Write.Table("users").
    WhereEq("id", 1).
    Update(map[string]any{"name": "NewName"})

// Increment/Decrement
affected, err := conn.Write.Table("users").
    WhereEq("id", 1).
    Increase("login_count").
    Update()

affected, err := conn.Write.Table("users").
    WhereEq("id", 1).
    Decrease("credits", 10).
    Update()

// Toggle boolean
affected, err := conn.Write.Table("users").
    WhereEq("id", 1).
    Toggle("is_active").
    Update()
DELETE
// Conditional delete
affected, err := conn.Write.Table("users").
    WhereEq("status", 0).
    Delete()

// Full table delete requires force confirmation
affected, err := conn.Write.Table("users").Delete(true)
JOIN
rows, err := conn.Read.Table("orders").
    Select("orders.id", "users.name", "orders.amount").
    Join("users", "users.id = orders.user_id").
    WhereGt("orders.amount", 100).
    Get()

rows, err := conn.Read.Table("posts").
    LeftJoin("comments", "comments.post_id = posts.id").
    Get()
GROUP BY & HAVING
rows, err := conn.Read.Table("orders").
    Select("user_id", "SUM(amount) as total").
    GroupBy("user_id").
    HavingGt("total", 1000).
    Get()
Context Support
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

rows, err := conn.Read.Table("users").
    Context(ctx).
    WhereEq("status", 1).
    Get()
Raw SQL
// Query
rows, err := conn.Query("", "SELECT * FROM users WHERE id = ?", 1)

// Execute
result, err := conn.Exec("", "UPDATE users SET name = ? WHERE id = ?", "Bob", 1)

// Access underlying *sql.DB
db := conn.Read.Raw()

API Reference

Config
Field Type Description Default
Path string Database file path -
MaxOpenConns int Maximum read connections 50
MaxIdleConns int Maximum idle connections 25
Lifetime int Connection lifetime (seconds) 120
Connector
Method Description
Query(key, query, args...) Execute raw SELECT query
QueryContext(ctx, key, query, args...) SELECT with Context
Exec(key, query, args...) Execute raw write operation
ExecContext(ctx, key, query, args...) Write with Context
Close() Close all connections
Builder - Chain Methods
Method Description
Table(name) Specify table
Select(columns...) Specify columns to select
Join(table, on) INNER JOIN
LeftJoin(table, on) LEFT JOIN
Where(condition, args...) WHERE condition
WhereEq/WhereNotEq/WhereGt/WhereLt/WhereGe/WhereLe Comparison conditions
WhereIn/WhereNotIn IN conditions
WhereNull/WhereNotNull NULL checks
WhereBetween BETWEEN condition
OrWhere... OR condition variants
GroupBy(columns...) GROUP BY
Having... HAVING condition variants
OrHaving... OR HAVING condition variants
OrderBy(column, direction) Sorting
Limit(num...) Limit rows
Offset(num) Offset
Total() Enable total count
Context(ctx) Set Context
Conflict(mode) Set conflict handling mode
Increase/Decrease(column, num) Increment/Decrement value
Toggle(column) Toggle boolean
Builder - Execute Methods
Method Returns Description
Create(columns...) error Create table
Insert(data, conflictData?) (int64, error) Insert and return LastInsertId
InsertBatch(data) (int64, error) Batch insert and return affected rows
Get() (*sql.Rows, error) Query multiple rows
First() (*sql.Row, error) Query single row
Count() (int64, error) Count rows
Update(data?) (int64, error) Update and return affected rows
Delete(force?) (int64, error) Delete and return affected rows
Raw() *sql.DB Get underlying connection
Conflict Modes
Constant Description
core.Ignore INSERT OR IGNORE
core.Replace INSERT OR REPLACE
core.Abort INSERT OR ABORT
core.Fail INSERT OR FAIL
core.Rollback INSERT OR ROLLBACK
Column Definition
Field Type Description
Name string Column name
Type string SQLite type
IsPrimary bool Primary key
AutoIncrease bool Auto increment
IsNullable bool Allow NULL
IsUnique bool Unique constraint
Default any Default value
ForeignKey *Foreign Foreign key reference

License

MIT License

Author

邱敬幃 Pardn Chiu

Stars

Star


©️ 2026 邱敬幃 Pardn Chiu

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func New

func New(c core.Config) (*core.Connector, error)

Types

This section is empty.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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