sqlite

package module
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2026 License: MIT Imports: 14 Imported by: 0

README

GORM SQLite Driver

A GORM driver for SQLite-compatible databases, based on libsql-client-go. It is pure Go and needs no CGO.

go get codeberg.org/morelj/gorm-sqlite-libsql

The package is named sqlite, so an aliased import keeps call sites readable.

Quick Start

import (
  sqlite "codeberg.org/morelj/gorm-sqlite-libsql"
  "gorm.io/gorm"
)

db, err := gorm.Open(sqlite.Open("libsql://your-db-your-org.turso.io?authToken=<token>"), &gorm.Config{})

For full documentation, visit https://gorm.io.

Supported DSNs

libsql-client-go is a remote client: it speaks the hrana protocol over HTTP or WebSocket and does not embed a SQLite engine. Only these schemes open:

DSN Target
libsql://host[?authToken=…] Turso / sqld over TLS
https://host, http://host sqld over hrana-over-HTTP
wss://host, ws://host sqld over hrana-over-WebSocket

authToken, auth_token and jwt are accepted as query parameters. To pass options that have no DSN equivalent — WithProxy, WithSchemaDb, WithRequestHeaders — build a connector yourself and hand over the pool:

connector, err := libsql.NewConnector(url, libsql.WithAuthToken(token), libsql.WithProxy(proxy))
if err != nil {
  return err
}
db, err := gorm.Open(sqlite.New(sqlite.Config{Conn: sql.OpenDB(connector)}), &gorm.Config{})
Local databases are not supported

There is no local SQLite engine in this driver, so a file path or an in-memory DSN does not open:

sqlite.Open("gorm.db")                          // error: unsupported URL scheme
sqlite.Open(":memory:")                          // error: missing protocol scheme
sqlite.Open("file:x?mode=memory&cache=shared")   // error: no sqlite driver present

For a file: DSN, libsql-client-go delegates to a driver already registered with database/sql under the name sqlite or sqlite3. Importing one alongside this driver restores local support:

import (
  _ "modernc.org/sqlite"           // registers "sqlite", pure Go
  // or _ "github.com/mattn/go-sqlite3" // registers "sqlite3", requires CGO

  sqlite "codeberg.org/morelj/gorm-sqlite-libsql"
)

// file: DSNs now work; a bare path still needs the file: prefix
db, err := gorm.Open(sqlite.Open("file:gorm.db"), &gorm.Config{})

Error Translation

Set gorm.Config{TranslateError: true} to receive gorm.ErrDuplicatedKey and gorm.ErrForeignKeyViolated. hrana reports a failed statement as a message rather than a numeric result code, so constraint failures are classified from the text SQLite produces. A driver supplied through Config.DriverName or Config.Conn whose error type has a Code() int method is classified from that code instead.

Alternative Drivers

Driver Repository
github.com/glebarez/sqlite github.com/glebarez/sqlite
github.com/libtnb/sqlite github.com/libtnb/sqlite
github.com/ncruces/go-sqlite3/gormlite github.com/ncruces/go-sqlite3

Testing

Unit tests need no database:

go test ./...

The tests that exercise the migrator and error translation against a live server skip unless GORM_LIBSQL_DSN names a scratch database — they empty its schema before each test:

GORM_LIBSQL_DSN=http://127.0.0.1:8080 go test ./...

AI Assistance

The port of this driver from go-sqlite3 to libsql-client-go was carried out with the help of an AI coding assistant (Claude Code). This covered swapping the underlying driver, rewriting error translation to classify constraint failures from the message hrana returns rather than from a numeric result code, and restructuring the tests that used to run against a local SQLite file.

The resulting code was validated by the test suite, including a run of the integration tests against a live hrana server. Treat it as you would any contribution: the upstream driver this is derived from carries its own history, and bugs introduced here are ours.

Documentation

Index

Constants

View Source
const DriverName = "libsql"

DriverName is the default driver name, registered by libsql-client-go.

Variables

View Source
var (
	ErrConstraintsNotImplemented = errors.New("constraints not implemented on sqlite, consider using DisableForeignKeyConstraintWhenMigrating, more details https://github.com/go-gorm/gorm/wiki/GORM-V2-Release-Note-Draft#all-new-migrator")
)

Functions

func New

func New(config Config) gorm.Dialector

func Open

func Open(dsn string) gorm.Dialector

Types

type Config

type Config struct {
	DriverName string
	DSN        string
	Conn       gorm.ConnPool
}

type Dialector

type Dialector struct {
	DriverName string
	DSN        string
	Conn       gorm.ConnPool
}

func (Dialector) BindVarTo

func (dialector Dialector) BindVarTo(writer clause.Writer, stmt *gorm.Statement, v interface{})

func (Dialector) ClauseBuilders

func (dialector Dialector) ClauseBuilders() map[string]clause.ClauseBuilder

func (Dialector) DataTypeOf

func (dialector Dialector) DataTypeOf(field *schema.Field) string

func (Dialector) DefaultValueOf

func (dialector Dialector) DefaultValueOf(field *schema.Field) clause.Expression

func (Dialector) Explain

func (dialector Dialector) Explain(sql string, vars ...interface{}) string

func (Dialector) Initialize

func (dialector Dialector) Initialize(db *gorm.DB) (err error)

func (Dialector) Migrator

func (dialector Dialector) Migrator(db *gorm.DB) gorm.Migrator

func (Dialector) Name

func (dialector Dialector) Name() string

func (Dialector) QuoteTo

func (dialector Dialector) QuoteTo(writer clause.Writer, str string)

func (Dialector) RollbackTo

func (dialectopr Dialector) RollbackTo(tx *gorm.DB, name string) error

func (Dialector) SavePoint

func (dialectopr Dialector) SavePoint(tx *gorm.DB, name string) error

func (Dialector) Translate

func (dialector Dialector) Translate(err error) error

Translate it will translate the error to native gorm errors.

type ErrMessage deprecated

type ErrMessage struct {
	Code         int `json:"Code"`
	ExtendedCode int `json:"ExtendedCode"`
	SystemErrno  int `json:"SystemErrno"`
}

ErrMessage was the intermediate shape the extended result code used to be decoded into.

Deprecated: Translate reads the extended result code from the driver error and no longer decodes errors through JSON. This type is retained so that code referring to it keeps compiling.

type Index

type Index struct {
	Seq     int
	Name    string
	Unique  bool
	Origin  string
	Partial bool
}

type Migrator

type Migrator struct {
	migrator.Migrator
}

func (Migrator) AlterColumn

func (m Migrator) AlterColumn(value interface{}, name string) error

func (Migrator) BuildIndexOptions

func (m Migrator) BuildIndexOptions(opts []schema.IndexOption, stmt *gorm.Statement) (results []interface{})

func (Migrator) ColumnTypes

func (m Migrator) ColumnTypes(value interface{}) ([]gorm.ColumnType, error)

ColumnTypes return columnTypes []gorm.ColumnType and execErr error

func (Migrator) CreateConstraint

func (m Migrator) CreateConstraint(value interface{}, name string) error

func (Migrator) CreateIndex

func (m Migrator) CreateIndex(value interface{}, name string) error

func (Migrator) CurrentDatabase

func (m Migrator) CurrentDatabase() (name string)

func (Migrator) DropColumn

func (m Migrator) DropColumn(value interface{}, name string) error

func (Migrator) DropConstraint

func (m Migrator) DropConstraint(value interface{}, name string) error

func (Migrator) DropIndex

func (m Migrator) DropIndex(value interface{}, name string) error

func (Migrator) DropTable

func (m Migrator) DropTable(values ...interface{}) error

func (Migrator) GetIndexes

func (m Migrator) GetIndexes(value interface{}) ([]gorm.Index, error)

GetIndexes return Indexes []gorm.Index and execErr error, See the doc

func (Migrator) GetTables

func (m Migrator) GetTables() (tableList []string, err error)

func (Migrator) HasColumn

func (m Migrator) HasColumn(value interface{}, name string) bool

func (Migrator) HasConstraint

func (m Migrator) HasConstraint(value interface{}, name string) bool

func (Migrator) HasIndex

func (m Migrator) HasIndex(value interface{}, name string) bool

func (Migrator) HasTable

func (m Migrator) HasTable(value interface{}) bool

func (Migrator) RenameIndex

func (m Migrator) RenameIndex(value interface{}, oldName, newName string) error

func (*Migrator) RunWithoutForeignKey

func (m *Migrator) RunWithoutForeignKey(fc func() error) error

Jump to

Keyboard shortcuts

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