diff --git a/migrate/engine/plan.go b/migrate/engine/plan.go index a561ee77..0408cfe0 100644 --- a/migrate/engine/plan.go +++ b/migrate/engine/plan.go @@ -17,7 +17,11 @@ const ( type PlanRequest struct { Dialect string - Scope Scope + // Using plans with this dialect instead of the one registered as Dialect, + // so a pure planner can plan offline in a program that links no database + // dialect of that name. Its Name must be Dialect. + Using Dialect + Scope Scope // Context lists objects present in Current only because a dependent sits on // them. They are not managed: no diff change on them is planned or preserved. Context []migrate.Name @@ -38,7 +42,12 @@ type PlanRequest struct { // rebuilds they force, their global order, preconditions and units. It reads // no database: live dependents and refusals arrive in the request. func Plan(req PlanRequest) (Artifact, error) { - d, err := Lookup(req.Dialect) + d, err := req.Using, error(nil) + if d == nil { + d, err = Lookup(req.Dialect) + } else if d.Name() != req.Dialect { + err = fmt.Errorf("engine: plan request names dialect %q but uses %q", req.Dialect, d.Name()) + } if err != nil { return Artifact{}, err } diff --git a/migrate/plan_v1.go b/migrate/plan_v1.go new file mode 100644 index 00000000..c06c909e --- /dev/null +++ b/migrate/plan_v1.go @@ -0,0 +1,42 @@ +package migrate + +// The types below are the v1 offline SQL Server planning API that +// sqlserver.Plan and sqlserver.BuildArtifact serve on top of the engine. New +// callers plan with engine.Plan, whose artifact carries units, preconditions +// and forced rebuilds that a v1 Plan flattens into steps. + +type Request struct { + Current Schema `json:"current"` + Desired Schema `json:"desired"` + // Selection limits the plan to these change IDs; empty plans every change. + Selection []string `json:"selection,omitempty"` +} + +type Step struct { + Change Change `json:"change"` + SQL string `json:"sql"` +} + +type Plan struct { + Steps []Step `json:"steps"` + // Changes lists every change between the snapshots, selected or not, and + // the rebuilds the selected ones force. + Changes []Change `json:"changes"` + // Warnings names each definition whose body is not understood. It is + // compared and created as written. + Warnings []string `json:"warnings,omitempty"` +} + +// Artifact binds reviewed SQL to complete baseline and desired snapshots. +type Artifact struct { + Version int `json:"version"` + Schemas []string `json:"schemas"` + Request Request `json:"request"` + Plan Plan `json:"plan"` + Hash string `json:"hash"` +} + +type ArtifactRequest struct { + Schemas []string + Request Request +} diff --git a/migrate/sqlserver/plan_v1.go b/migrate/sqlserver/plan_v1.go new file mode 100644 index 00000000..43e58640 --- /dev/null +++ b/migrate/sqlserver/plan_v1.go @@ -0,0 +1,151 @@ +package sqlserver + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + + "github.com/flanksource/sqlglot-go/migrate" + "github.com/flanksource/sqlglot-go/migrate/engine" +) + +// artifactV1Version is the version of the v1 artifact BuildArtifact writes. +const artifactV1Version = 1 + +// Plan is the v1 offline planner: it plans the request with the engine and +// the pure Planner, so no dialect has to be registered, and flattens the +// ordered units into one step per statement. +func Plan(request migrate.Request) (migrate.Plan, error) { + a, err := planV1(request, nil) + if err != nil { + return migrate.Plan{}, err + } + return planOfArtifact(a) +} + +// BuildArtifact plans a v1 artifact whose snapshots are limited to +// input.Schemas and binds the plan to them with a hash. +func BuildArtifact(input migrate.ArtifactRequest) (migrate.Artifact, error) { + if err := artifactScope(input.Schemas, input.Request); err != nil { + return migrate.Artifact{}, err + } + a, err := planV1(input.Request, input.Schemas) + if err != nil { + return migrate.Artifact{}, err + } + plan, err := planOfArtifact(a) + if err != nil { + return migrate.Artifact{}, err + } + artifact := migrate.Artifact{ + Version: artifactV1Version, Schemas: a.Scope.Schemas, Plan: plan, + Request: migrate.Request{Current: a.Baseline, Desired: a.Desired, Selection: a.Selection}, + } + artifact.Hash, err = artifactV1Hash(artifact) + return artifact, err +} + +// ValidateArtifact checks the version and hash, then rebuilds the artifact +// from its own snapshots and requires the same hash, so edited SQL is refused. +func ValidateArtifact(artifact migrate.Artifact) error { + if artifact.Version != artifactV1Version { + return fmt.Errorf("sqlserver: unsupported migration artifact version %d, want %d", artifact.Version, artifactV1Version) + } + hash, err := artifactV1Hash(artifact) + if err != nil { + return err + } + if artifact.Hash != hash { + return fmt.Errorf("sqlserver: migration artifact hash mismatch: recorded %s, content hashes to %s", artifact.Hash, hash) + } + expected, err := BuildArtifact(migrate.ArtifactRequest{Schemas: artifact.Schemas, Request: artifact.Request}) + if err != nil { + return fmt.Errorf("sqlserver: rebuild migration artifact: %w", err) + } + if expected.Hash != artifact.Hash { + return fmt.Errorf("sqlserver: migration artifact SQL does not match its snapshots and planner version: rebuild gives %s, recorded %s", expected.Hash, artifact.Hash) + } + return nil +} + +func planV1(request migrate.Request, schemas []string) (engine.Artifact, error) { + return engine.Plan(engine.PlanRequest{ + Dialect: Planner{}.Name(), Using: Planner{}, + Scope: engine.Scope{Mode: engine.ScopeComplete, Schemas: schemas}, + Current: request.Current, Desired: request.Desired, Selection: request.Selection, + }) +} + +// planOfArtifact lists every change the diff finds, as v1 did, with the +// rebuilds the plan forces, and one step per planned statement in order. +func planOfArtifact(a engine.Artifact) (migrate.Plan, error) { + diff, err := Planner{}.Diff(a.Baseline, a.Desired) + if err != nil { + return migrate.Plan{}, err + } + plan := migrate.Plan{Steps: []migrate.Step{}, Changes: diff.Changes(), Warnings: a.Warnings} + planned := map[string]migrate.Change{} + for _, c := range a.Changes { + planned[c.ID] = c + if c.Cause != "" { + plan.Changes = append(plan.Changes, c) + } + } + for _, unit := range a.Units { + for _, op := range unit.Ops { + change, ok := planned[op.Change] + if !ok { + return migrate.Plan{}, fmt.Errorf("sqlserver: op %s implements unplanned change %s", op.ID, op.Change) + } + for _, s := range op.Statements { + plan.Steps = append(plan.Steps, migrate.Step{Change: change, SQL: s.SQL}) + } + } + } + return plan, nil +} + +func artifactV1Hash(artifact migrate.Artifact) (string, error) { + artifact.Hash = "" + body, err := json.Marshal(artifact) + if err != nil { + return "", fmt.Errorf("sqlserver: hash migration artifact: %w", err) + } + sum := sha256.Sum256(body) + return hex.EncodeToString(sum[:]), nil +} + +func artifactScope(schemas []string, request migrate.Request) error { + if len(schemas) == 0 { + return fmt.Errorf("sqlserver: migration artifact requires explicit schema scope") + } + seen := map[string]bool{} + for _, name := range schemas { + if name == "" || seen[name] { + return fmt.Errorf("sqlserver: empty or duplicate artifact schema %q", name) + } + seen[name] = true + } + for _, snapshot := range []migrate.Schema{request.Current, request.Desired} { + var names []migrate.Name + for _, t := range snapshot.Tables { + names = append(names, t.Name) + } + for _, d := range snapshot.Definitions { + names = append(names, d.Name) + } + for _, q := range snapshot.Sequences { + names = append(names, q.Name) + } + for _, t := range snapshot.TableTypes { + names = append(names, t.Name) + } + for _, name := range names { + if !seen[name.Schema] { + return fmt.Errorf("sqlserver: %s.%s is outside artifact schema scope %v", name.Schema, name.Name, schemas) + } + } + } + return nil +} diff --git a/migrate/sqlserver/plan_v1_test.go b/migrate/sqlserver/plan_v1_test.go new file mode 100644 index 00000000..ce83fac9 --- /dev/null +++ b/migrate/sqlserver/plan_v1_test.go @@ -0,0 +1,73 @@ +package sqlserver_test + +import ( + "github.com/flanksource/sqlglot-go/migrate" + "github.com/flanksource/sqlglot-go/migrate/engine" + "github.com/flanksource/sqlglot-go/migrate/sqlserver" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +var _ = Describe("The v1 offline planning API", func() { + var ( + withNote = schemaOf(charTable(charOrders, charColumn("id", "int", false), charColumn("note", "nvarchar(50)", true))) + addNote = charID("add", "column", charOrders, "note") + addOrder = charID("add", "table", charCustomers, "") + ) + stepSQL := func(p migrate.Plan) []string { + out := []string{} + for _, s := range p.Steps { + out = append(out, s.SQL) + } + return out + } + + It("plans the engine's ordered statements as steps", func() { + plan, err := sqlserver.Plan(migrate.Request{Desired: keyedOrders()}) + Expect(err).NotTo(HaveOccurred()) + Expect(stepSQL(plan)).To(Equal(statementsOf(mustPlanBetween(migrate.Schema{}, keyedOrders())))) + Expect(plan.Steps[0].Change.ID).To(Equal(addOrder)) + }) + + It("lists the unselected changes beside the selected steps", func() { + desired := withNote + desired.Tables = append(desired.Tables, charTable(charCustomers, charColumn("id", "int", false))) + current := schemaOf(charTable(charOrders, charColumn("id", "int", false))) + plan, err := sqlserver.Plan(migrate.Request{Current: current, Desired: desired, Selection: []string{addNote}}) + Expect(err).NotTo(HaveOccurred()) + Expect(stepSQL(plan)).To(Equal([]string{"ALTER TABLE [dbo].[orders] ADD [note] nvarchar(50) NULL"})) + Expect(changeIDs(plan.Changes)).To(ConsistOf(addNote, addOrder)) + }) + + It("binds an artifact whose hash ignores selection and snapshot order", func() { + desired := withNote + desired.Tables = append(desired.Tables, charTable(charCustomers, charColumn("id", "int", false))) + reordered := migrate.Schema{Tables: []migrate.Table{desired.Tables[1], desired.Tables[0]}} + a, err := sqlserver.BuildArtifact(migrate.ArtifactRequest{Schemas: []string{"dbo"}, Request: migrate.Request{Desired: desired, Selection: []string{addOrder, charID("add", "table", charOrders, "")}}}) + Expect(err).NotTo(HaveOccurred()) + b, err := sqlserver.BuildArtifact(migrate.ArtifactRequest{Schemas: []string{"dbo"}, Request: migrate.Request{Desired: reordered, Selection: []string{charID("add", "table", charOrders, ""), addOrder}}}) + Expect(err).NotTo(HaveOccurred()) + Expect(b.Hash).To(Equal(a.Hash)) + Expect(sqlserver.ValidateArtifact(a)).To(Succeed()) + a.Plan.Steps[0].SQL += " -- edited" + Expect(sqlserver.ValidateArtifact(a)).To(MatchError(ContainSubstring("hash mismatch"))) + }) + + It("refuses an artifact snapshot outside its schema scope", func() { + _, err := sqlserver.BuildArtifact(migrate.ArtifactRequest{Schemas: []string{"sales"}, Request: migrate.Request{Desired: withNote}}) + Expect(err).To(MatchError(ContainSubstring("dbo.orders is outside artifact schema scope"))) + }) + + It("refuses a dialect that is not the one the request names", func() { + _, err := engine.Plan(engine.PlanRequest{Dialect: "postgres", Using: sqlserver.Planner{}, Scope: engine.Scope{Mode: engine.ScopeComplete}}) + Expect(err).To(MatchError(ContainSubstring(`names dialect "postgres" but uses "sqlserver"`))) + }) +}) + +func changeIDs(changes []migrate.Change) []string { + ids := []string{} + for _, c := range changes { + ids = append(ids, c.ID) + } + return ids +} diff --git a/rspress.config.ts b/rspress.config.ts new file mode 100644 index 00000000..29f66fac --- /dev/null +++ b/rspress.config.ts @@ -0,0 +1,50 @@ +import { defineConfig } from '@rspress/core'; + +export default defineConfig({ + root: 'docs', + title: 'sqlglot-go', + description: 'Parse SQL, inspect schemas, and plan reviewed migrations in Go.', + lang: 'en', + route: { + exclude: ['diagrams/**'], + }, + markdown: { + link: { checkDeadLinks: true, checkAnchors: true }, + }, + themeConfig: { + nav: [ + { text: 'Guide', link: '/guide/getting-started' }, + { text: 'Go API', link: '/guide/go-api' }, + { text: 'Inspection', link: '/guide/inspection' }, + { text: 'Migrations', link: '/guide/migrations' }, + ], + sidebar: { + '/': [ + { + text: 'Using sqlglot-go', + items: [ + { text: 'Getting started', link: '/guide/getting-started' }, + { text: 'Command line', link: '/guide/cli' }, + { text: 'Web UI', link: '/guide/web-ui' }, + { text: 'Go API', link: '/guide/go-api' }, + { text: 'Connections and inspection', link: '/guide/inspection' }, + { text: 'Migrate and resume work', link: '/guide/migrations' }, + ], + }, + { + text: 'Development', + items: [ + { text: 'Contributing and verification', link: '/guide/contributing' }, + { text: 'Upstream issues', link: '/upstream-issues' }, + ], + }, + ], + }, + socialLinks: [ + { icon: 'github', mode: 'link', content: 'https://github.com/flanksource/sqlglot-go' }, + ], + footer: { + message: 'Apache 2.0 ยท Derived from sqlglot (MIT). See LICENSE, LICENSE.sqlglot and NOTICE in the repository.', + }, + }, +}); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 00000000..01497aaa --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2023", + "lib": ["ES2023", "DOM"], + "module": "ESNext", + "moduleResolution": "bundler", + "noEmit": true, + "strict": true, + "skipLibCheck": true, + "isolatedModules": true, + "verbatimModuleSyntax": true + }, + "include": ["rspress.config.ts"] +}