From 061cd759a43ae55a043ae09c712ec5b5764dc54b Mon Sep 17 00:00:00 2001 From: Luiz Neves Date: Tue, 17 Nov 2026 07:58:43 -0300 Subject: [PATCH 1/7] feat: make:model --from-table, --version, release pipeline, dialect CI; fix GroupBy injection Security fix (breaking): Query.GroupBy passed its argument to GORM unquoted, so a caller-supplied value could inject SQL. It is now quoted like OrderBy. Use the new GroupByRaw to group by an expression. - make:model --from-table generates a model from a live table - migro --version (ldflags via goreleaser, build-info fallback) - GoReleaser + release workflow, CHANGELOG, Dependabot, SECURITY.md, issue templates - CI: MariaDB, CockroachDB and SQL Server jobs (non-blocking), govulncheck, coverage, -race on PG/MySQL - Tests: eager-loading query count is constant, identifier arguments stay quoted - Example tests, coming-from-GORM and coming-from-Laravel pages, per-dialect feature table --- .github/ISSUE_TEMPLATE/bug_report.md | 19 +++ .github/ISSUE_TEMPLATE/config.yml | 5 + .github/ISSUE_TEMPLATE/feature_request.md | 11 ++ .github/dependabot.yml | 8 + .github/workflows/ci.yml | 76 ++++++++- .github/workflows/release.yml | 22 +++ .goreleaser.yaml | 21 +++ CHANGELOG.md | 29 ++++ README.md | 2 +- SECURITY.md | 20 +++ cmd/migro/launcher_test.go | 21 ++- cmd/migro/main.go | 27 ++- console/commands.go | 4 +- console/console_test.go | 52 ++++++ console/make.go | 12 ++ console/make_from_table.go | 199 ++++++++++++++++++++++ docs/advanced-queries.md | 2 + docs/coming-from-gorm.md | 65 +++++++ docs/coming-from-laravel.md | 72 ++++++++ docs/command-line.md | 2 +- docs/databases.md | 27 ++- internal/testdb/testdb.go | 1 + orm/example_test.go | 122 +++++++++++++ orm/guarantees_test.go | 138 +++++++++++++++ orm/query_where.go | 12 +- 25 files changed, 953 insertions(+), 16 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/release.yml create mode 100644 .goreleaser.yaml create mode 100644 CHANGELOG.md create mode 100644 SECURITY.md create mode 100644 console/make_from_table.go create mode 100644 docs/coming-from-gorm.md create mode 100644 docs/coming-from-laravel.md create mode 100644 orm/example_test.go create mode 100644 orm/guarantees_test.go diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..5085031 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,19 @@ +--- +name: Bug report +about: Something behaves differently from the docs +labels: bug +--- + +**migro version** (`migro --version`): +**Go version**: +**Database and version** (e.g. PostgreSQL 16, MariaDB 11): + +**What you did** (a minimal model, migration or query): + +```go + +``` + +**What you expected**: + +**What happened** (error code and message, generated SQL if you have it): diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..1db59ba --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Security vulnerability + url: https://github.com/LouisRiverstone/migro/security/advisories/new + about: Report it privately, not as a public issue. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..fb874e2 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,11 @@ +--- +name: Feature request +about: Suggest something to add +labels: enhancement +--- + +**What are you trying to do?** + +**How do you do it today** (in Laravel, Lucid, GORM or plain SQL)? + +**What would the migro API look like?** diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..c1ad29f --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,8 @@ +version: 2 +updates: + - package-ecosystem: gomod + directory: / + schedule: { interval: weekly } + - package-ecosystem: github-actions + directory: / + schedule: { interval: weekly } diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ebe0558..22f6596 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,7 +18,19 @@ jobs: - uses: golangci/golangci-lint-action@v8 with: { version: v2.15.0 } - run: go vet ./... - - run: go test -race -count=1 ./... + - run: go test -race -count=1 -covermode=atomic -coverprofile=coverage.out ./... + - name: coverage summary + run: go tool cover -func=coverage.out | tail -1 + - uses: actions/upload-artifact@v4 + with: { name: coverage, path: coverage.out } + + vulncheck: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: { go-version-file: go.mod } + - run: go run golang.org/x/vuln/cmd/govulncheck@v1.1.4 ./... postgres: runs-on: ubuntu-latest @@ -35,7 +47,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: { go-version-file: go.mod } - - run: go test -p 1 -count=1 ./... + - run: go test -race -p 1 -count=1 ./... mysql: runs-on: ubuntu-latest @@ -48,6 +60,66 @@ jobs: env: MIGRO_TEST_DIALECT: mysql MIGRO_TEST_DSN: root:root@tcp(127.0.0.1:3306)/migro?parseTime=true + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: { go-version-file: go.mod } + - run: go test -race -p 1 -count=1 ./... + + # The jobs below cover dialects that were only unit-tested before. They are + # non-blocking until each one is confirmed green, then drop continue-on-error. + mariadb: + runs-on: ubuntu-latest + continue-on-error: true + services: + mariadb: + image: mariadb:11 + env: { MARIADB_ROOT_PASSWORD: root, MARIADB_DATABASE: migro } + ports: ["3306:3306"] + options: --health-cmd "healthcheck.sh --connect --innodb_initialized" --health-interval 5s --health-retries 20 + env: + MIGRO_TEST_DIALECT: mariadb + MIGRO_TEST_DSN: root:root@tcp(127.0.0.1:3306)/migro?parseTime=true + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: { go-version-file: go.mod } + - run: go test -race -p 1 -count=1 ./... + + cockroachdb: + runs-on: ubuntu-latest + continue-on-error: true + env: + MIGRO_TEST_DIALECT: cockroachdb + MIGRO_TEST_DSN: host=localhost user=root dbname=defaultdb port=26257 sslmode=disable + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: { go-version-file: go.mod } + - name: start cockroachdb + run: | + docker run -d --name crdb -p 26257:26257 cockroachdb/cockroach:latest-v24.3 start-single-node --insecure + for i in $(seq 30); do + docker exec crdb ./cockroach sql --insecure -e 'select 1' >/dev/null 2>&1 && exit 0 + sleep 2 + done + docker logs crdb; exit 1 + - run: go test -p 1 -count=1 ./... + + sqlserver: + runs-on: ubuntu-latest + continue-on-error: true + services: + mssql: + image: mcr.microsoft.com/mssql/server:2022-latest + env: { ACCEPT_EULA: "Y", MSSQL_SA_PASSWORD: "Migro_Passw0rd" } + ports: ["1433:1433"] + options: >- + --health-cmd "/opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P Migro_Passw0rd -Q 'select 1'" + --health-interval 10s --health-retries 20 + env: + MIGRO_TEST_DIALECT: sqlserver + MIGRO_TEST_DSN: sqlserver://sa:Migro_Passw0rd@localhost:1433?database=master steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..0f38595 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,22 @@ +name: release +on: + push: + tags: ['v*'] + +permissions: + contents: write + +jobs: + goreleaser: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: { fetch-depth: 0 } + - uses: actions/setup-go@v5 + with: { go-version-file: go.mod } + - uses: goreleaser/goreleaser-action@v6 + with: + version: "~> v2" + args: release --clean + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.goreleaser.yaml b/.goreleaser.yaml new file mode 100644 index 0000000..f22efac --- /dev/null +++ b/.goreleaser.yaml @@ -0,0 +1,21 @@ +version: 2 +project_name: migro +builds: + - main: ./cmd/migro + binary: migro + env: [CGO_ENABLED=0] + goos: [linux, darwin, windows] + goarch: [amd64, arm64] + flags: [-trimpath] + ldflags: ['-s -w -X main.version={{.Version}}'] +archives: + - formats: [tar.gz] + format_overrides: + - { goos: windows, formats: [zip] } + files: [LICENSE, README.md, CHANGELOG.md] +checksum: + name_template: checksums.txt +changelog: + disable: true # release notes come from CHANGELOG.md +release: + github: { owner: LouisRiverstone, name: migro } diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..38a998d --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,29 @@ +# Changelog + +All notable changes are listed here. The project is pre-1.0: minor versions may contain breaking changes, and they are called out under **Breaking**. + +## [Unreleased] + +### Added +- `migro make:model Name --from-table=users` generates a model from a live table. +- `migro --version`. +- `Query.GroupByRaw` for grouping by an expression. +- Runnable `Example*` tests for the godoc, and docs: coming from GORM, coming from Laravel/Lucid, per-database feature table. +- Tests that fix the eager-loading query count and check that identifier arguments stay quoted. +- `SECURITY.md`, issue templates, Dependabot. +- CI jobs for MariaDB, CockroachDB and SQL Server (non-blocking until verified), `govulncheck`, coverage report. +- `-race` on the PostgreSQL and MySQL jobs. +- Tagged releases publish CLI binaries (linux, macOS, windows; amd64, arm64) through GoReleaser. + +### Fixed +- **Security:** `Query.GroupBy` sent its argument unquoted, so a caller-supplied value could inject SQL. It is now quoted like `OrderBy`. Use `GroupByRaw` for expressions. **Breaking** for code that passed an expression to `GroupBy`. + +## [0.1.1] + +- Documentation: version picker, per-release docs build, first-release install notes. + +## [0.1.0] + +- Models, relations, collections, casts, resources, scopes, strict mode, lifecycle, UUID/ULID keys. +- Schema builder, query builder, migrations, schema dump and diff, seeders and factories. +- Events, read replicas, sharding, and the `migro` CLI. diff --git a/README.md b/README.md index 50db579..5e09a28 100644 --- a/README.md +++ b/README.md @@ -126,7 +126,7 @@ migro migration:fresh --seed # rebuild the database and seed it - **Test helpers** (`dbtest`): database assertions, query counting, `RefreshDatabase` - **Events**, **named connections**, **connection pool options**, **read replicas** and **sharding** -PostgreSQL, CockroachDB, Redshift, MySQL, MariaDB, SQLite, SQL Server and Oracle. PostgreSQL, MySQL and SQLite run in CI; the others are unit-tested but not yet verified against live servers. +PostgreSQL, CockroachDB, Redshift, MySQL, MariaDB, SQLite, SQL Server and Oracle. PostgreSQL, MySQL and SQLite run in CI as blocking jobs. MariaDB, CockroachDB and SQL Server run in non-blocking jobs while they are verified; Redshift and Oracle are unit-tested only. ## Documentation diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..58ff055 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,20 @@ +# Security policy + +## Supported versions + +migro is pre-1.0. Security fixes go into the latest release only. + +## Reporting a vulnerability + +Please do not open a public issue. Report it privately through GitHub: **Security → Report a vulnerability** on the [repository page](https://github.com/LouisRiverstone/migro/security/advisories/new). + +Include the migro version, the database and dialect, a minimal reproduction, and what an attacker could do with it. You will get an answer within a few days, and a fix or a clear decision after that. Credit is given in the release notes unless you prefer otherwise. + +## What counts + +- SQL injection through an API that documents its argument as safe (column and table names passed to `Where*`, `OrderBy`, `GroupBy`, `WhereJSON` and the schema builder are quoted; `*Raw` methods and `Select` expressions are sent as written, by design). +- Mass-assignment or hidden-attribute leaks past `Fillable`, `Guarded` or `Hidden`. +- Weak defaults in the `Hashed` and `Encrypted` casts. +- A migration or CLI command that runs against the wrong database or skips the production confirmation. + +Using `*Raw` methods with unsanitised user input is an application bug, not a migro vulnerability. diff --git a/cmd/migro/launcher_test.go b/cmd/migro/launcher_test.go index 8bdb4ea..38d0522 100644 --- a/cmd/migro/launcher_test.go +++ b/cmd/migro/launcher_test.go @@ -67,8 +67,27 @@ func TestFindRootAndNeedsRunner(t *testing.T) { t.Error("no go.mod should fail") } for cmd, want := range map[string]bool{"make:migration": false, "help": false, "migration:run": true, "db:seed": true, "migrate": true} { - if needsRunner(cmd) != want { + if needsRunner([]string{cmd}) != want { t.Errorf("needsRunner(%q) != %v", cmd, want) } } + if !needsRunner([]string{"make:model", "User", "--from-table=users"}) { + t.Error("make:model --from-table reads the database and needs the runner") + } +} + +func TestVersion(t *testing.T) { + old := version + defer func() { version = old }() + version = "v9.9.9" + if got := resolveVersion(); got != "v9.9.9" { + t.Errorf("release version = %q", got) + } + version = "" + if got := resolveVersion(); got == "" { + t.Error("must fall back to build info or dev") + } + if code := run([]string{"--version"}); code != 0 { + t.Errorf("--version exit = %d", code) + } } diff --git a/cmd/migro/main.go b/cmd/migro/main.go index fc301ec..a97c3bb 100644 --- a/cmd/migro/main.go +++ b/cmd/migro/main.go @@ -16,14 +16,34 @@ import ( "context" "fmt" "os" + "runtime/debug" + "slices" "strings" "github.com/LouisRiverstone/migro/console" ) +// version is set at release time (-ldflags "-X main.version=v1.2.3"); `go install ...@vX` fills it from build info. +var version = "" + func main() { os.Exit(run(os.Args[1:])) } +// resolveVersion prefers the release-time value, then the module version Go embeds, then "dev". +func resolveVersion() string { + if version != "" { + return version + } + if info, ok := debug.ReadBuildInfo(); ok && info.Main.Version != "" && info.Main.Version != "(devel)" { + return info.Main.Version + } + return "dev" +} + func run(args []string) int { + if len(args) == 1 && (args[0] == "--version" || args[0] == "-v" || args[0] == "version") { + fmt.Println("migro " + resolveVersion()) + return console.ExitOK + } cwd, err := os.Getwd() if err != nil { fmt.Fprintln(os.Stderr, "ERROR ", err) @@ -38,7 +58,7 @@ func run(args []string) int { fmt.Fprintln(os.Stderr, "ERROR ", err) return console.ExitError } - if len(args) == 0 || !needsRunner(args[0]) { + if len(args) == 0 || !needsRunner(args) { return app.Run(context.Background(), args) } if rootErr != nil { @@ -49,8 +69,11 @@ func run(args []string) int { } // needsRunner reports whether a command must run inside the compiled project. -func needsRunner(cmd string) bool { +func needsRunner(args []string) bool { + cmd := args[0] switch { + case cmd == "make:model" && slices.ContainsFunc(args, func(a string) bool { return strings.HasPrefix(a, "--from-table") }): + return true // reads the live schema case cmd == "help" || cmd == "list" || cmd == "--help" || cmd == "-h": return false case strings.HasPrefix(cmd, "make:"): diff --git a/console/commands.go b/console/commands.go index 85f245b..3a123e6 100644 --- a/console/commands.go +++ b/console/commands.go @@ -95,8 +95,8 @@ func allCommands() []command { {name: "make:cast", desc: "Create a custom attribute cast", usage: "make:cast [--path=dir]", flags: spec(map[string]bool{"path": true}, nil), run: makeCast}, {name: "make:model", desc: "Create a model (-m migration, -f factory, -s seeder, -a all)", - usage: "make:model [-m] [-f] [-s] [-a] [--uuid|--ulid] [--path=dir]", - flags: spec(map[string]bool{"migration": false, "factory": false, "seeder": false, "all": false, "uuid": false, "ulid": false, "path": true}, + usage: "make:model [-m] [-f] [-s] [-a] [--uuid|--ulid] [--from-table=name] [--database=name] [--path=dir]", + flags: spec(map[string]bool{"from-table": true, "database": true, "migration": false, "factory": false, "seeder": false, "all": false, "uuid": false, "ulid": false, "path": true}, map[string]string{"m": "migration", "f": "factory", "s": "seeder", "a": "all"}), run: makeModel}, } } diff --git a/console/console_test.go b/console/console_test.go index 1e4b241..0e2253d 100644 --- a/console/console_test.go +++ b/console/console_test.go @@ -395,3 +395,55 @@ func TestDotEnvAndConnections(t *testing.T) { t.Fatalf("missing .env is fine: %v", err) } } + +func TestMakeModelFromTable(t *testing.T) { + h := newHarness(t) + db, err := h.app.Connections["default"](context.Background()) + if err != nil { + t.Fatal(err) + } + for _, ddl := range []string{ + `CREATE TABLE blog_posts (id INTEGER PRIMARY KEY AUTOINCREMENT, created_at DATETIME, updated_at DATETIME, deleted_at DATETIME, user_id BIGINT NOT NULL, title VARCHAR(255) NOT NULL, body TEXT, meta JSON, views INTEGER)`, + `CREATE TABLE audit (code VARCHAR(10) PRIMARY KEY, happened DATETIME NOT NULL)`, + } { + if err := db.Gorm.Exec(ddl).Error; err != nil { + t.Fatal(err) + } + } + _ = db.Close() + + h.mustRun("make:model", "BlogPost", "--from-table=blog_posts") + src, err := os.ReadFile(filepath.Join(h.app.Root, "app", "models", "blog_post.go")) + if err != nil { + t.Fatal(err) + } + squash := func(b []byte) string { return strings.Join(strings.Fields(string(b)), " ") } + for _, want := range []string{"orm.SoftDeleteModel", "UserID int64", "Title string", "Body *string", "Views *int32", `"encoding/json"`} { + if !strings.Contains(squash(src), want) { + t.Errorf("missing %q in:\n%s", want, src) + } + } + for _, unwanted := range []string{"CreatedAt", "DeletedAt", "TableName"} { + if strings.Contains(string(src), unwanted) { + t.Errorf("unexpected %q in:\n%s", unwanted, src) + } + } + + h.mustRun("make:model", "Audit", "--from-table=audit") + src, _ = os.ReadFile(filepath.Join(h.app.Root, "app", "models", "audit.go")) + for _, want := range []string{"Code string", "primaryKey", "Happened time.Time"} { + if !strings.Contains(squash(src), want) { + t.Errorf("missing %q in:\n%s", want, src) + } + } + if strings.Contains(string(src), "orm.") { + t.Errorf("a table without the BaseModel shape must not embed it:\n%s", src) + } + + if code := h.run("make:model", "Ghost", "--from-table=nope"); code != console.ExitError { + t.Errorf("unknown table exit = %d", code) + } + if code := h.run("make:model", "X", "--from-table=audit", "-m"); code != console.ExitUsage { + t.Errorf("--from-table with -m exit = %d", code) + } +} diff --git a/console/make.go b/console/make.go index 2443d30..711b9dc 100644 --- a/console/make.go +++ b/console/make.go @@ -382,6 +382,18 @@ type %[2]s struct { // Email string `+"`gorm:\"uniqueIndex\"`"+` } `, detectPackage(dir, "models"), base, table, embed) + if from := c.flags.str("from-table"); from != "" { + if embed != "BaseModel" || c.flags.isTrue("migration") || c.flags.isTrue("all") { + return usagef("--from-table cannot be combined with --uuid, --ulid, -m or -a: the table already exists") + } + cols, err := c.readTableColumns(from) + if err != nil { + return err + } + if src, err = renderModelFromTable(detectPackage(dir, "models"), base, from, cols); err != nil { + return err + } + } if err := writeNew(path, src); err != nil { return err } diff --git a/console/make_from_table.go b/console/make_from_table.go new file mode 100644 index 0000000..71c1a01 --- /dev/null +++ b/console/make_from_table.go @@ -0,0 +1,199 @@ +package console + +import ( + "fmt" + "go/format" + "sort" + "strings" + + "github.com/LouisRiverstone/migro" + "gorm.io/gorm/schema" +) + +// tableColumn is what make:model --from-table reads from the live database. +type tableColumn struct { + name string + dbType string + length int64 + nullable bool + primary bool +} + +var initialisms = map[string]string{"id": "ID", "url": "URL", "uri": "URI", "uuid": "UUID", "ulid": "ULID", "ip": "IP", "api": "API", "html": "HTML", "json": "JSON", "sql": "SQL", "http": "HTTP"} + +// fieldName turns a column name into an exported Go field name: user_id -> UserID. +func fieldName(col string) string { + var b strings.Builder + for _, part := range strings.FieldsFunc(col, func(r rune) bool { return r == '_' || r == ' ' || r == '-' }) { + if up, ok := initialisms[strings.ToLower(part)]; ok { + b.WriteString(up) + continue + } + b.WriteString(strings.ToUpper(part[:1]) + part[1:]) + } + name := b.String() + if name == "" || (name[0] >= '0' && name[0] <= '9') { + return "Col" + name + } + return name +} + +// goType maps a database type name to a Go type. The bool reports whether a NULL-able column +// should become a pointer (slices already hold nil). +func goType(c tableColumn) (typ string, pointerable bool) { + t := strings.ToLower(c.dbType) + if i := strings.IndexAny(t, "( "); i > 0 { + t = t[:i] + } + switch t { + case "tinyint": + if c.length == 1 { + return "bool", true + } + return "int8", true + case "bool", "boolean", "bit": + return "bool", true + case "smallint", "int2", "smallserial": + return "int16", true + case "int", "integer", "int4", "mediumint", "serial": + return "int32", true + case "bigint", "int8", "bigserial": + return "int64", true + case "float", "real", "float4": + return "float32", true + case "double", "float8", "numeric", "decimal", "money", "number", "double precision": + return "float64", true + case "date", "datetime", "datetime2", "timestamp", "timestamptz", "timestamp with time zone", "timestamp without time zone", "time", "smalldatetime": + return "time.Time", true + case "json", "jsonb": + return "json.RawMessage", false + case "blob", "bytea", "binary", "varbinary", "longblob", "mediumblob", "tinyblob": + return "[]byte", false + } + return "string", true +} + +// renderModelFromTable produces a model source file. When the table follows the BaseModel +// shape (id, created_at, updated_at, optionally deleted_at) it embeds orm.BaseModel or +// orm.SoftDeleteModel instead of repeating those fields. +func renderModelFromTable(pkg, name, table string, cols []tableColumn) (string, error) { + has := map[string]tableColumn{} + for _, c := range cols { + has[c.name] = c + } + embed, skip := "", map[string]bool{} + if id, ok := has["id"]; ok && id.primary { + if t, _ := goType(id); strings.HasPrefix(t, "int") { + ca, caOK := has["created_at"] + ua, uaOK := has["updated_at"] + if caOK && uaOK { + ct, _ := goType(ca) + ut, _ := goType(ua) + if ct == "time.Time" && ut == "time.Time" { + embed, skip["id"], skip["created_at"], skip["updated_at"] = "BaseModel", true, true, true + if _, soft := has["deleted_at"]; soft { + embed, skip["deleted_at"] = "SoftDeleteModel", true + } + } + } + } + } + + naming := schema.NamingStrategy{} + var fields strings.Builder + imports := map[string]bool{} + used := map[string]bool{} + for _, c := range cols { + if skip[c.name] { + continue + } + field := fieldName(c.name) + for used[field] { + field += "_" + } + used[field] = true + typ, pointerable := goType(c) + if typ == "time.Time" { + imports["time"] = true + } + if typ == "json.RawMessage" { + imports["encoding/json"] = true + } + if c.nullable && pointerable && !c.primary { + typ = "*" + typ + } + var tags []string + if naming.ColumnName("", field) != c.name { + tags = append(tags, "column:"+c.name) + } + if c.primary && field != "ID" { + tags = append(tags, "primaryKey") + } + tag := "" + if len(tags) > 0 { + tag = " `gorm:\"" + strings.Join(tags, ";") + "\"`" + } + fmt.Fprintf(&fields, "\t%s %s%s\n", field, typ, tag) + } + + var b strings.Builder + fmt.Fprintf(&b, "package %s\n\nimport (\n", pkg) + paths := make([]string, 0, len(imports)) + for p := range imports { + paths = append(paths, p) + } + sort.Strings(paths) + for _, p := range paths { + fmt.Fprintf(&b, "\t%q\n", p) + } + if embed != "" { + if len(paths) > 0 { + b.WriteString("\n") + } + b.WriteString("\t\"github.com/LouisRiverstone/migro/orm\"\n") + } + fmt.Fprintf(&b, ")\n\n// %s mirrors the %q table. Generated by make:model --from-table; adjust types and add relations by hand.\ntype %s struct {\n", name, table, name) + if embed != "" { + fmt.Fprintf(&b, "\torm.%s\n", embed) + } + b.WriteString(fields.String()) + b.WriteString("}\n") + if naming.TableName(name) != table { + fmt.Fprintf(&b, "\nfunc (%s) TableName() string { return %q }\n", name, table) + } + src := b.String() + if len(paths) == 0 && embed == "" { + src = strings.Replace(src, "import (\n)\n\n", "", 1) + } + out, err := format.Source([]byte(src)) + if err != nil { + return "", migro.Wrap(migro.InvalidSchema, err, "generate model for table %s", table) + } + return string(out), nil +} + +// readTableColumns introspects table through the migrator. +func (c *call) readTableColumns(table string) ([]tableColumn, error) { + db, _, err := c.openDB() + if err != nil { + return nil, err + } + defer db.Close() + mg := db.Gorm.Migrator() + if !mg.HasTable(table) { + return nil, migro.Newf(migro.NotFound, "table %q does not exist", table) + } + cts, err := mg.ColumnTypes(table) + if err != nil { + return nil, migro.Wrap(migro.QueryFailed, err, "read columns of %s", table) + } + cols := make([]tableColumn, 0, len(cts)) + for _, ct := range cts { + tc := tableColumn{name: ct.Name(), dbType: ct.DatabaseTypeName()} + tc.length, _ = ct.Length() + tc.nullable, _ = ct.Nullable() + tc.primary, _ = ct.PrimaryKey() + cols = append(cols, tc) + } + return cols, nil +} diff --git a/docs/advanced-queries.md b/docs/advanced-queries.md index ad54c0c..b234d82 100644 --- a/docs/advanced-queries.md +++ b/docs/advanced-queries.md @@ -77,6 +77,8 @@ posts.Query().Select("user_id").GroupBy("user_id").Having("COUNT(*) > ?", 3).Get posts.Query().Distinct("user_id").Get(ctx) ``` +`GroupBy` quotes each name as an identifier. To group by an expression, use `GroupByRaw("DATE(created_at)")`; its text is sent as written, so never build it from user input. + ## Unions ```go diff --git a/docs/coming-from-gorm.md b/docs/coming-from-gorm.md new file mode 100644 index 0000000..edec388 --- /dev/null +++ b/docs/coming-from-gorm.md @@ -0,0 +1,65 @@ +--- +title: Coming from GORM +nav_order: 2.5 +description: Adopt migro in an existing GORM project without rewriting anything. +--- + +# Coming from GORM + +migro sits on top of GORM. Your models, `*gorm.DB` queries and hooks keep working, so you adopt it one model at a time. + +## Step 1: open through migro + +```go +db, err := migro.Open(migro.Config{Dialect: "postgres", DSN: dsn}) +// db.Gorm is the *gorm.DB you already use +users := db.Gorm.Where("active = ?", true).Find(&list) // unchanged +``` + +Nothing else changes. Migrations, seeders and the CLI work from this point. + +## Step 2: move schema changes to migrations + +Instead of `AutoMigrate`, describe the database in versioned files. If the database already exists, let migro write the first migration for you: + +``` +migro migration:diff baseline # compares your models with the live schema +migro migration:run +``` + +Or go the other way and generate models from tables you already have: + +``` +migro make:model Post --from-table=posts +``` + +The generated struct embeds `orm.BaseModel` (or `orm.SoftDeleteModel`) when the table has `id`, `created_at`, `updated_at` (and `deleted_at`). Otherwise it lists every column. Review the Go types: `decimal` becomes `float64`, JSON becomes `json.RawMessage`. + +## Step 3: opt a model in + +Embed `orm.BaseModel` where you had `gorm.Model`, and query through `orm.New`: + +| GORM | migro | +|---|---| +| `gorm.Model` | `orm.BaseModel` (`orm.SoftDeleteModel` for `DeletedAt`) | +| `db.First(&u, 1)` | `users.Find(ctx, 1)` | +| `db.Where("a = ?", 1).Find(&list)` | `users.Query().Where("a = ?", 1).Get(ctx)` | +| `db.Preload("Posts").Find(&list)` | `users.Query().With("Posts").Get(ctx)` | +| `db.Create(&u)` | `users.Create(ctx, &u)` | +| `db.Save(&u)` | `u.Save(ctx)`, which updates only changed columns | +| `db.Unscoped().Find(&list)` | `users.Query().WithTrashed().Get(ctx)` | +| `db.Transaction(func(tx *gorm.DB) error {...})` | `db.Transaction(ctx, func(tx *migro.DB) error {...})` | +| `db.Clauses(clause.OnConflict{...}).Create(&rows)` | `users.Upsert(ctx, rows, uniqueBy...)` | +| `db.Session(&gorm.Session{DryRun: true})` | `query.ToSQL(ctx)` | + +## What changes in practice + +- **Relations are fields.** Declare `Posts orm.HasMany[Post]` instead of a `[]Post` slice. Load them with `With`, or lazily with `u.Posts.Get(ctx)`. +- **Context is explicit.** Terminal methods take `ctx` as the first argument. +- **Errors carry codes.** Check `migro.CodeOf(err) == migro.NotFound` instead of `errors.Is(err, gorm.ErrRecordNotFound)`. See [Errors](errors.md). +- **Mass assignment is opt-in.** `CreateFrom` and `Fill` only accept columns listed in `Fillable()` when you define it. +- **Turn on strict mode** while you migrate: `db.ShouldBeStrict(true)` fails on lazy loading, which is how you find N+1 queries. See [Strict mode](strict-mode.md). + +## Staying on GORM where it fits + +You do not have to convert everything. A raw `db.Gorm.Raw(...)` or a hook-heavy model can stay as it is. Mixed code is the intended setup. diff --git a/docs/coming-from-laravel.md b/docs/coming-from-laravel.md new file mode 100644 index 0000000..db7a10c --- /dev/null +++ b/docs/coming-from-laravel.md @@ -0,0 +1,72 @@ +--- +title: Coming from Laravel or Lucid +nav_order: 2.6 +description: Eloquent, Lucid and artisan equivalents in migro. +--- + +# Coming from Laravel or Lucid + +migro follows Eloquent's and Lucid's names, so most code translates one to one. Where Go forces a difference, it is listed below. + +## Models and queries + +| Eloquent / Lucid | migro | +|---|---| +| `User::find(1)` | `users.Find(ctx, 1)` | +| `User::findOrFail(1)` | `users.FindOrFail(ctx, 1)` | +| `User::where('a', 1)->get()` | `users.Query().Where("a = ?", 1).Get(ctx)` | +| `->first()` / `->sole()` | `.First(ctx)` / `.Sole(ctx)` | +| `->with('posts')` | `.With("Posts")` | +| `->withCount('posts')` | `.WithCount("Posts")` | +| `->has('posts')` / `->whereHas(...)` | `.Has("Posts")` / `.WhereHas("Posts", fn)` | +| `->paginate(20)` | `.Paginate(ctx, page, 20)` | +| `->cursorPaginate()` | `.CursorPaginate(...)` | +| `->latest()` | `.Latest()` | +| `->lockForUpdate()` | `.LockForUpdate()` | +| `->withTrashed()` / `->onlyTrashed()` | `.WithTrashed()` / `.OnlyTrashed()` | +| `User::create([...])` | `users.CreateFrom(ctx, map[string]any{...})` | +| `firstOrCreate` / `updateOrCreate` | `FirstOrCreate` / `UpdateOrCreate` | +| `User::upsert(...)` | `users.Upsert(ctx, rows, uniqueBy...)` | +| `$user->save()` / `isDirty()` | `u.Save(ctx)` / `u.IsDirty("name")` | +| `$fillable` / `$hidden` / `$appends` | `Fillable()` / `Hidden()` / `Appends()` methods | +| global scopes | `GlobalScopes()` method; `WithoutGlobalScope(name)` | +| `Model::shouldBeStrict()` | `db.ShouldBeStrict(true)` | +| `$casts` | [casts](mutators-casting.md) (`orm.CastJSON()`, `CastHashed()`, ...) | +| API resources | [resources](resources.md) | + +## Relations + +`hasMany`, `belongsTo`, `belongsToMany`, `hasManyThrough` and the morph family are typed fields instead of methods: + +```go +type Post struct { + orm.BaseModel + UserID uint + Author orm.BelongsTo[User] `orm:"foreignKey:user_id"` + Tags orm.MorphToMany[Tag] `orm:"morph:taggable"` +} +``` + +Pivot writes (`attach`, `detach`, `sync`, `toggle`) are `Attach`, `Detach`, `Sync` and `Toggle`. + +## Migrations and seeders + +| artisan / ace | migro | +|---|---| +| `make:migration` | `migro make:migration` | +| `migrate`, `migrate:rollback`, `migrate:fresh --seed` | `migro migration:run`, `migration:rollback`, `migration:fresh --seed` (the `migrate:*` names also work) | +| `migrate:status` | `migro migration:status` | +| `db:seed --class=X` | `migro db:seed --class=X` | +| `schema:dump` | `migro schema:dump` | +| `make:model -mfs` | `migro make:model Name -m -f -s` | +| `db:show`, `db:table`, `model:show` | same names | + +Migrations are Go files with `Up` and `Down`. The [schema builder](schema-builder.md) mirrors Laravel's `Blueprint` (`Increments`, `ForeignID().Constrained()`, `Timestamps()`). + +## What differs on purpose + +- **`ctx` everywhere.** Go has no request-scoped global; pass `context.Context`. +- **Errors, not exceptions.** Every call returns an `error` with a code. See [Errors](errors.md). +- **No magic attribute access.** Fields are Go struct fields, and unknown columns do not exist at runtime. +- **Observers register explicitly** on an `events.Bus`: `events.Observe[User](bus, &UserObserver{})`. +- **Mass assignment** only applies to `Fill`/`CreateFrom`. Assigning struct fields directly is always allowed. diff --git a/docs/command-line.md b/docs/command-line.md index 0c23591..af75c96 100644 --- a/docs/command-line.md +++ b/docs/command-line.md @@ -88,7 +88,7 @@ func main() { | `db:seed` | Run seeders. Starts from `DatabaseSeeder` when you registered one (it calls the others with `seed.Call`), otherwise runs every seeder by name. `--class=UserSeeder` runs one; `--once` skips those that already ran. | | `make:seeder ` | New seeder. | | `make:factory ` | New factory. `--model=example.com/app/models.User` names the model (default: `/app/models`). | -| `make:model ` | New model. `-m` also creates its migration, `-f` a factory, `-s` a seeder, `-a` all three. `--uuid` or `--ulid` embeds a string-key model. | +| `make:model ` | New model. `-m` also creates its migration, `-f` a factory, `-s` a seeder, `-a` all three. `--uuid` or `--ulid` embeds a string-key model. `--from-table=name` reads the live table and writes the struct for you (column types, nullable pointers, `gorm` tags); it needs a database connection and cannot be combined with `-m`, `-a`, `--uuid` or `--ulid`. | | `help` | List commands. | Every command accepts `--database=` to pick a connection, and `--force` / `--no-interaction` (`-n`). Exit codes: `0` ok, `1` error, `2` bad usage. diff --git a/docs/databases.md b/docs/databases.md index 2b3642d..62addd3 100644 --- a/docs/databases.md +++ b/docs/databases.md @@ -11,18 +11,35 @@ description: What is verified on each database, and per-database behavior and li | Database | Dialect name | Verified how | Transactional DDL | |---|---|---|---| | SQLite | `sqlite` | Full test suite in CI (blocking) | yes | -| PostgreSQL | `postgres` | Full suite in a CI job that does not block merges yet | yes | -| MySQL | `mysql` | Full suite in a CI job that does not block merges yet | no | -| MariaDB | `mariadb` | Generated SQL unit-tested; never run on a live server | no | -| CockroachDB | `cockroachdb` | Generated SQL unit-tested; never run on a live server | no (schema changes are not wrapped) | +| PostgreSQL | `postgres` | Full suite in a CI job (blocking) | yes | +| MySQL | `mysql` | Full suite in a CI job (blocking) | no | +| MariaDB | `mariadb` | Full suite in a non-blocking CI job, results pending | no | +| CockroachDB | `cockroachdb` | Full suite in a non-blocking CI job, results pending | no (schema changes are not wrapped) | | Redshift | `redshift` | Generated SQL unit-tested; never run on a live server | yes | -| SQL Server | `sqlserver` | Generated SQL unit-tested; never run on a live server | yes | +| SQL Server | `sqlserver` | Full suite in a non-blocking CI job, results pending | yes | | Oracle | `oracle` | Generated SQL unit-tested; never run on a live server | no | "Never run on a live server" means the SQL migro produces is checked against expected fragments, but nobody has executed it against the real database yet. Expect to find rough edges there, and please report them or [help verify](contributing.md#running-tests-against-a-real-database). "Transactional DDL" decides whether a migration runs inside a transaction (see [Migrations](migrations.md#behavior-to-know)). Where it is `no`, a migration that fails halfway can leave partial changes, so keep migrations small. +## Feature support + +Every dialect handles the schema builder, `With`/`WhereHas`, aggregates, pagination and casts. These are the places where it differs: + +| Database | Row locks | JSON paths | Full-text | `Upsert` | `InsertOrIgnore` | +|---|---|---|---|---|---| +| PostgreSQL | update, share | yes | yes | `ON CONFLICT` | yes | +| CockroachDB | update, share | yes | yes | `ON CONFLICT` | yes | +| Redshift | no | yes | no | no | no | +| MySQL | update, share | yes | yes | `ON DUPLICATE KEY` | yes | +| MariaDB | update, share | yes | yes | `ON DUPLICATE KEY` | yes | +| SQLite | no (writes lock the file) | yes | no | `ON CONFLICT` | yes | +| SQL Server | no | yes | no | `MERGE` | no, use `Upsert` | +| Oracle | update only | yes | no | `MERGE` | no, use `Upsert` | + +"No" means the call returns an `UNSUPPORTED_FEATURE` error instead of running something wrong. Check the code with `migro.CodeOf(err)`. Native enums exist on MySQL and MariaDB only; elsewhere `Enum` is a string with a `CHECK`. + ## Per-database notes - **MySQL / MariaDB:** `Increments`/`BigIncrements` are `unsigned`, so a foreign-key column must be `Integer(...).Unsigned()` / `BigInteger(...).Unsigned()` to match, otherwise MySQL rejects the constraint. `ForeignID` already does this. Enums are native. DDL is not transactional, so a migration that fails halfway leaves its earlier statements applied. An index on a column that already has a foreign key replaces the key's automatic index, and MySQL then refuses to drop it (error 1553) until the key is gone. diff --git a/internal/testdb/testdb.go b/internal/testdb/testdb.go index 404a94c..580b2b3 100644 --- a/internal/testdb/testdb.go +++ b/internal/testdb/testdb.go @@ -11,6 +11,7 @@ import ( _ "github.com/LouisRiverstone/migro/dialect/mysql" _ "github.com/LouisRiverstone/migro/dialect/postgres" _ "github.com/LouisRiverstone/migro/dialect/sqlite" + _ "github.com/LouisRiverstone/migro/dialect/sqlserver" ) func Open(t testing.TB) *migro.DB { diff --git a/orm/example_test.go b/orm/example_test.go new file mode 100644 index 0000000..3237b52 --- /dev/null +++ b/orm/example_test.go @@ -0,0 +1,122 @@ +package orm_test + +import ( + "context" + "fmt" + "os" + "path/filepath" + + "github.com/LouisRiverstone/migro" + _ "github.com/LouisRiverstone/migro/dialect/sqlite" + "github.com/LouisRiverstone/migro/orm" + "github.com/LouisRiverstone/migro/schema" +) + +type Author struct { + orm.BaseModel + Name string + Books orm.HasMany[Book] `orm:"foreignKey:author_id"` +} + +type Book struct { + orm.BaseModel + AuthorID uint + Title string + Author orm.BelongsTo[Author] `orm:"foreignKey:author_id"` +} + +// exampleDB opens a throwaway SQLite database with the two tables above. +func exampleDB() (*migro.DB, func()) { + dir, _ := os.MkdirTemp("", "migro-example") + db, err := migro.Open(migro.Config{Dialect: "sqlite", DSN: filepath.Join(dir, "example.db")}) + if err != nil { + panic(err) + } + ctx := context.Background() + s := schema.New(db) + must0 := func(err error) { + if err != nil { + panic(err) + } + } + must0(s.CreateTable(ctx, "authors", func(t *schema.Table) { t.Increments("id"); t.String("name"); t.Timestamps() })) + must0(s.CreateTable(ctx, "books", func(t *schema.Table) { + t.Increments("id") + t.Integer("author_id") + t.String("title") + t.Timestamps() + })) + return db, func() { _ = db.Close(); _ = os.RemoveAll(dir) } +} + +func ExampleModel_Create() { + db, done := exampleDB() + defer done() + ctx := context.Background() + + authors := orm.New[Author](db) + a := &Author{Name: "Ursula"} + if err := authors.Create(ctx, a); err != nil { + panic(err) + } + found, _ := authors.Find(ctx, a.ID) + fmt.Println(found.Name, found.ID) + // Output: Ursula 1 +} + +func ExampleQuery_With() { + db, done := exampleDB() + defer done() + ctx := context.Background() + + authors, books := orm.New[Author](db), orm.New[Book](db) + a := &Author{Name: "Ursula"} + _ = authors.Create(ctx, a) + _ = books.CreateMany(ctx, []Book{{AuthorID: a.ID, Title: "A Wizard of Earthsea"}, {AuthorID: a.ID, Title: "The Dispossessed"}}) + + // One query for authors, one for all their books: never one query per author. + list, _ := authors.Query().With("Books").Get(ctx) + for _, au := range list { + for _, b := range au.Books.Items() { + fmt.Println(au.Name, "-", b.Title) + } + } + // Output: + // Ursula - A Wizard of Earthsea + // Ursula - The Dispossessed +} + +func ExampleQuery_Paginate() { + db, done := exampleDB() + defer done() + ctx := context.Background() + + books := orm.New[Book](db) + rows := make([]Book, 25) + for i := range rows { + rows[i] = Book{AuthorID: 1, Title: fmt.Sprintf("book %02d", i+1)} + } + _ = books.CreateMany(ctx, rows) + + page, _ := books.Query().OrderBy("id", "asc").Paginate(ctx, 2, 10) + fmt.Println(len(page.Data), page.Total, page.CurrentPage) + // Output: 10 25 2 +} + +func ExampleQuery_Has() { + db, done := exampleDB() + defer done() + ctx := context.Background() + + authors, books := orm.New[Author](db), orm.New[Book](db) + a, b := &Author{Name: "with books"}, &Author{Name: "without books"} + _ = authors.Create(ctx, a) + _ = authors.Create(ctx, b) + _ = books.Create(ctx, &Book{AuthorID: a.ID, Title: "x"}) + + list, _ := authors.Query().Has("Books").Get(ctx) + for _, au := range list { + fmt.Println(au.Name) + } + // Output: with books +} diff --git a/orm/guarantees_test.go b/orm/guarantees_test.go new file mode 100644 index 0000000..8d8d979 --- /dev/null +++ b/orm/guarantees_test.go @@ -0,0 +1,138 @@ +package orm_test + +import ( + "context" + "strings" + "testing" + + "github.com/LouisRiverstone/migro" + "github.com/LouisRiverstone/migro/orm" +) + +// ---- no N+1 ----------------------------------------------------------------------------- + +// Eager loading is the library's central promise: the number of statements must not depend on +// how many rows come back. +func TestEagerLoadingQueryCountIsConstant(t *testing.T) { + db, ctx := eSeed(t) + + load := func() int { + return countQueries(db, func() { + posts := must(orm.New[ePost](db).Query(). + With("Author").With("Comments").With("Tags").WithCount("Comments"). + OrderBy("id", "asc").Get(ctx)) + for _, p := range posts { // touching loaded relations must not query again + _, _ = p.Author.Get(ctx) + _ = p.Comments.Items() + } + }) + } + small := load() + + extra := make([]ePost, 40) + for i := range extra { + extra[i] = ePost{UserID: uint(i%3) + 1, Title: "bulk"} + } + ok(t, orm.New[ePost](db).CreateMany(ctx, extra)) + large := load() + + if small != large { + t.Fatalf("query count grew with the data: %d statements for 3 posts, %d for 43", small, large) + } + if small > 6 { + t.Errorf("eager loading three relations plus a count took %d statements; expected one per relation", small) + } +} + +func countQueries(db *migro.DB, fn func()) int { + n := 0 + off := db.Listen(func(migro.QueryEvent) { n++ }) + defer off() + fn() + return n +} + +// ---- identifiers are never spliced into SQL ---------------------------------------------- + +// outsideQuotes drops every quoted run, so what is left is SQL the library itself wrote. +func outsideQuotes(sql string) string { + var b strings.Builder + var open rune + for _, r := range sql { + switch { + case open != 0: + if r == open { + open = 0 + } + case r == '"' || r == '`' || r == '\'': + open = r + default: + b.WriteRune(r) + } + } + return b.String() +} + +// Methods that take a column or path name from the caller. Application code should not feed them +// user input, but when it does the name must stay inside identifier quotes. +func TestIdentifierArgumentsAreQuoted(t *testing.T) { + ctx := context.Background() + payloads := []string{ + `id; DROP TABLE e_users; --`, + `id"; DROP TABLE e_users; --`, + "id`; DROP TABLE e_users; --", + `id) OR (1=1`, + } + type attempt struct { + name string + run func(q *orm.Query[eUser], p string) error + } + attempts := []attempt{ + {"WhereIn", func(q *orm.Query[eUser], p string) error { _, err := q.WhereIn(p, []int{1}).Get(ctx); return err }}, + {"WhereNotIn", func(q *orm.Query[eUser], p string) error { _, err := q.WhereNotIn(p, []int{1}).Get(ctx); return err }}, + {"WhereNull", func(q *orm.Query[eUser], p string) error { _, err := q.WhereNull(p).Get(ctx); return err }}, + {"WhereNotNull", func(q *orm.Query[eUser], p string) error { _, err := q.WhereNotNull(p).Get(ctx); return err }}, + {"WhereBetween", func(q *orm.Query[eUser], p string) error { _, err := q.WhereBetween(p, 1, 2).Get(ctx); return err }}, + {"WhereLike", func(q *orm.Query[eUser], p string) error { _, err := q.WhereLike(p, "%a%").Get(ctx); return err }}, + {"WhereColumn", func(q *orm.Query[eUser], p string) error { _, err := q.WhereColumn(p, "=", "id").Get(ctx); return err }}, + {"WhereColumn right", func(q *orm.Query[eUser], p string) error { _, err := q.WhereColumn("id", "=", p).Get(ctx); return err }}, + {"WhereJSON column", func(q *orm.Query[eUser], p string) error { _, err := q.WhereJSON(p, "a", "=", 1).Get(ctx); return err }}, + {"WhereJSON path", func(q *orm.Query[eUser], p string) error { + _, err := q.WhereJSON("name", p, "=", 1).Get(ctx) + return err + }}, + {"WhereJSON operator", func(q *orm.Query[eUser], p string) error { + _, err := q.WhereJSON("name", "a", p, 1).Get(ctx) + return err + }}, + {"OrderBy", func(q *orm.Query[eUser], p string) error { _, err := q.OrderBy(p, "asc").Get(ctx); return err }}, + {"OrderBy direction", func(q *orm.Query[eUser], p string) error { _, err := q.OrderBy("id", p).Get(ctx); return err }}, + {"OrderByDesc", func(q *orm.Query[eUser], p string) error { _, err := q.OrderByDesc(p).Get(ctx); return err }}, + {"Latest", func(q *orm.Query[eUser], p string) error { _, err := q.Latest(p).Get(ctx); return err }}, + {"Oldest", func(q *orm.Query[eUser], p string) error { _, err := q.Oldest(p).Get(ctx); return err }}, + {"GroupBy", func(q *orm.Query[eUser], p string) error { _, err := q.GroupBy(p).Get(ctx); return err }}, + {"Sum", func(q *orm.Query[eUser], p string) error { _, err := q.Sum(ctx, p); return err }}, + {"Max", func(q *orm.Query[eUser], p string) error { _, err := q.Max(ctx, p); return err }}, + {"FirstWhere", func(q *orm.Query[eUser], p string) error { _, err := q.FirstWhere(ctx, p, 1); return err }}, + } + for _, a := range attempts { + for _, p := range payloads { + t.Run(a.name, func(t *testing.T) { + db, _ := eSeed(t) // a fresh database per attempt: one successful injection must not hide the rest + var seen []string + off := db.Listen(func(e migro.QueryEvent) { seen = append(seen, e.SQL) }) + _ = a.run(orm.New[eUser](db).Query(), p) // an error is the right outcome; what matters is the SQL + off() + for _, sql := range seen { + rest := strings.ToUpper(outsideQuotes(sql)) + if strings.Contains(rest, "DROP") || strings.Contains(rest, "OR (1=1") || strings.Contains(rest, "--") { + t.Errorf("payload %q escaped identifier quoting:\n%s", p, sql) + } + } + if n, err := orm.New[eUser](db).Query().Count(context.Background()); err != nil || n != 3 { + t.Fatalf("e_users damaged after %s(%q): %d rows, %v", a.name, p, n, err) + } + }) + } + } +} diff --git a/orm/query_where.go b/orm/query_where.go index 673e0fa..8c1a273 100644 --- a/orm/query_where.go +++ b/orm/query_where.go @@ -158,14 +158,22 @@ func (q *Query[T]) Sole(ctx context.Context) (*T, error) { // ---- grouping, distinct, union ---------------------------------------------------------------- -// GroupBy groups by columns; combine it with Select and Having for aggregates. +// GroupBy groups by columns (each one is quoted as an identifier); combine it with Select and Having +// for aggregates. Use GroupByRaw to group by an expression. func (q *Query[T]) GroupBy(cols ...string) *Query[T] { for _, c := range cols { - q.g = q.g.Group(c) // GORM quotes the name itself + q.g = q.g.Clauses(clause.GroupBy{Columns: []clause.Column{{Name: q.db.Dialect.Quote(c), Raw: true}}}) } return q } +// GroupByRaw groups by a SQL expression such as "DATE(created_at)". The text is sent as written, so +// never build it from user input. +func (q *Query[T]) GroupByRaw(expr string) *Query[T] { + q.g = q.g.Group(expr) + return q +} + // Having filters groups: Having("COUNT(*) > ?", 3). Never concatenate input into the condition. func (q *Query[T]) Having(query any, args ...any) *Query[T] { q.g = q.g.Having(query, args...) From 363c30419701d14cd9b5354536c01e266af65501 Mon Sep 17 00:00:00 2001 From: Luiz Neves Date: Tue, 17 Nov 2026 08:14:44 -0300 Subject: [PATCH 2/7] fix: dialect fixes found by the new CI jobs; govulncheck on the latest Go - CockroachDB: identity columns instead of SERIAL (sequential ids), DROP INDEX ... CASCADE for unique constraints - SQL Server: RESTRICT becomes NO ACTION; aggregates no longer add an ORDER BY via LIMIT - Tests tolerate UNSUPPORTED_FEATURE for row locks and InsertOrIgnore; the injection test understands [bracket] quoting - CI: SQL Server tests run in their own database; govulncheck uses the latest Go; golang.org/x/text v0.41.0 --- .github/workflows/ci.yml | 9 +++++++-- dialect/postgres/postgres.go | 15 ++++++++++++++- go.mod | 4 ++-- go.sum | 8 ++++---- orm/guarantees_test.go | 24 +++++++++++++++++------- orm/lifecycle_test.go | 8 +++++++- orm/query_advanced_test.go | 8 ++++++-- orm/query_ext.go | 4 +++- schema/schema_test.go | 2 +- schema/table.go | 3 +++ 10 files changed, 64 insertions(+), 21 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 22f6596..b189ccb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,8 +28,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + # The latest patch release: go.mod pins the minimum Go, and the standard library fixes come with the toolchain. - uses: actions/setup-go@v5 - with: { go-version-file: go.mod } + with: { go-version: stable } - run: go run golang.org/x/vuln/cmd/govulncheck@v1.1.4 ./... postgres: @@ -119,9 +120,13 @@ jobs: --health-interval 10s --health-retries 20 env: MIGRO_TEST_DIALECT: sqlserver - MIGRO_TEST_DSN: sqlserver://sa:Migro_Passw0rd@localhost:1433?database=master + MIGRO_TEST_DSN: sqlserver://sa:Migro_Passw0rd@localhost:1433?database=migro steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: { go-version-file: go.mod } + - name: create the test database # master holds system tables the suite would try to drop + run: | + id=$(docker ps -q --filter ancestor=mcr.microsoft.com/mssql/server:2022-latest) + docker exec "$id" /opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P Migro_Passw0rd -Q "CREATE DATABASE migro" - run: go test -p 1 -count=1 ./... diff --git a/dialect/postgres/postgres.go b/dialect/postgres/postgres.go index 1092ca2..5c04951 100644 --- a/dialect/postgres/postgres.go +++ b/dialect/postgres/postgres.go @@ -116,6 +116,10 @@ func (d *pgDialect) AutoIncrement(big bool) string { } return "integer identity(1,1) primary key" } + if d.v == cockroach { + // SERIAL is unique_rowid() there: huge, non-sequential values. An identity column counts 1, 2, 3. + return "bigint generated by default as identity primary key" + } if big { return "bigserial primary key" } @@ -133,10 +137,19 @@ func (d *pgDialect) RenameColumn(t, from, to string) string { return fmt.Sprintf("ALTER TABLE %s RENAME COLUMN %s TO %s", d.Quote(t), d.Quote(from), d.Quote(to)) } func (d *pgDialect) DropIndex(_, name string) string { return "DROP INDEX " + d.Quote(name) } + +// DropConstraint is used for unique constraints. CockroachDB backs them with an index and refuses +// ALTER TABLE ... DROP CONSTRAINT for them. func (d *pgDialect) DropConstraint(t, name string) string { + if d.v == cockroach { + return fmt.Sprintf("DROP INDEX %s@%s CASCADE", d.Quote(t), d.Quote(name)) + } + return d.dropTableConstraint(t, name) +} +func (d *pgDialect) dropTableConstraint(t, name string) string { return fmt.Sprintf("ALTER TABLE %s DROP CONSTRAINT %s", d.Quote(t), d.Quote(name)) } -func (d *pgDialect) DropForeign(t, name string) string { return d.DropConstraint(t, name) } +func (d *pgDialect) DropForeign(t, name string) string { return d.dropTableConstraint(t, name) } // Redshift has no CREATE INDEX. func (d *pgDialect) SupportsIndexes() bool { return d.v != redshift } diff --git a/go.mod b/go.mod index 4f3efec..982a3c6 100644 --- a/go.mod +++ b/go.mod @@ -33,9 +33,9 @@ require ( github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/shopspring/decimal v1.4.0 // indirect github.com/sijms/go-ora/v2 v2.9.0 // indirect - golang.org/x/sync v0.20.0 // indirect + golang.org/x/sync v0.22.0 // indirect golang.org/x/sys v0.45.0 // indirect - golang.org/x/text v0.37.0 // indirect + golang.org/x/text v0.41.0 // indirect modernc.org/libc v1.22.5 // indirect modernc.org/mathutil v1.5.0 // indirect modernc.org/memory v1.5.0 // indirect diff --git a/go.sum b/go.sum index efd5aef..7ad4834 100644 --- a/go.sum +++ b/go.sum @@ -77,13 +77,13 @@ golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988= golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc= golang.org/x/net v0.54.0 h1:2zJIZAxAHV/OHCDTCOHAYehQzLfSXuf/5SoL/Dv6w/w= golang.org/x/net v0.54.0/go.mod h1:Sj4oj8jK6XmHpBZU/zWHw3BV3abl4Kvi+Ut7cQcY+cQ= -golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= -golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY= golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= -golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= -golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= +golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/orm/guarantees_test.go b/orm/guarantees_test.go index 8d8d979..059da62 100644 --- a/orm/guarantees_test.go +++ b/orm/guarantees_test.go @@ -54,18 +54,28 @@ func countQueries(db *migro.DB, fn func()) int { // ---- identifiers are never spliced into SQL ---------------------------------------------- -// outsideQuotes drops every quoted run, so what is left is SQL the library itself wrote. +// outsideQuotes drops every quoted run ("x", `x`, 'x', [x]), honouring the doubled closing character +// that escapes itself, so what is left is SQL the library itself wrote. func outsideQuotes(sql string) string { var b strings.Builder - var open rune - for _, r := range sql { + rs := []rune(sql) + var closing rune + for i := 0; i < len(rs); i++ { + r := rs[i] switch { - case open != 0: - if r == open { - open = 0 + case closing != 0: + if r != closing { + continue } + if i+1 < len(rs) && rs[i+1] == closing { // escaped: stays inside the quote + i++ + continue + } + closing = 0 case r == '"' || r == '`' || r == '\'': - open = r + closing = r + case r == '[': + closing = ']' default: b.WriteRune(r) } diff --git a/orm/lifecycle_test.go b/orm/lifecycle_test.go index b01e21a..6ca17ba 100644 --- a/orm/lifecycle_test.go +++ b/orm/lifecycle_test.go @@ -278,7 +278,13 @@ func TestUpsertInsertOrIgnoreFirstOrNew(t *testing.T) { t.Fatalf("needs uniqueBy: %v", err) } - ok(t, things.InsertOrIgnore(ctx, []uThing{{SKU: "a", Qty: 999}, {SKU: "d", Qty: 4}})) + err := things.InsertOrIgnore(ctx, []uThing{{SKU: "a", Qty: 999}, {SKU: "d", Qty: 4}}) + if migro.CodeOf(err) == migro.UnsupportedFeature { + // SQL Server, Oracle and Redshift fail loudly instead of running a plain INSERT. Reach the same state another way. + ok(t, things.Upsert(ctx, []uThing{{SKU: "d", Qty: 4}}, []string{"sku"}, nil)) + err = nil + } + ok(t, err) if a := must(things.FindBy(ctx, "sku", "a")); a.Qty != 10 { t.Fatalf("InsertOrIgnore must keep the existing row: %+v", a) } diff --git a/orm/query_advanced_test.go b/orm/query_advanced_test.go index 5657abb..8deab5d 100644 --- a/orm/query_advanced_test.go +++ b/orm/query_advanced_test.go @@ -85,8 +85,12 @@ func TestSoleFirstWhereLocks(t *testing.T) { t.Fatalf("FirstWhere: %+v", u) } // SQLite ignores row locks, so the query still runs. Get, not Count: PostgreSQL refuses a lock with an aggregate. - if got := must(users.Query().LockForUpdate().SharedLock().Get(ctx)); len(got) != 3 { - t.Fatalf("locks: %d", len(got)) + got, err := users.Query().LockForUpdate().SharedLock().Get(ctx) + if migro.CodeOf(err) == migro.UnsupportedFeature { + return // databases without row locks refuse instead of silently ignoring the request + } + if err != nil || len(got) != 3 { + t.Fatalf("locks: %d %v", len(got), err) } } diff --git a/orm/query_ext.go b/orm/query_ext.go index 2dc9366..a23a6d3 100644 --- a/orm/query_ext.go +++ b/orm/query_ext.go @@ -102,7 +102,9 @@ func asFloat(v any) float64 { func (q *Query[T]) scalar(ctx context.Context, expr string) (any, error) { var row map[string]any - if err := q.clone().g.WithContext(ctx).Select(expr + " AS v").Take(&row).Error; err != nil { + // Scan, not Take: an aggregate always returns one row, and a LIMIT forces SQL Server to add an + // ORDER BY on a column the aggregate does not group by. + if err := q.clone().g.WithContext(ctx).Select(expr + " AS v").Scan(&row).Error; err != nil { return nil, wrap(err, "aggregate") } if b, ok := row["v"].([]byte); ok { // some drivers return decimals as bytes diff --git a/schema/schema_test.go b/schema/schema_test.go index 6e6b0fc..73b7aba 100644 --- a/schema/schema_test.go +++ b/schema/schema_test.go @@ -29,7 +29,7 @@ func users(t *schema.Table) { func TestCreateSQLPerDialect(t *testing.T) { cases := map[string][]string{ "postgres": {`"id" serial primary key`, `"active" boolean DEFAULT TRUE NOT NULL`, `CHECK ("role" IN ('admin', 'user'))`, `"created_at" timestamptz`, `numeric(10,2)`}, - "cockroachdb": {`"id" serial primary key`}, + "cockroachdb": {`"id" bigint generated by default as identity primary key`}, "redshift": {`integer identity(1,1) primary key`}, "mysql": {"`id` int unsigned not null auto_increment primary key", "`role` enum('admin','user') DEFAULT 'user'", "`active` tinyint(1) DEFAULT 1 NOT NULL"}, "mariadb": {"`email` varchar(120) NOT NULL"}, diff --git a/schema/table.go b/schema/table.go index b0519af..db5fcd8 100644 --- a/schema/table.go +++ b/schema/table.go @@ -331,6 +331,9 @@ func (f *Foreign) sql(d dialect.Dialect, t *Table) (string, error) { if !fkActions[up] { return "", migro.Newf(migro.InvalidSchema, "foreign key on %q: invalid action %q", t.name, a[1]) } + if up == "RESTRICT" && d.Name() == "sqlserver" { + up = "NO ACTION" // SQL Server has no RESTRICT; NO ACTION also refuses the change + } s += " " + a[0] + " " + up } return s, nil From 68977bb2dfe54ed0323d632eceeab18b6121d4d2 Mon Sep 17 00:00:00 2001 From: Luiz Neves Date: Tue, 17 Nov 2026 08:15:28 -0300 Subject: [PATCH 3/7] ci: govulncheck v1.9.0 (v1.1.4 crashes on the newest Go) --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b189ccb..25187cd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,7 +31,7 @@ jobs: # The latest patch release: go.mod pins the minimum Go, and the standard library fixes come with the toolchain. - uses: actions/setup-go@v5 with: { go-version: stable } - - run: go run golang.org/x/vuln/cmd/govulncheck@v1.1.4 ./... + - run: go run golang.org/x/vuln/cmd/govulncheck@v1.9.0 ./... postgres: runs-on: ubuntu-latest From 649e3e6c8f7be01d5d6b067d244ad6081937dd79 Mon Sep 17 00:00:00 2001 From: Luiz Neves Date: Tue, 17 Nov 2026 08:49:21 -0300 Subject: [PATCH 4/7] fix: PostgreSQL and SQL Server findings from CI - Min/Max return int64 for every integer width, so the result type no longer depends on the driver - SQL Server: AVG over an integer column is cast to float; a cascading self-referencing foreign key is refused with a clear error - Tests: ToSQL accepts FETCH NEXT, the self-referencing cascade check skips SQL Server, the fixture picks NO ACTION there --- .../20260201000007_create_categories_table.go | 6 +++++- integration/pipeline_test.go | 3 +++ orm/query_ext.go | 21 ++++++++++++++++--- orm/relation_aggregate.go | 3 +++ orm/strict_test.go | 2 +- schema/table.go | 3 +++ 6 files changed, 33 insertions(+), 5 deletions(-) diff --git a/integration/database/migrations/20260201000007_create_categories_table.go b/integration/database/migrations/20260201000007_create_categories_table.go index bb64f27..f05b454 100644 --- a/integration/database/migrations/20260201000007_create_categories_table.go +++ b/integration/database/migrations/20260201000007_create_categories_table.go @@ -17,7 +17,11 @@ func (CreateCategoriesTable) Up(ctx context.Context, s *schema.Builder) error { t.Increments("id") t.Integer("parent_id").Unsigned().Nullable() t.String("name").NotNull() - t.Foreign("parent_id").References("categories", "id").OnDelete("CASCADE").Named("categories_parent_fk") + onDelete := "CASCADE" + if s.DB().Dialect.Name() == "sqlserver" { + onDelete = "NO ACTION" // SQL Server cannot cascade through a self-referencing key + } + t.Foreign("parent_id").References("categories", "id").OnDelete(onDelete).Named("categories_parent_fk") t.Timestamps() }) } diff --git a/integration/pipeline_test.go b/integration/pipeline_test.go index 2a4fcdd..3fbb764 100644 --- a/integration/pipeline_test.go +++ b/integration/pipeline_test.go @@ -222,6 +222,9 @@ func TestReferentialActions(t *testing.T) { }) t.Run("CASCADE walks a self-referencing tree", func(t *testing.T) { + if db.Dialect.Name() == "sqlserver" { + t.Skip("SQL Server cannot cascade through a self-referencing key") + } mustExec(t, db, "DELETE FROM categories WHERE id = 1") // Tech -> Databases if n := count(t, db, "categories"); n != 0 { t.Fatalf("whole tree should be gone, %d left", n) diff --git a/orm/query_ext.go b/orm/query_ext.go index a23a6d3..4b05d93 100644 --- a/orm/query_ext.go +++ b/orm/query_ext.go @@ -62,7 +62,11 @@ func (q *Query[T]) Sum(ctx context.Context, col string) (float64, error) { return q.aggregate(ctx, "COALESCE(SUM("+q.db.Dialect.Quote(col)+"), 0)") } func (q *Query[T]) Avg(ctx context.Context, col string) (float64, error) { - return q.aggregate(ctx, "COALESCE(AVG("+q.db.Dialect.Quote(col)+"), 0)") + c := q.db.Dialect.Quote(col) + if q.db.Dialect.Name() == "sqlserver" { + c = "CAST(" + c + " AS float)" // AVG over an integer column truncates there + } + return q.aggregate(ctx, "COALESCE(AVG("+c+"), 0)") } // Min and Max keep the column's own type (nil when no row matches). @@ -107,8 +111,19 @@ func (q *Query[T]) scalar(ctx context.Context, expr string) (any, error) { if err := q.clone().g.WithContext(ctx).Select(expr + " AS v").Scan(&row).Error; err != nil { return nil, wrap(err, "aggregate") } - if b, ok := row["v"].([]byte); ok { // some drivers return decimals as bytes - return string(b), nil + switch v := row["v"].(type) { + case []byte: // some drivers return decimals as bytes + return string(v), nil + case int8: + return int64(v), nil + case int16: + return int64(v), nil + case int32: // the driver picks the column's width; callers should not depend on it + return int64(v), nil + case int: + return int64(v), nil + case float32: + return float64(v), nil } return row["v"], nil } diff --git a/orm/relation_aggregate.go b/orm/relation_aggregate.go index 7277300..0ad7fa2 100644 --- a/orm/relation_aggregate.go +++ b/orm/relation_aggregate.go @@ -142,6 +142,9 @@ func (d *relDef) aggregateInto(ctx context.Context, db *migro.DB, owners []refle if len(keys) > 0 { var rows []map[string]any ownerCol := q(ownerRaw) + if fn == "AVG" && db.Dialect.Name() == "sqlserver" { + col = "CAST(" + col + " AS float)" // AVG over an integer column truncates there + } err := g.Select(ownerCol+" AS k, "+fn+"("+col+") AS v"). Where(ownerCol+" IN ?", keys).Group(ownerRaw).Find(&rows).Error if err != nil { diff --git a/orm/strict_test.go b/orm/strict_test.go index a5721b9..f5091d7 100644 --- a/orm/strict_test.go +++ b/orm/strict_test.go @@ -90,7 +90,7 @@ func TestQueryLogListenAndToSQL(t *testing.T) { sql, err := users.Query().Where("name = ?", "ana").Limit(3).ToSQL(ctx) ok(t, err) - if !strings.Contains(sql, "ana") || !strings.Contains(sql, "LIMIT") || strings.Contains(sql, "?") { + if !strings.Contains(sql, "ana") || (!strings.Contains(sql, "LIMIT") && !strings.Contains(sql, "FETCH NEXT")) || strings.Contains(sql, "?") { t.Fatalf("to sql: %s", sql) } if len(db.QueryLog()) != 0 { diff --git a/schema/table.go b/schema/table.go index db5fcd8..03bc62d 100644 --- a/schema/table.go +++ b/schema/table.go @@ -331,6 +331,9 @@ func (f *Foreign) sql(d dialect.Dialect, t *Table) (string, error) { if !fkActions[up] { return "", migro.Newf(migro.InvalidSchema, "foreign key on %q: invalid action %q", t.name, a[1]) } + if d.Name() == "sqlserver" && f.refTable == t.name && (up == "CASCADE" || up == "SET NULL" || up == "SET DEFAULT") { + return "", migro.Newf(migro.UnsupportedFeature, "sqlserver cannot %s on a self-referencing foreign key (%q): use NO ACTION and delete children first", strings.ToLower(a[0]+" "+up), t.name) + } if up == "RESTRICT" && d.Name() == "sqlserver" { up = "NO ACTION" // SQL Server has no RESTRICT; NO ACTION also refuses the change } From e8d4aee1610de2e34e6b6fae91410aad776a028b Mon Sep 17 00:00:00 2001 From: Luiz Neves Date: Tue, 17 Nov 2026 08:55:57 -0300 Subject: [PATCH 5/7] fix(sqlserver): drop a column's DEFAULT constraint first; make pipeline tests portable - DropColumn on SQL Server removes the auto-named DEFAULT constraint before the column - Tests bind booleans instead of the TRUE literal and expect NO ACTION for the self-referencing key on SQL Server --- dialect/features.go | 6 ++++++ dialect/sqlserver/sqlserver.go | 14 ++++++++++++++ integration/pipeline_test.go | 18 +++++++++++++----- schema/schema_test.go | 25 +++++++++++++++++++++++++ schema/table.go | 4 ++++ 5 files changed, 62 insertions(+), 5 deletions(-) diff --git a/dialect/features.go b/dialect/features.go index 7555e57..ce3a92b 100644 --- a/dialect/features.go +++ b/dialect/features.go @@ -79,3 +79,9 @@ func JSONPathString(path []string) string { } return b.String() } + +// ColumnDropper is implemented by dialects whose DROP COLUMN needs more than one statement. +type ColumnDropper interface { + // DropColumnSQL returns the statements that drop table.column, in order. + DropColumnSQL(table, column string) []string +} diff --git a/dialect/sqlserver/sqlserver.go b/dialect/sqlserver/sqlserver.go index fd4224a..0a25950 100644 --- a/dialect/sqlserver/sqlserver.go +++ b/dialect/sqlserver/sqlserver.go @@ -3,6 +3,7 @@ package sqlserver import ( "fmt" + "strings" "github.com/LouisRiverstone/migro/dialect" "gorm.io/driver/sqlserver" @@ -100,3 +101,16 @@ func (d *msDialect) DatePart(col string, part dialect.DatePart) string { } return "CAST(" + col + " AS DATE)" } + +// DropColumnSQL first drops the column's DEFAULT constraint: SQL Server names it itself and refuses to +// drop a column that still has one. +func (d *msDialect) DropColumnSQL(table, column string) []string { + lit := func(s string) string { return "N'" + strings.ReplaceAll(s, "'", "''") + "'" } + return []string{ + "DECLARE @dc sysname; " + + "SELECT @dc = dc.name FROM sys.default_constraints dc JOIN sys.columns c ON c.default_object_id = dc.object_id " + + "WHERE dc.parent_object_id = OBJECT_ID(" + lit(d.Quote(table)) + ") AND c.name = " + lit(column) + "; " + + "IF @dc IS NOT NULL EXEC('ALTER TABLE " + strings.ReplaceAll(d.Quote(table), "'", "''") + " DROP CONSTRAINT ' + QUOTENAME(@dc));", + "ALTER TABLE " + d.Quote(table) + " DROP COLUMN " + d.Quote(column), + } +} diff --git a/integration/pipeline_test.go b/integration/pipeline_test.go index 3fbb764..af47056 100644 --- a/integration/pipeline_test.go +++ b/integration/pipeline_test.go @@ -107,6 +107,14 @@ func mustFail(t *testing.T, what string, err error) { } } +// categoryParentAction is the ON DELETE action the categories migration picks for this database. +func categoryParentAction(db *migro.DB) string { + if db.Dialect.Name() == "sqlserver" { + return "NO ACTION" + } + return "CASCADE" +} + func mustExec(t *testing.T, db *migro.DB, sql string, args ...any) { t.Helper() if err := db.Gorm.Exec(sql, args...).Error; err != nil { @@ -171,9 +179,9 @@ func TestConstraintsRejectBadData(t *testing.T) { "profile of a ghost user": g.Exec("INSERT INTO profiles (id, user_id) VALUES (91, 99)").Error, "duplicate pivot row": g.Exec("INSERT INTO role_user (user_id, role_id) VALUES (1, 1)").Error, "pivot to a ghost role": g.Exec("INSERT INTO role_user (user_id, role_id) VALUES (1, 99)").Error, - "duplicate post slug": g.Exec("INSERT INTO posts (id, user_id, slug, title, published) VALUES (90, 2, 'hello-db', 'other', TRUE)").Error, - "composite unique (user,title)": g.Exec("INSERT INTO posts (id, user_id, slug, title, published) VALUES (91, 1, 'new-slug', 'Hello DB', TRUE)").Error, - "post with ghost category": g.Exec("INSERT INTO posts (id, user_id, category_id, slug, title, published) VALUES (92, 1, 99, 's', 't', TRUE)").Error, + "duplicate post slug": g.Exec("INSERT INTO posts (id, user_id, slug, title, published) VALUES (90, 2, 'hello-db', 'other', ?)", true).Error, + "composite unique (user,title)": g.Exec("INSERT INTO posts (id, user_id, slug, title, published) VALUES (91, 1, 'new-slug', 'Hello DB', ?)", true).Error, + "post with ghost category": g.Exec("INSERT INTO posts (id, user_id, category_id, slug, title, published) VALUES (92, 1, 99, 's', 't', ?)", true).Error, "duplicate order line": g.Exec("INSERT INTO order_items (order_id, line_no, product_id, quantity, unit_price) VALUES (1, 1, 2, 1, 1)").Error, "order line of ghost order": g.Exec("INSERT INTO order_items (order_id, line_no, product_id, quantity, unit_price) VALUES (99, 1, 1, 1, 1)").Error, "duplicate taggable": g.Exec("INSERT INTO taggables (tag_id, taggable_id, taggable_type) VALUES (1, 1, 'post')").Error, @@ -184,7 +192,7 @@ func TestConstraintsRejectBadData(t *testing.T) { } // the same title is fine for another user, and the same morph id for another type - mustExec(t, db, "INSERT INTO posts (id, user_id, slug, title, published) VALUES (93, 2, 'hello-again', 'Hello DB', TRUE)") + mustExec(t, db, "INSERT INTO posts (id, user_id, slug, title, published) VALUES (93, 2, 'hello-again', 'Hello DB', ?)", true) mustExec(t, db, "INSERT INTO taggables (tag_id, taggable_id, taggable_type) VALUES (1, 1, 'video')") // defaults filled in by the schema @@ -662,7 +670,7 @@ func TestPretendRendersEveryMigrationWithoutTouchingTheDatabase(t *testing.T) { sql := strings.NewReplacer(`"`, "", "`", "", "[", "", "]", "").Replace(strings.Join(all, "\n")) for _, want := range []string{ "CREATE TABLE countries", "CREATE TABLE order_items", "CREATE INDEX comments_commentable_type_commentable_id_index", - "CREATE INDEX orders_status_placed_at_index", "FOREIGN KEY (parent_id) REFERENCES categories (id) ON DELETE CASCADE", + "CREATE INDEX orders_status_placed_at_index", "FOREIGN KEY (parent_id) REFERENCES categories (id) ON DELETE " + categoryParentAction(db), "PRIMARY KEY (tag_id, taggable_id, taggable_type)", } { if !strings.Contains(sql, want) { diff --git a/schema/schema_test.go b/schema/schema_test.go index 73b7aba..dcfd9ce 100644 --- a/schema/schema_test.go +++ b/schema/schema_test.go @@ -256,3 +256,28 @@ func TestFullTextIndexPerDialect(t *testing.T) { } } } + +func TestDropColumnPerDialect(t *testing.T) { + drop := func(tb *schema.Table) { tb.DropColumn("archived") } + for name, want := range map[string]string{ + "postgres": `ALTER TABLE "posts" DROP COLUMN "archived"`, + "sqlserver": `DROP COLUMN [archived]`, + } { + d, err := dialect.Get(name) + if err != nil { + t.Fatal(err) + } + stmts, err := schema.AlterSQL(d, "posts", drop) + if err != nil { + t.Fatal(err) + } + sql := strings.Join(stmts, "\n") + if !strings.Contains(sql, want) { + t.Errorf("%s: want %q in:\n%s", name, want, sql) + } + hasDefaultDrop := strings.Contains(sql, "sys.default_constraints") + if (name == "sqlserver") != hasDefaultDrop { + t.Errorf("%s: dropping the DEFAULT constraint first is a SQL Server need only:\n%s", name, sql) + } + } +} diff --git a/schema/table.go b/schema/table.go index 03bc62d..067e647 100644 --- a/schema/table.go +++ b/schema/table.go @@ -490,6 +490,10 @@ func (t *Table) compileAlter(d dialect.Dialect) ([]string, error) { out = append(out, fmt.Sprintf("ALTER TABLE %s %s %s", q, d.AddColumnKeyword(), s)) } for _, c := range t.dropColumns { + if cd, ok := d.(dialect.ColumnDropper); ok { + out = append(out, cd.DropColumnSQL(t.name, c)...) + continue + } out = append(out, fmt.Sprintf("ALTER TABLE %s DROP COLUMN %s", q, d.Quote(c))) } for _, r := range t.renames { From 6f2c32c0d55f71b914b7a6983208f4551ab4aba2 Mon Sep 17 00:00:00 2001 From: Luiz Neves Date: Tue, 17 Nov 2026 09:01:32 -0300 Subject: [PATCH 6/7] fix(sqlserver): build the DROP CONSTRAINT statement in a variable; portable insert in the pipeline test --- dialect/sqlserver/sqlserver.go | 7 +++++-- integration/pipeline_test.go | 6 +++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/dialect/sqlserver/sqlserver.go b/dialect/sqlserver/sqlserver.go index 0a25950..e352b02 100644 --- a/dialect/sqlserver/sqlserver.go +++ b/dialect/sqlserver/sqlserver.go @@ -107,10 +107,13 @@ func (d *msDialect) DatePart(col string, part dialect.DatePart) string { func (d *msDialect) DropColumnSQL(table, column string) []string { lit := func(s string) string { return "N'" + strings.ReplaceAll(s, "'", "''") + "'" } return []string{ - "DECLARE @dc sysname; " + + // EXEC cannot take a function call as its argument, so the statement is built in a variable first. + "DECLARE @dc sysname, @stmt nvarchar(max); " + "SELECT @dc = dc.name FROM sys.default_constraints dc JOIN sys.columns c ON c.default_object_id = dc.object_id " + "WHERE dc.parent_object_id = OBJECT_ID(" + lit(d.Quote(table)) + ") AND c.name = " + lit(column) + "; " + - "IF @dc IS NOT NULL EXEC('ALTER TABLE " + strings.ReplaceAll(d.Quote(table), "'", "''") + " DROP CONSTRAINT ' + QUOTENAME(@dc));", + "IF @dc IS NOT NULL BEGIN " + + "SET @stmt = N'ALTER TABLE " + strings.ReplaceAll(d.Quote(table), "'", "''") + " DROP CONSTRAINT ' + QUOTENAME(@dc); " + + "EXEC (@stmt); END", "ALTER TABLE " + d.Quote(table) + " DROP COLUMN " + d.Quote(column), } } diff --git a/integration/pipeline_test.go b/integration/pipeline_test.go index af47056..98bff3b 100644 --- a/integration/pipeline_test.go +++ b/integration/pipeline_test.go @@ -192,7 +192,11 @@ func TestConstraintsRejectBadData(t *testing.T) { } // the same title is fine for another user, and the same morph id for another type - mustExec(t, db, "INSERT INTO posts (id, user_id, slug, title, published) VALUES (93, 2, 'hello-again', 'Hello DB', ?)", true) + if db.Dialect.Name() == "sqlserver" { // an identity column refuses explicit ids + mustExec(t, db, "INSERT INTO posts (user_id, slug, title, published) VALUES (2, 'hello-again', 'Hello DB', ?)", true) + } else { + mustExec(t, db, "INSERT INTO posts (id, user_id, slug, title, published) VALUES (93, 2, 'hello-again', 'Hello DB', ?)", true) + } mustExec(t, db, "INSERT INTO taggables (tag_id, taggable_id, taggable_type) VALUES (1, 1, 'video')") // defaults filled in by the schema From cde105f7a7a1b67ef3ac6f209dbc960088e299a0 Mon Sep 17 00:00:00 2001 From: Luiz Neves Date: Tue, 17 Nov 2026 09:06:45 -0300 Subject: [PATCH 7/7] test: insert explicit ids through IDENTITY_INSERT on SQL Server --- integration/pipeline_test.go | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/integration/pipeline_test.go b/integration/pipeline_test.go index 98bff3b..27e0c32 100644 --- a/integration/pipeline_test.go +++ b/integration/pipeline_test.go @@ -115,6 +115,15 @@ func categoryParentAction(db *migro.DB) string { return "CASCADE" } +// mustExecID runs an INSERT that names the identity column. SQL Server only allows that inside IDENTITY_INSERT. +func mustExecID(t *testing.T, db *migro.DB, table, sql string, args ...any) { + t.Helper() + if db.Dialect.Name() == "sqlserver" { + sql = "SET IDENTITY_INSERT " + table + " ON; " + sql + "; SET IDENTITY_INSERT " + table + " OFF" + } + mustExec(t, db, sql, args...) +} + func mustExec(t *testing.T, db *migro.DB, sql string, args ...any) { t.Helper() if err := db.Gorm.Exec(sql, args...).Error; err != nil { @@ -200,13 +209,13 @@ func TestConstraintsRejectBadData(t *testing.T) { mustExec(t, db, "INSERT INTO taggables (tag_id, taggable_id, taggable_type) VALUES (1, 1, 'video')") // defaults filled in by the schema - mustExec(t, db, "INSERT INTO products (id, sku, name, price) VALUES (91, 'SKU-D', 'Defaults', 5)") + mustExecID(t, db, "products", "INSERT INTO products (id, sku, name, price) VALUES (91, 'SKU-D', 'Defaults', 5)") var stock int g.Table("products").Select("stock").Where("id = 91").Scan(&stock) if stock != 0 { t.Errorf("stock default: %d", stock) } - mustExec(t, db, "INSERT INTO orders (id, user_id, total) VALUES (91, 1, 1)") + mustExecID(t, db, "orders", "INSERT INTO orders (id, user_id, total) VALUES (91, 1, 1)") var status string g.Table("orders").Select("status").Where("id = 91").Scan(&status) if status != "pending" {