CodeSampleX

Exemplo

github.com/glebarez/sqlite v1.11.0: sqlite.Dialector maps gosqlite constraint errors to GORM sentinel errors when TranslateError is enabled, supports nested transaction savepoints, and strips unsupported locking clauses

Amostra verificada para golang github.com/glebarez/sqlite v1.11.0: sqlite.Dialector maps gosqlite constraint errors to GORM sentinel errors when…

sha256:3b814829abe2c2b811eb5908b8650494c3373daf3ad4301a6fc604f8dee87b9d

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
3
Chaves de assinatura que o compilaram
2
Ambiente declarado go linux x64 go go go

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
go 1.26 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-17
go 1.26 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-18
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 FAIL compile:SKIPPED · contract:FAIL · load:SKIPPED · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-09-08

Caso

HOW
Objetivo
sqlite.Dialector maps gosqlite constraint errors to GORM sentinel errors when TranslateError is enabled, supports nested transaction savepoints, and strips unsupported locking clauses
Pacotes
Símbolos
  • Dialector
  • Open
Ambiente
go
Criado
2026-08-17T18:22:13Z

Contrato

  1. sqlite.Dialector translates pure-Go gosqlite unique and foreign key constraint errors into gorm.ErrDuplicatedKey and gorm.ErrForeignKeyViolated when TranslateError is enabled, while returning raw driver errors when disabled
  2. Nested transactions use SavePoint and RollbackTo to revert inner sub-transaction changes without aborting the parent transaction
  3. ClauseBuilders strips clause.Locking expressions so row-level locking clauses like FOR UPDATE do not trigger SQLite syntax errors
  4. sqlite.Dialector with an explicit Conn field initializes GORM directly over an existing sql.DB connection pool without opening a new DSN

Arquivos

  • NOTES.md
  • csx.json
  • go.mod
  • go.sum
  • sqlite_dialector_test.go

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

NOTES.md
# Notes on github.com/glebarez/sqlite

Prior solution search returned sample `sha256:9d4113f969da2b92bcfe242eb33b22d13f3c369252322f2fa8915ede8d7d3800`, which demonstrated basic DSN opening and CRUD operations. This project verifies deeper dialector semantics: constraint error translation, savepoint rollbacks in nested transactions, locking clause suppression, and pre-existing connection pool binding.

## Pinned Versions
- `github.com/glebarez/sqlite` v1.11.0
- `gorm.io/gorm` v1.25.7

## Observed Behaviour

1. **Constraint Error Translation (`Dialector.Translate`)**:
   - The pure-Go SQLite driver produces driver-specific `*gosqlite.Error` types on constraint failures.
   - When `TranslateError: true` is configured in `gorm.Config`, `Dialector.Translate` inspects the error code and maps `SQLITE_CONSTRAINT_UNIQUE` and `SQLITE_CONSTRAINT_PRIMARYKEY` to `gorm.ErrDuplicatedKey`, and `SQLITE_CONSTRAINT_FOREIGNKEY` to `gorm.ErrForeignKeyViolated`.
   - Without `TranslateError: true` (GORM's default configuration), GORM returns the raw `*gosqlite.Error`. Checking errors with `errors.Is(err, gorm.ErrDuplicatedKey)` fails silently by returning `false`.

2. **Nested Transactions via Savepoints (`SavePoint` / `RollbackTo`)**:
   - SQLite does not support nested `BEGIN TRANSACTION` calls.
   - `sqlite.Dialector` implements `SavePoint` and `RollbackTo` using SQL `SAVEPOINT` and `ROLLBACK TO SAVEPOINT`.
   - When `tx.Transaction(...)` is nested inside an outer `db.Transaction(...)`, a failure in the nested transaction rolls back only the inner operations, allowing the outer transaction to proceed and commit remaining changes.

3. **Locking Clause Suppression (`ClauseBuilders`)**:
   - SQLite does not support row-level locking (`FOR UPDATE` / `FOR SHARE`).
   - `sqlite.Dialector.ClauseBuilders()["FOR"]` detects `clause.Locking` expressions and omits them from the rendered SQL statement, preventing SQL syntax errors during query execution.

4. **Connection Pool Attachment (`Dialector.Conn`)**:
   - Passing an existing `*sql.DB` to `&sqlite.Dialector{Conn: sqlDB}` connects GORM to the existing connection pool directly, bypassing DSN string parsing while preserving full SQLite dialector callbacks and clause builders.
csx.json
{"case":{"believed":"gorm.Open with the glebarez pure-Go sqlite dialector automatically translates database constraint violations to gorm.ErrDuplicatedKey or gorm.ErrForeignKeyViolated by default without setting TranslateError","caseId":"case:sha256:75ef6157c530e645c202bc863b08e5379a08994d1a6f36d2d4de542384774c45","contract":["sqlite.Dialector translates pure-Go gosqlite unique and foreign key constraint errors into gorm.ErrDuplicatedKey and gorm.ErrForeignKeyViolated when TranslateError is enabled, while returning raw driver errors when disabled","Nested transactions use SavePoint and RollbackTo to revert inner sub-transaction changes without aborting the parent transaction","ClauseBuilders strips clause.Locking expressions so row-level locking clauses like FOR UPDATE do not trigger SQLite syntax errors","sqlite.Dialector with an explicit Conn field initializes GORM directly over an existing sql.DB connection pool without opening a new DSN"],"goal":"sqlite.Dialector maps gosqlite constraint errors to GORM sentinel errors when TranslateError is enabled, supports nested transaction savepoints, and strips unsupported locking clauses","kind":"HOW","packages":["pkg:golang/github.com/glebarez/sqlite@1.11.0","pkg:golang/gorm.io/gorm@1.25.7"],"schemaVersion":1,"symbols":["Dialector","Open"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","ecosystem":"golang","executionContext":"go","language":"go","os":"linux","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/glebarez/sqlite@1.11.0","pkg:golang/gorm.io/gorm@1.25.7"],"schemaVersion":1,"symbols":["Dialector","Open"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.5

require (
	github.com/glebarez/sqlite v1.11.0
	gorm.io/gorm v1.25.7
)

require (
	github.com/dustin/go-humanize v1.0.1 // indirect
	github.com/glebarez/go-sqlite v1.21.2 // indirect
	github.com/google/uuid v1.3.0 // indirect
	github.com/jinzhu/inflection v1.0.0 // indirect
	github.com/jinzhu/now v1.1.5 // indirect
	github.com/mattn/go-isatty v0.0.17 // indirect
	github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
	golang.org/x/sys v0.7.0 // indirect
	modernc.org/libc v1.22.5 // indirect
	modernc.org/mathutil v1.5.0 // indirect
	modernc.org/memory v1.5.0 // indirect
	modernc.org/sqlite v1.23.1 // indirect
)
go.sum
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/glebarez/go-sqlite v1.21.2 h1:3a6LFC4sKahUunAmynQKLZceZCOzUthkRkEAl9gAXWo=
github.com/glebarez/go-sqlite v1.21.2/go.mod h1:sfxdZyhQjTM2Wry3gVYWaW072Ri1WMdWJi0k6+3382k=
github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw=
github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
gorm.io/gorm v1.25.7 h1:VsD6acwRjz2zFxGO50gPO6AkNs7KKnvfzUjHQhZDz/A=
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
modernc.org/libc v1.22.5 h1:91BNch/e5B0uPbJFgqbxXuOnxBQjlS//icfQEGmvyjE=
modernc.org/libc v1.22.5/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY=
modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ=
modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds=
modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU=
modernc.org/sqlite v1.23.1 h1:nrSBg4aRQQwq59JpvGEQ15tNxoO5pX/kUjcRNwSAGQM=
modernc.org/sqlite v1.23.1/go.mod h1:OrDj17Mggn6MhE+iPbBNf7RGKODDE9NFT0f3EwDzJqk=
sqlite_dialector_test.go
package main

import (
	"database/sql"
	"errors"
	"strings"
	"testing"

	"github.com/glebarez/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"gorm.io/gorm/logger"
)

type Category struct {
	ID   uint   `gorm:"primarykey"`
	Code string `gorm:"uniqueIndex"`
	Name string
}

type Product struct {
	ID         uint `gorm:"primarykey"`
	CategoryID uint
	Category   Category `gorm:"constraint:OnDelete:CASCADE;"`
	Title      string
}

func TestTranslateErrorAndSavePoints(t *testing.T) {
	// 1. Enabling TranslateError translates gosqlite constraint errors into GORM sentinel errors
	dsn := "file:test_contract?mode=memory&cache=shared&_pragma=foreign_keys(1)"
	db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{
		Logger:         logger.Default.LogMode(logger.Silent),
		TranslateError: true,
	})
	if err != nil {
		t.Fatalf("failed to open database: %v", err)
	}

	if err := db.AutoMigrate(&Category{}, &Product{}); err != nil {
		t.Fatalf("failed to auto migrate: %v", err)
	}

	// Insert initial category
	cat := Category{Code: "ELEC", Name: "Electronics"}
	if err := db.Create(&cat).Error; err != nil {
		t.Fatalf("failed to create category: %v", err)
	}

	// Unique constraint violation translates to gorm.ErrDuplicatedKey
	dupErr := db.Create(&Category{Code: "ELEC", Name: "Duplicate"}).Error
	if !errors.Is(dupErr, gorm.ErrDuplicatedKey) {
		t.Fatalf("expected gorm.ErrDuplicatedKey for unique violation, got: %v", dupErr)
	}

	// Foreign key violation translates to gorm.ErrForeignKeyViolated
	fkErr := db.Create(&Product{CategoryID: 9999, Title: "Invalid FK"}).Error
	if !errors.Is(fkErr, gorm.ErrForeignKeyViolated) {
		t.Fatalf("expected gorm.ErrForeignKeyViolated for foreign key violation, got: %v", fkErr)
	}

	// Without TranslateError: true, raw *gosqlite.Error is returned and errors.Is(err, gorm.ErrDuplicatedKey) is false
	rawDB, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Silent),
	})
	if err != nil {
		t.Fatalf("failed to open rawDB: %v", err)
	}
	rawErr := rawDB.Create(&Category{Code: "ELEC", Name: "Duplicate Raw"}).Error
	if errors.Is(rawErr, gorm.ErrDuplicatedKey) {
		t.Fatalf("expected errors.Is(rawErr, gorm.ErrDuplicatedKey) to be false without TranslateError")
	}

	// 2. Nested transactions use SavePoint and RollbackTo to rollback sub-transactions without aborting the outer transaction
	txErr := db.Transaction(func(outerTx *gorm.DB) error {
		if err := outerTx.Create(&Category{Code: "BOOK", Name: "Books"}).Error; err != nil {
			return err
		}

		// Inner transaction that fails and rolls back
		_ = outerTx.Transaction(func(innerTx *gorm.DB) error {
			if err := innerTx.Create(&Category{Code: "FAIL", Name: "Failing SubTx"}).Error; err != nil {
				return err
			}
			return errors.New("rollback inner sub-transaction")
		})

		// Inner transaction that succeeds
		if err := outerTx.Transaction(func(innerTx *gorm.DB) error {
			return innerTx.Create(&Category{Code: "CLOTH", Name: "Clothing"}).Error
		}); err != nil {
			return err
		}

		return nil
	})
	if txErr != nil {
		t.Fatalf("outer transaction failed: %v", txErr)
	}

	// Verify outer committed records exist, while inner rolled-back record does not
	var categories []Category
	if err := db.Order("code").Find(&categories).Error; err != nil {
		t.Fatalf("failed to find categories: %v", err)
	}
	expectedCodes := []string{"BOOK", "CLOTH", "ELEC"}
	if len(categories) != len(expectedCodes) {
		t.Fatalf("expected %d categories, got %d", len(expectedCodes), len(categories))
	}
	for i, c := range categories {
		if c.Code != expectedCodes[i] {
			t.Errorf("category %d: expected code %s, got %s", i, expectedCodes[i], c.Code)
		}
	}

	// 3. ClauseBuilders suppresses clause.Locking so row-level locking does not fail SQLite execution
	var prods []Product
	lockingStmt := db.Session(&gorm.Session{DryRun: true}).Clauses(clause.Locking{Strength: "UPDATE"}).Find(&prods).Statement
	renderedSQL := strings.TrimSpace(lockingStmt.SQL.String())
	if strings.Contains(renderedSQL, "FOR UPDATE") {
		t.Fatalf("expected FOR UPDATE to be stripped by SQLite dialector, got: %s", renderedSQL)
	}
	if renderedSQL != "SELECT * FROM `products`" {
		t.Fatalf("unexpected SQL generated with Locking clause: %s", renderedSQL)
	}

	// 4. Initializing Dialector with a custom Conn (sql.DB) connects without re-opening via DSN
	rawSQLDB, err := sql.Open("sqlite", "file:custom_conn?mode=memory&cache=shared")
	if err != nil {
		t.Fatalf("sql.Open failed: %v", err)
	}
	defer rawSQLDB.Close()

	customDB, err := gorm.Open(&sqlite.Dialector{Conn: rawSQLDB}, &gorm.Config{
		Logger: logger.Default.LogMode(logger.Silent),
	})
	if err != nil {
		t.Fatalf("gorm.Open with custom Conn failed: %v", err)
	}
	var val int
	if err := customDB.Raw("SELECT 42").Scan(&val).Error; err != nil || val != 42 {
		t.Fatalf("expected custom Conn query to return 42, got val=%d, err=%v", val, err)
	}
}

Seeder de origem

csx-seed