Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .github/ISSUE_TEMPLATE/bug_report.md
Original file line number Diff line number Diff line change
@@ -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):
5 changes: 5 additions & 0 deletions .github/ISSUE_TEMPLATE/config.yml
Original file line number Diff line number Diff line change
@@ -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.
11 changes: 11 additions & 0 deletions .github/ISSUE_TEMPLATE/feature_request.md
Original file line number Diff line number Diff line change
@@ -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?**
8 changes: 8 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
version: 2
updates:
- package-ecosystem: gomod
directory: /
schedule: { interval: weekly }
- package-ecosystem: github-actions
directory: /
schedule: { interval: weekly }
81 changes: 79 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,20 @@ 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
# 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.9.0 ./...

postgres:
runs-on: ubuntu-latest
Expand All @@ -35,7 +48,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
Expand All @@ -52,4 +65,68 @@ jobs:
- 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=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 ./...
22 changes: 22 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -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 }}
21 changes: 21 additions & 0 deletions .goreleaser.yaml
Original file line number Diff line number Diff line change
@@ -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 }
29 changes: 29 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
20 changes: 20 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
@@ -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.
21 changes: 20 additions & 1 deletion cmd/migro/launcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
27 changes: 25 additions & 2 deletions cmd/migro/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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 {
Expand All @@ -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:"):
Expand Down
4 changes: 2 additions & 2 deletions console/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,8 @@ func allCommands() []command {
{name: "make:cast", desc: "Create a custom attribute cast",
usage: "make:cast <Name> [--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 <Name> [-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 <Name> [-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},
}
}
Expand Down
Loading
Loading