{"id":45771669,"url":"https://github.com/arllen133/sqlc","last_synced_at":"2026-02-26T06:03:03.693Z","repository":{"id":335438534,"uuid":"1122559739","full_name":"arllen133/sqlc","owner":"arllen133","description":"sqlc - High Performance Golang ORM Framework","archived":false,"fork":false,"pushed_at":"2026-02-24T10:17:43.000Z","size":7448,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-02-24T15:49:24.088Z","etag":null,"topics":["golang","orm","sqlc","sqlx","squirrel"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/arllen133.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-12-25T02:34:27.000Z","updated_at":"2026-02-24T10:16:03.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/arllen133/sqlc","commit_stats":null,"previous_names":["arllen133/sqlc"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/arllen133/sqlc","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arllen133%2Fsqlc","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arllen133%2Fsqlc/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arllen133%2Fsqlc/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arllen133%2Fsqlc/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/arllen133","download_url":"https://codeload.github.com/arllen133/sqlc/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arllen133%2Fsqlc/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29849830,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-25T22:37:40.667Z","status":"online","status_checked_at":"2026-02-26T02:00:06.774Z","response_time":89,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["golang","orm","sqlc","sqlx","squirrel"],"created_at":"2026-02-26T06:03:01.602Z","updated_at":"2026-02-26T06:03:03.680Z","avatar_url":"https://github.com/arllen133.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# sqlc - High Performance Golang ORM Framework\n\nA modern ORM framework based on **Go Generics + Code Generation + Squirrel SQL Builder**.\n\n## Core Features\n\n- ✅ **Generics Driven** - Type-safe API using Go 1.18+ generics, zero runtime reflection overhead.\n- ✅ **Code Generation** - Auto-generate model metadata, only ~50 lines of code per model.\n- ✅ **SQL Builder** - Integrated Squirrel for SQL construction, auto-adapts to MySQL/PostgreSQL/SQLite.\n- ✅ **Fluent Query API** - Chainable query builder.\n- ✅ **Transaction Support** - Auto-commit/rollback transaction management.\n- ✅ **Lifecycle Hooks** - Model hooks like BeforeCreate/AfterCreate.\n- ✅ **JSON Support** - Rich JSON operations including querying, updating, and deep merging (RFC 7396).\n- ✅ **Observability** - Built-in support for `slog` logging and OpenTelemetry tracing.\n- ✅ **High Performance** - High-performance ORM designed for speed and efficiency.\n\n## Quick Start\n\n### Installation\n\n```bash\ngo get github.com/arllen133/sqlc\n```\n\n### Define Model\n\n```go\npackage models\n\nimport \"time\"\n\ntype User struct {\n    ID        int64     `db:\"id,primaryKey,autoIncrement\"`\n    Username  string    `db:\"username,size:100,unique\"`\n    Email     string    `db:\"email,size:255\"`\n    CreatedAt time.Time `db:\"created_at\"`\n}\n```\n\n### Generate Code\n\n```bash\ngo install github.com/arllen133/sqlc/cmd/sqlcli@latest\nsqlcli -i ./models\n```\n\nThis generates `models/generated/user_gen.go`, containing:\n\n- `generated.User` - Schema instance with type-safe field definitions.\n- `generated.UserMetadata` - JSON path accessors (if JSON fields exist).\n\n\u003e [!NOTE]\n\u003e Generated filenames always use `snake_case` (e.g., `user_config_gen.go` for a `UserConfig` struct).\n\n### CLI Versioning\n\nYou can check the version of `sqlcli` using the `-v` flag:\n\n```bash\nsqlcli -v\n```\n\nWhen building `sqlcli` from source, you can inject a version string using `-ldflags`:\n\n```bash\ngo build -ldflags=\"-X 'github.com/arllen133/sqlc/cmd/sqlcli/generator.Version=v1.2.3'\" ./cmd/sqlcli\n```\n\n### Declarative Configuration (Optional)\n\nCreate a `config.go` file in your model directory to customize code generation:\n\n```go\n// models/config.go\npackage models\n\nimport \"github.com/arllen133/sqlc/gen\"\n\nvar _ = gen.Config{\n    OutPath:        \"../generated\",              // Output directory (relative to model dir)\n    IncludeStructs: []any{\"User\", Post{}},       // Supports strings and type literals\n    ExcludeStructs: []any{BaseModel{}, \"Draft\"}, // Skip these structs\n}\n```\n\nWhen `sqlcli` runs, it automatically detects and applies this configuration.\n\n### Usage\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"database/sql\"\n    \"log/slog\"\n    \"time\"\n\n    _ \"github.com/mattn/go-sqlite3\"\n    \"github.com/arllen133/sqlc\"\n    \"yourapp/models\"\n    \"yourapp/models/generated\" // Import generated code\n)\n\nfunc main() {\n    // 1. Connect to Database with Observability\n    db, _ := sql.Open(\"sqlite3\", \"app.db\")\n    session := sqlc.NewSession(db, \u0026sqlc.SQLiteDialect{},\n        sqlc.WithLogger(slog.Default()), // Enable logging\n        sqlc.WithDefaultTracer(),        // Enable OpenTelemetry tracing\n    )\n\n    // 2. Create Repository\n    userRepo := sqlc.NewRepository[models.User](session)\n    ctx := context.Background()\n\n    // 3. Create Record\n    user := \u0026models.User{\n        Username: \"alice\",\n        Email:    \"alice@example.com\",\n    }\n    userRepo.Create(ctx, user)\n    // user.ID is auto-filled\n\n    // 4. Type-Safe Query\n    users, _ := userRepo.Query().\n        Where(generated.User.Username.Eq(\"alice\")).\n        OrderBy(generated.User.CreatedAt.Asc()).\n        Limit(10).\n        Find(ctx)\n\n    // 5. Update\n    user.Email = \"new@example.com\"\n    userRepo.Update(ctx, user)\n\n    // 6. Delete\n    userRepo.Delete(ctx, user.ID)\n}\n```\n\n## Advanced Features\n\n### Soft Delete\n\nModels with a `DeletedAt` field (e.g., `*time.Time`, `sql.NullTime`, or numeric unix timestamps) automatically support soft delete.\n\n```go\ntype Product struct {\n    ID        int64      `db:\"id,primaryKey,autoIncrement\"`\n    Name      string     `db:\"name\"`\n    DeletedAt *time.Time `db:\"deleted_at,softDelete\"` // Enables soft delete\n}\n```\n\nBy default, all queries automatically filter out soft-deleted records. You can modify this behavior:\n\n```go\n// 1. Default: Automatically filters soft-deleted records\nactiveProducts, _ := repo.Query().Find(ctx) // WHERE deleted_at IS NULL\n\n// 2. Include deleted records\nallProducts, _ := repo.Query().WithTrashed().Find(ctx)\n\n// 3. Query ONLY deleted records\ndeletedProducts, _ := repo.Query().OnlyTrashed().Find(ctx)\n```\n\nSoft-deleted records can be permanently removed (hard deleted) using the `Unscoped()` repository wrapper:\n\n```go\n// Soft delete (sets deleted_at)\nrepo.Delete(ctx, productID)\n\n// Hard delete (DELETE FROM products WHERE id = ...)\nrepo.Unscoped().Delete(ctx, productID)\n```\n\n### Transactions\n\n```go\nerr := session.Transaction(ctx, func(txSession *sqlc.Session) error {\n    txRepo := sqlc.NewRepository[models.User](txSession)\n\n    user1 := \u0026models.User{Username: \"user1\"}\n    if err := txRepo.Create(ctx, user1); err != nil {\n        return err // Auto-rollback\n    }\n\n    return nil // Auto-commit\n})\n```\n\n### JSON Operations\n\nRich support for JSON columns with dialect-specific optimizations (MySQL, PostgreSQL, SQLite).\n\n#### Define JSON Field\n\n```go\ntype Metadata struct {\n    Tags []string `json:\"tags\"`\n    Info struct {\n        Age int `json:\"age\"`\n    } `json:\"info\"`\n}\n\ntype Post struct {\n    ID   int64                 `db:\"id\"`\n    Meta sqlc.JSON[Metadata]   `db:\"meta,type:json\"`\n}\n```\n\n#### JSON Querying\n\n```go\nimport \"yourapp/models/generated\"\n\n// Query by JSON path\nrepo.Query().\n    Where(generated.Metadata.Age.Gt(18)). // Metadata is generated from Metadata struct name\n    Where(generated.Metadata.Tags.Contains(\"golang\")).\n    Find(ctx)\n```\n\n#### JSON Updates\n\n```go\n// Partial update (JSON_SET)\nrepo.UpdateColumns(ctx, id,\n    generated.Metadata.Age.Set(25),\n)\n\n// Remove field (JSON_REMOVE)\nrepo.UpdateColumns(ctx, id,\n    generated.Metadata.Info.Remove(), // Assuming Info itself can be removed or a field inside it\n    // Or for a custom path:\n    field.JSONRemove(generated.Post.Meta, \"$.deprecated_field\"),\n)\n```\n\n#### JSON Merge (RFC 7396)\n\nEfficiently merge JSON objects using DB-native functions (`JSON_MERGE_PATCH` in MySQL, `||` in Postgres, `json_patch` in SQLite).\n\n```go\n// Merge Patch\nrepo.UpdateColumns(ctx, id,\n    generated.Post.Meta.MergePatch(map[string]any{\n        \"view_count\": 100,\n        \"tags\": []string{\"updated\"},\n    }),\n)\n```\n\n### Relations \u0026 Eager Loading\n\nSupport for defining and eagerly loading relationships (HasOne, HasMany, BelongsTo) to avoid N+1 query problems.\n\n#### Define Relations\n\nUse the `relation` tag on your struct fields. These fields are typically not stored in the database column matching the field name, so use `db:\"-\"`.\n\n```go\ntype User struct {\n    ID    int64   `db:\"id,primaryKey,autoIncrement\"`\n    Posts []*Post `db:\"-\" relation:\"hasMany,foreignKey:user_id\"`\n}\n\ntype Post struct {\n    ID     int64 `db:\"id,primaryKey\"`\n    UserID int64 `db:\"user_id\"`\n    // BelongsTo: FK (user_id) is on the Post struct\n    Author *User `db:\"-\" relation:\"belongsTo,foreignKey:user_id\"`\n}\n```\n\n#### Generate Code\n\nRunning `sqlcli` will automatically generate relation metadata in your `*_gen.go` files, e.g., `generated.User_Posts`.\n\n```bash\nsqlcli -i ./models\n```\n\n#### Eager Loading (Preload)\n\nUse `WithPreload` to load relationships efficiently (usually via logical IN queries). `WithPreload` also supports customizing the child query via variadic options.\n\n```go\n// 1. Basic Preload: Load Users with ALL their Posts\nusers, _ := userRepo.Query().\n    WithPreload(sqlc.Preload(generated.User_Posts)).\n    Find(ctx)\n\nfor _, u := range users {\n    fmt.Printf(\"User %d has %d posts\\n\", u.ID, len(u.Posts))\n}\n\n// 2. Custom Preload: Load Users and ONLY their published posts\nusersWithPubPosts, _ := userRepo.Query().\n    WithPreload(sqlc.Preload(generated.User_Posts, func(q *sqlc.QueryBuilder[models.Post]) *sqlc.QueryBuilder[models.Post] {\n        return q.Where(generated.Post.Status.Eq(\"published\")).\n                 OrderBy(generated.Post.CreatedAt.Desc()).\n                 Limit(5) // Only fetch the 5 most recent published posts per user\n    })).\n    Find(ctx)\n\n// 3. Load Posts with their Author\nposts, _ := postRepo.Query().\n    WithPreload(sqlc.Preload(generated.Post_Author)).\n    Find(ctx)\n```\n\n### Observability\n\n#### Logging\n\nBuilt-in support for `log/slog`.\n\n```go\nsess := sqlc.NewSession(db, dialect,\n    sqlc.WithLogger(slog.Default()),\n    sqlc.WithSlowQueryThreshold(200*time.Millisecond), // Alert on slow queries\n    sqlc.WithQueryLogging(true),                       // Log all queries (debug)\n)\n```\n\n#### Tracing\n\nBuilt-in integration with OpenTelemetry.\n\n```go\nimport \"go.opentelemetry.io/otel\"\n\nsess := sqlc.NewSession(db, dialect,\n    sqlc.WithTracer(otel.Tracer(\"my-service\")),\n)\n```\n\nSpans include attributes like `db.statement`, `db.system`, and `db.table`.\n\n### Fluent Expressions\n\n```go\nmodels.UserFields.Username.Eq(\"alice\")      // username = 'alice'\nmodels.UserFields.Age.Ne(18)                // age != 18\nmodels.UserFields.Age.Gt(18)                // age \u003e 18\nmodels.UserFields.Age.Gte(18)               // age \u003e= 18\nmodels.UserFields.Age.Lt(30)                // age \u003c 30\nmodels.UserFields.Status.In(\"a\", \"b\")       // status IN ('a', 'b')\nmodels.UserFields.Username.Like(\"%alice%\")  // username LIKE '%alice%'\nmodels.UserFields.Email.IsNull()            // email IS NULL\n```\n\n### Joins and Aggregations\n\n```go\n// JOIN\nrepo.Query().\n    Join(\"departments\", clause.Expr{SQL: \"users.dept_id = departments.id\"}).\n    Find(ctx)\n\n// Aggregation\ncount, _ := repo.Query().\n    Where(models.UserFields.Status.Eq(\"active\")).\n    Count(ctx)\n```\n\n### Upsert\n\nSupport `INSERT ... ON CONFLICT/DUPLICATE KEY UPDATE` across databases.\n\n```go\n// Default: Update non-PK columns on conflict\nrepo.Upsert(ctx, user)\n\n// Custom: Specific conflict target and update columns\nrepo.Upsert(ctx, user,\n    sqlc.OnConflict(models.UserFields.Email),\n    sqlc.DoUpdate(models.UserFields.Username),\n)\n```\n\n## Database Support\n\n- ✅ **SQLite** (Modern JSON support)\n- ✅ **MySQL** (5.7+, 8.0+)\n- ✅ **PostgreSQL** (JSONB support)\n\n## License\n\nMIT License\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Farllen133%2Fsqlc","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Farllen133%2Fsqlc","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Farllen133%2Fsqlc/lists"}