CodeSampleX

샘플

gorm.io/gorm v1.25.7

검증된 샘플 — golang gorm.io/gorm v1.25.7. go 1.26 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: gorm.Open with DummyDialector initializes DB session and…

sha256:5f774f7025fb349b5a57a0a996973993c8433668ce1a49d7467974187bb1f636

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
2
빌드한 서명 키
2
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 go

검증 실행 환경

환경 컨트랙트 단계 실행일
go 1.26 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-20
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-08

케이스

HOW
목표
verify pkg:golang/gorm.io/gorm@v1.25.7
패키지
생성일
2026-08-19T23:03:08Z

컨트랙트

  1. gorm.Open with DummyDialector initializes DB session and compiles SQL in DryRun mode
  2. schema.Parse parses model struct tags, primary keys, table names, and field definitions
  3. Statement query builder generates correct SELECT SQL clauses with Where, Order, and Limit
  4. clause.OnConflict generates correct UPSERT SQL statements with target columns and update assignments
  5. Statement update builder constructs parameterized UPDATE SQL statements from model instances and map attributes

파일

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract.go

소스 아티팩트 내려받기 (tar.gz)

소스

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify pkg:golang/gorm.io/gorm@v1.25.7
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/gorm.io/gorm@v1.25.7
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:363a536b602cc88e1f6c70002a9396f4e771b8161ae2cb41b8c0bd05ec89faaf","contract":["gorm.Open with DummyDialector initializes DB session and compiles SQL in DryRun mode","schema.Parse parses model struct tags, primary keys, table names, and field definitions","Statement query builder generates correct SELECT SQL clauses with Where, Order, and Limit","clause.OnConflict generates correct UPSERT SQL statements with target columns and update assignments","Statement update builder constructs parameterized UPDATE SQL statements from model instances and map attributes"],"goal":"verify pkg:golang/gorm.io/gorm@v1.25.7","kind":"HOW","packages":["pkg:golang/gorm.io/gorm@v1.25.7"],"schemaVersion":1},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/gorm.io/gorm@v1.25.7"],"schemaVersion":1,"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.26.6

require gorm.io/gorm v1.25.7

require (
	github.com/jinzhu/inflection v1.0.0 // indirect
	github.com/jinzhu/now v1.1.5 // indirect
)
go.sum
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=
gorm.io/gorm v1.25.7 h1:VsD6acwRjz2zFxGO50gPO6AkNs7KKnvfzUjHQhZDz/A=
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
main.go
package main

import (
	"fmt"
	"sync"
	"time"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"gorm.io/gorm/schema"
	"gorm.io/gorm/utils/tests"
)

// User represents an application user entity with GORM struct tags.
type User struct {
	ID        uint      `gorm:"primaryKey;autoIncrement"`
	Username  string    `gorm:"size:64;not null;uniqueIndex:idx_users_username"`
	Email     string    `gorm:"size:255;not null;uniqueIndex:idx_users_email"`
	Role      string    `gorm:"size:32;default:'viewer';not null"`
	Active    bool      `gorm:"default:true"`
	CreatedAt time.Time `gorm:"autoCreateTime"`
}

// TableName specifies the custom table name for User.
func (User) TableName() string {
	return "app_users"
}

// UserRepo provides data access operations using GORM.
type UserRepo struct {
	db *gorm.DB
}

// NewUserRepo initializes a UserRepo with the given GORM DB instance.
func NewUserRepo(db *gorm.DB) *UserRepo {
	return &UserRepo{db: db}
}

// BuildCreateStatement compiles the insert statement for a user.
func (r *UserRepo) BuildCreateStatement(u *User) *gorm.Statement {
	return r.db.Session(&gorm.Session{DryRun: true}).Create(u).Statement
}

// BuildQueryStatement compiles a filtered and ordered select statement.
func (r *UserRepo) BuildQueryStatement(role string, limit int) *gorm.Statement {
	var users []User
	return r.db.Session(&gorm.Session{DryRun: true}).
		Model(&User{}).
		Where("role = ? AND active = ?", role, true).
		Order("id DESC").
		Limit(limit).
		Find(&users).
		Statement
}

// BuildUpsertStatement compiles an insert with ON CONFLICT DO UPDATE clause.
func (r *UserRepo) BuildUpsertStatement(u *User) *gorm.Statement {
	return r.db.Session(&gorm.Session{DryRun: true}).
		Model(&User{}).
		Clauses(clause.OnConflict{
			Columns:   []clause.Column{{Name: "email"}},
			DoUpdates: clause.AssignmentColumns([]string{"username", "role", "active"}),
		}).
		Create(u).
		Statement
}

// BuildUpdateStatement compiles an update statement for specific fields.
func (r *UserRepo) BuildUpdateStatement(id uint, updates map[string]interface{}) *gorm.Statement {
	return r.db.Session(&gorm.Session{DryRun: true}).
		Model(&User{}).
		Where("id = ?", id).
		Updates(updates).
		Statement
}

func main() {
	db, err := gorm.Open(tests.DummyDialector{}, &gorm.Config{
		DryRun: true,
	})
	if err != nil {
		fmt.Printf("Error opening GORM session: %v\n", err)
		return
	}

	repo := NewUserRepo(db)

	sampleUser := &User{
		Username: "sample_user",
		Email:    "user@example.com",
		Role:     "admin",
		Active:   true,
	}

	createStmt := repo.BuildCreateStatement(sampleUser)
	fmt.Printf("Create SQL: %s\n", createStmt.SQL.String())

	queryStmt := repo.BuildQueryStatement("admin", 10)
	fmt.Printf("Query SQL: %s\n", queryStmt.SQL.String())

	upsertStmt := repo.BuildUpsertStatement(sampleUser)
	fmt.Printf("Upsert SQL: %s\n", upsertStmt.SQL.String())

	updateStmt := repo.BuildUpdateStatement(1, map[string]interface{}{"role": "editor"})
	fmt.Printf("Update SQL: %s\n", updateStmt.SQL.String())

	parsedSchema, err := schema.Parse(&User{}, &sync.Map{}, schema.NamingStrategy{})
	if err != nil {
		fmt.Printf("Error parsing schema: %v\n", err)
		return
	}
	fmt.Printf("Parsed Table: %s, Primary Key: %s\n", parsedSchema.Table, parsedSchema.PrimaryFields[0].DBName)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/gorm.io/gorm@v1.25.7",
  "kind": "HOW",
  "packages": [
    "pkg:golang/gorm.io/gorm@v1.25.7"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.go
package main

import (
	"fmt"
	"os"
	"strings"
	"sync"
	"time"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"gorm.io/gorm/schema"
	"gorm.io/gorm/utils/tests"
)

// ContractUser defines an entity for contract verification
type ContractUser struct {
	ID        uint      `gorm:"primaryKey;autoIncrement"`
	Username  string    `gorm:"size:64;not null;uniqueIndex:idx_contract_user_name"`
	Email     string    `gorm:"size:255;not null;uniqueIndex:idx_contract_email"`
	Role      string    `gorm:"size:32;default:'viewer';not null"`
	Active    bool      `gorm:"default:true"`
	CreatedAt time.Time `gorm:"autoCreateTime"`
}

func (ContractUser) TableName() string {
	return "contract_users"
}

func main() {
	// Assertion 1: gorm.Open with DummyDialector initializes DB session and compiles SQL in DryRun mode
	{
		db, err := gorm.Open(tests.DummyDialector{}, &gorm.Config{
			DryRun: true,
		})
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: gorm.Open failed: %v\n", err)
			os.Exit(1)
		}
		if db == nil {
			fmt.Fprintf(os.Stderr, "FAIL: gorm.Open returned nil DB\n")
			os.Exit(1)
		}
		if !db.DryRun {
			fmt.Fprintf(os.Stderr, "FAIL: expected db.DryRun to be true\n")
			os.Exit(1)
		}
	}

	// Assertion 2: schema.Parse parses model struct tags, primary keys, table names, and field definitions
	{
		s, err := schema.Parse(&ContractUser{}, &sync.Map{}, schema.NamingStrategy{})
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: schema.Parse failed: %v\n", err)
			os.Exit(1)
		}

		if s.Table != "contract_users" {
			fmt.Fprintf(os.Stderr, "FAIL: expected table 'contract_users', got '%s'\n", s.Table)
			os.Exit(1)
		}

		if len(s.PrimaryFields) != 1 || s.PrimaryFields[0].DBName != "id" {
			fmt.Fprintf(os.Stderr, "FAIL: expected primary key 'id', got %+v\n", s.PrimaryFields)
			os.Exit(1)
		}

		emailField := s.LookUpField("Email")
		if emailField == nil || emailField.DBName != "email" {
			fmt.Fprintf(os.Stderr, "FAIL: field 'Email' not found or mismatch\n")
			os.Exit(1)
		}

		if !emailField.NotNull {
			fmt.Fprintf(os.Stderr, "FAIL: expected email field to have NotNull=true\n")
			os.Exit(1)
		}
	}

	// Assertion 3: Statement query builder generates correct SELECT SQL clauses with Where, Order, and Limit
	{
		db, _ := gorm.Open(tests.DummyDialector{}, &gorm.Config{DryRun: true})
		var users []ContractUser

		stmt := db.Model(&ContractUser{}).
			Where("role = ? AND active = ?", "admin", true).
			Order("id DESC").
			Limit(10).
			Offset(20).
			Find(&users).Statement

		sqlStr := stmt.SQL.String()
		if !strings.Contains(sqlStr, "SELECT * FROM `contract_users` WHERE role = ? AND active = ? ORDER BY id DESC LIMIT ? OFFSET ?") {
			fmt.Fprintf(os.Stderr, "FAIL: unexpected Select SQL: %s\n", sqlStr)
			os.Exit(1)
		}

		if len(stmt.Vars) != 4 || stmt.Vars[0] != "admin" || stmt.Vars[1] != true || stmt.Vars[2] != 10 || stmt.Vars[3] != 20 {
			fmt.Fprintf(os.Stderr, "FAIL: unexpected Select Vars: %v\n", stmt.Vars)
			os.Exit(1)
		}
	}

	// Assertion 4: clause.OnConflict generates correct UPSERT SQL statements with target columns and update assignments
	{
		db, _ := gorm.Open(tests.DummyDialector{}, &gorm.Config{DryRun: true})
		user := &ContractUser{
			Username: "user_test",
			Email:    "test@example.com",
			Role:     "editor",
			Active:   true,
		}

		stmt := db.Model(&ContractUser{}).
			Clauses(clause.OnConflict{
				Columns:   []clause.Column{{Name: "email"}},
				DoUpdates: clause.AssignmentColumns([]string{"username", "role", "active"}),
			}).
			Create(user).Statement

		sqlStr := stmt.SQL.String()
		if !strings.Contains(sqlStr, "ON CONFLICT (`email`) DO UPDATE SET") {
			fmt.Fprintf(os.Stderr, "FAIL: OnConflict clause missing in SQL: %s\n", sqlStr)
			os.Exit(1)
		}
		if !strings.Contains(sqlStr, "`username`=`excluded`.`username`") || !strings.Contains(sqlStr, "`role`=`excluded`.`role`") {
			fmt.Fprintf(os.Stderr, "FAIL: OnConflict update assignment missing in SQL: %s\n", sqlStr)
			os.Exit(1)
		}
	}

	// Assertion 5: Statement update builder constructs parameterized UPDATE SQL statements from model instances and map attributes
	{
		db, _ := gorm.Open(tests.DummyDialector{}, &gorm.Config{DryRun: true})

		stmt := db.Model(&ContractUser{}).
			Where("id = ?", uint(42)).
			Updates(map[string]interface{}{
				"role":   "superadmin",
				"active": false,
			}).Statement

		sqlStr := stmt.SQL.String()
		if !strings.HasPrefix(sqlStr, "UPDATE `contract_users` SET") || !strings.Contains(sqlStr, "WHERE id = ?") {
			fmt.Fprintf(os.Stderr, "FAIL: unexpected Update SQL: %s\n", sqlStr)
			os.Exit(1)
		}

		foundSuperadmin := false
		for _, v := range stmt.Vars {
			if v == "superadmin" {
				foundSuperadmin = true
				break
			}
		}
		if !foundSuperadmin {
			fmt.Fprintf(os.Stderr, "FAIL: update var 'superadmin' not found in %v\n", stmt.Vars)
			os.Exit(1)
		}
	}

	fmt.Println("PASS: gorm.io/gorm contract passed")
}

오리진 시더

익명