Repository navigation
Expand file tree
/
Copy pathmigrate.go
More file actions
676 lines (584 loc) · 20.8 KB
/
Copy pathmigrate.go
File metadata and controls
676 lines (584 loc) · 20.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
package laravel
import (
"bytes"
"cmp"
"context"
"errors"
"flag"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/token"
"io"
"io/fs"
"maps"
"net/url"
"os"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
"time"
"go.laravel.com/config"
"go.laravel.com/console"
"go.laravel.com/db"
"go.laravel.com/internal/schemadump"
"go.laravel.com/str"
)
// errCancelled is a command that someone declined at its prompt. It exits
// with status 1 and prints nothing more.
var errCancelled = console.Exit(1)
// migrationsDir is where make:migration writes migrations, relative to the
// application's base path.
var migrationsDir = filepath.Join("database", "migrations")
type migrateCommand struct {
app *App
// fresh drops every table first, as migrate:fresh.
fresh bool
force, seed, schemaOnly bool
database, seeder, schemaPath string
}
func (m *migrateCommand) Name() string {
if m.fresh {
return "migrate:fresh"
}
return "migrate"
}
func (m *migrateCommand) Description() string {
if m.fresh {
return "Drop all tables and run every migration"
}
return "Run the pending migrations"
}
func (m *migrateCommand) Flags(flags *flag.FlagSet) {
flags.BoolVar(&m.force, "force", false, "Run without asking in production, and create a missing database")
flags.StringVar(&m.database, "database", "", "Migrate the connection with this `name`, instead of the default database")
flags.BoolVar(&m.seed, "seed", false, "Run the seeders after migrating")
flags.StringVar(&m.seeder, "seeder", "", "Run the seeder with this `name` after migrating")
flags.StringVar(&m.schemaPath, "schema-path", "", "Load the schema dump at this `path`, instead of the connection's")
flags.BoolVar(&m.schemaOnly, "schema-only", false, "Load the schema dump without running any migrations")
}
// Run runs the pending migrations, or with --fresh, drops every table and
// runs every migration, then runs the seeders that --seed or --seeder
// asks for.
func (m *migrateCommand) Run(ctx context.Context, c *console.Console) error {
target, err := m.app.migrationTarget(m.database)
if err != nil {
return err
}
seed, seeders := m.seed, m.app.seeders
if m.seeder != "" {
// Check the name before migrating, so a typo doesn't leave the
// database migrated but unseeded.
if seeders, err = m.app.seeder(m.seeder); err != nil {
return err
}
seed = true
}
if err := m.app.confirmInProduction(ctx, c, m.force); err != nil {
return err
}
if err := m.app.createMissingDatabase(ctx, c, target, m.force); err != nil {
return err
}
dump, err := m.app.schemaDump(target, m.schemaPath)
if err != nil {
return err
}
migrator := db.Migrator{
DB: target.conn,
Migrations: m.app.migrations,
Starting: func(name string) { c.Step("Migrating `" + name + "`...") },
Schema: dump,
Loading: func(path string) {
c.Step("Loading schema dump `" + path + "`...")
},
}
if m.schemaOnly {
migrator.Migrations = nil
}
var ran int
if m.fresh {
c.Step("Dropping all tables...")
ran, err = migrator.Fresh(ctx)
} else {
ran, err = migrator.Migrate(ctx)
}
switch {
case err != nil:
return err
case m.schemaOnly:
case ran == 0:
c.Info("No pending migrations found.")
default:
c.Successf("%d %s ran.", ran, str.Plural("migration", ran))
}
if seed {
return m.app.runSeeders(ctx, c, target.conn, seeders)
}
return nil
}
type migrateStatusCommand struct {
app *App
database string
}
func (*migrateStatusCommand) Name() string { return "migrate:status" }
func (*migrateStatusCommand) Description() string { return "List migrations and their status" }
func (m *migrateStatusCommand) Flags(flags *flag.FlagSet) {
flags.StringVar(&m.database, "database", "", "Read the connection with this `name`, instead of the default database")
}
func (m *migrateStatusCommand) Run(ctx context.Context, c *console.Console) error {
return m.app.migrationStatus(ctx, c, m.database)
}
type schemaDumpCommand struct {
app *App
prune, withoutMigrationData bool
database, path string
}
func (*schemaDumpCommand) Name() string { return "schema:dump" }
func (*schemaDumpCommand) Description() string { return "Dump the database schema to a file" }
func (s *schemaDumpCommand) Flags(flags *flag.FlagSet) {
flags.StringVar(&s.database, "database", "", "Dump the connection with this `name`, instead of the default database")
flags.StringVar(&s.path, "path", "", "Write the dump to this `path`, instead of database/schema/<connection>-schema.sql")
flags.BoolVar(&s.prune, "prune", false, "Delete every migration file after dumping")
flags.BoolVar(&s.withoutMigrationData, "without-migration-data", false, "Leave out the rows of the migrations table")
}
// Run dumps the connection's schema with its database's command-line
// client, then with --prune deletes the migrations that the dump squashes.
func (s *schemaDumpCommand) Run(ctx context.Context, c *console.Console) error {
target, err := s.app.migrationTarget(s.database)
if err != nil {
return err
}
path := cmp.Or(s.path, filepath.Join(schemadump.Dir, target.connection+"-schema.sql"))
if err := os.MkdirAll(filepath.Dir(s.app.basePath(path)), 0o755); err != nil {
return err
}
if err := target.conn.DumpSchema(ctx, s.app.basePath(path), s.withoutMigrationData); err != nil {
return err
}
c.Success("Database schema dumped to `" + filepath.ToSlash(path) + "`.")
if !s.prune {
return nil
}
pruned, err := s.app.pruneMigrations()
if err != nil {
return err
}
c.Successf("%d %s pruned.", pruned, str.Plural("migration", pruned))
return nil
}
// pruneMigrations deletes every Go file of the migrations directory except
// migrations.go and tests, and empties its All list, so the package still
// builds. It returns how many of the deleted files were migrations.
func (a *App) pruneMigrations() (int, error) {
dir := filepath.Join(a.Config().App.BasePath, migrationsDir)
list := filepath.Join(dir, "migrations.go")
display := filepath.ToSlash(filepath.Join(migrationsDir, "migrations.go"))
source, err := os.ReadFile(list)
var emptied []byte
switch {
case errors.Is(err, fs.ErrNotExist):
case err != nil:
return 0, err
default:
parsed, err := parser.ParseFile(token.NewFileSet(), list, source, parser.ParseComments)
if err != nil {
return 0, fmt.Errorf("`%s` can't be read: %w", display, err)
}
all := findAll(parsed)
if all == nil {
return 0, fmt.Errorf("`%s` has no `All` list to empty", display)
}
if emptied, err = format.Source(slices.Concat(source[:all.Lbrace-parsed.FileStart+1], source[all.Rbrace-parsed.FileStart:])); err != nil {
return 0, fmt.Errorf("`%s` can't be formatted: %w", display, err)
}
}
entries, err := os.ReadDir(dir)
if errors.Is(err, fs.ErrNotExist) {
return 0, nil
}
if err != nil {
return 0, err
}
pruned := 0
for _, entry := range entries {
name := entry.Name()
if entry.IsDir() || filepath.Ext(name) != ".go" || name == "migrations.go" || strings.HasSuffix(name, "_test.go") {
continue
}
if err := os.Remove(filepath.Join(dir, name)); err != nil {
return pruned, err
}
if migrationFile.MatchString(name) {
pruned++
}
}
if emptied == nil {
return pruned, nil
}
return pruned, os.WriteFile(list, emptied, 0o644)
}
type makeMigrationCommand struct {
app *App
create, table string
}
func (*makeMigrationCommand) Name() string { return "make:migration" }
func (*makeMigrationCommand) Description() string { return "Create a migration" }
func (*makeMigrationCommand) Arguments() []Argument {
return []Argument{{
Name: "NAME",
Description: "The migration's name: create_posts_table creates posts, and add_slug_to_posts_table changes it",
Required: true,
}}
}
func (m *makeMigrationCommand) Flags(flags *flag.FlagSet) {
flags.StringVar(&m.create, "create", "", "The `table` the migration creates")
flags.StringVar(&m.table, "table", "", "The `table` the migration changes")
}
func (m *makeMigrationCommand) Run(_ context.Context, c *console.Console) error {
if m.create != "" && m.table != "" {
return console.Usagef("argument `--create` can't be used with `--table`")
}
return m.app.makeMigration(c, c.Args[0], m.create, m.table)
}
// A migrationTarget is the database that a migrate command runs on: the
// default database, or the connection that --database names.
type migrationTarget struct {
conn *db.DB
// url is the writer's URL, where a missing database is created.
url string
// connection is the connection's name: the one --database gives, the
// configured default, or default. Its schema dump is named for it.
connection string
}
// migrationTarget returns the connection called name, or the default
// database when name is empty. A name that isn't a connection is an error,
// since it comes from the command line.
func (a *App) migrationTarget(name string) (migrationTarget, error) {
if name == "" {
database := a.Config().Database
return migrationTarget{a.db, cmp.Or(database.WriteURL, database.URL), cmp.Or(database.Default, "default")}, nil
}
connection, ok := a.Config().Database.Connections[name]
if !ok {
names := slices.Sorted(maps.Keys(a.Config().Database.Connections))
if len(names) == 0 {
return migrationTarget{}, fmt.Errorf("database connection `%s` isn't defined; add it to config.Database.Connections", name)
}
return migrationTarget{}, fmt.Errorf("database connection `%s` isn't defined; the connections are `%s`", name, strings.Join(names, "`, `"))
}
return migrationTarget{a.connection(name), cmp.Or(connection.WriteURL, connection.URL), name}, nil
}
// schemaDump returns the schema dump that migrate loads into the target
// when it has run no migrations: the file at path, which --schema-path
// gives, or else the target's dump, or nil when there's none.
func (a *App) schemaDump(target migrationTarget, path string) (*db.SchemaDump, error) {
if path == "" {
return schemadump.Find(a.schema, a.Config().App.BasePath, target.connection)
}
contents, err := os.ReadFile(a.basePath(path))
if errors.Is(err, fs.ErrNotExist) {
// As in Laravel Classic, migrate runs the migrations instead.
return nil, nil
}
if err != nil {
return nil, err
}
return &db.SchemaDump{Path: path, Contents: contents}, nil
}
// basePath resolves a path from the command line against the
// application's base path.
func (a *App) basePath(path string) string {
if filepath.IsAbs(path) {
return path
}
return filepath.Join(a.Config().App.BasePath, path)
}
// confirmInProduction asks before a command changes a production database,
// unless it was given --force.
func (a *App) confirmInProduction(ctx context.Context, c *console.Console, force bool) error {
if force || a.Config().App.Env != config.Production {
return nil
}
c.Warn("The application is in production.")
confirmed, err := c.Confirm(ctx, "Are you sure you want to run this command?", false)
if err != nil {
return err
}
if !confirmed {
c.Info("Command cancelled.")
return errCancelled
}
return nil
}
// createMissingDatabase offers to create the target's database when its
// server doesn't have it, as on a new machine. --force creates it without
// asking.
func (a *App) createMissingDatabase(ctx context.Context, c *console.Console, target migrationTarget, force bool) error {
if _, err := target.conn.Exec(ctx, "select 1"); db.FailureOf(err) != db.MissingDatabase {
// migrate reports any other failure when it connects.
return nil
}
name := databaseName(target.url)
if !force {
if c.Input == nil {
return fmt.Errorf("database `%s` doesn't exist on connection `%s`; use `--force` to create it", name, target.connection)
}
c.Warnf("Database `%s` doesn't exist on connection `%s`.", name, target.connection)
create, err := c.Confirm(ctx, "Would you like to create it?", true)
if err != nil {
return err
}
if !create {
c.Info("Command cancelled.")
return errCancelled
}
}
if err := db.CreateDatabase(ctx, db.Config{URL: target.url}, a.drivers...); err != nil {
return err
}
c.Success("Database `" + name + "` created.")
return nil
}
// databaseName returns the name of the database that a URL names.
func databaseName(databaseURL string) string {
if u, err := url.Parse(databaseURL); err == nil {
return strings.TrimPrefix(u.Path, "/")
}
return databaseURL
}
// migrationStatus lists each migration and whether it has run, then warns
// about migration files that the application doesn't list.
func (a *App) migrationStatus(ctx context.Context, c *console.Console, database string) error {
target, err := a.migrationTarget(database)
if err != nil {
return err
}
statuses, err := db.Migrator{DB: target.conn, Migrations: a.migrations}.Status(ctx)
if db.FailureOf(err) == db.MissingDatabase {
return fmt.Errorf("database `%s` doesn't exist on connection `%s`; run `migrate` to create it", databaseName(target.url), target.connection)
}
if err != nil {
return err
}
dump, err := schemadump.Find(a.schema, a.Config().App.BasePath, target.connection)
if err != nil {
return err
}
squashed := 0
if dump != nil {
// The dump records the migrations that it squashes, whose files
// schema:dump --prune deleted.
before := len(statuses)
statuses = slices.DeleteFunc(statuses, func(status db.MigrationStatus) bool { return status.Batch > 0 && !status.Registered })
squashed = before - len(statuses)
}
latest := ""
for _, status := range statuses {
if status.Batch > 0 {
latest = max(latest, status.Name)
}
}
rows := make([][]string, len(statuses))
for i, status := range statuses {
batch, label, tone := "", "ran", console.Success
switch {
case status.Batch > 0 && !status.Registered:
label, tone = "ran, not registered", console.Warning
case status.Batch == 0 && status.Name < latest:
label, tone = "pending, out of order", console.Warning
case status.Batch == 0:
label, tone = "pending", console.Warning
}
if status.Batch > 0 {
batch = strconv.Itoa(status.Batch)
}
rows[i] = []string{status.Name, batch, c.Paint(tone, label)}
}
if len(rows) > 0 {
table(c, []string{"Migration", "Batch", "Status"}, rows)
if squashed > 0 {
// A blank line sets the squashed count apart from the table. It
// goes where the message goes, so -q drops both.
io.WriteString(c.Stderr(), "\n")
}
}
switch {
case squashed == 1:
c.Info("1 migration is squashed into the schema dump.")
case squashed > 1:
c.Info(strconv.Itoa(squashed) + " migrations are squashed into the schema dump.")
case len(rows) == 0:
c.Info("No migrations found.")
}
for _, name := range a.unlistedMigrations() {
c.Warn("The migration in `" + filepath.ToSlash(filepath.Join(migrationsDir, name+".go")) + "` isn't in `All`, so `migrate` doesn't run it.")
}
return nil
}
// migrationFile matches the name of a file that make:migration writes.
var migrationFile = regexp.MustCompile(`^\d{4}_\d{2}_\d{2}_\d{6}_\w+\.go$`)
// unlistedMigrations returns the migrations in the application's migrations
// directory that it doesn't list. A server that has only the binary has no
// directory, and so none.
func (a *App) unlistedMigrations() []string {
entries, err := os.ReadDir(filepath.Join(a.Config().App.BasePath, migrationsDir))
if err != nil {
return nil
}
var unlisted []string
for _, entry := range entries {
name := strings.TrimSuffix(entry.Name(), ".go")
listed := slices.ContainsFunc(a.migrations, func(m db.Migration) bool { return m.Name == name })
if migrationFile.MatchString(entry.Name()) && !strings.HasSuffix(name, "_test") && !listed {
unlisted = append(unlisted, name)
}
}
return unlisted
}
// makeMigration writes a migration to the migrations directory and adds it
// to the All list in its migrations.go.
func (a *App) makeMigration(c *console.Console, name, create, table string) error {
name = str.Snake(name)
function := str.Camel(name)
if !regexp.MustCompile(`^[a-z][a-z0-9_]*$`).MatchString(name) || token.IsKeyword(function) {
return fmt.Errorf("migration name `%s` needs to start with a letter and have only letters, digits, and underscores", name)
}
if strings.HasSuffix(name, "_test") {
return fmt.Errorf("migration name `%s` can't end in `_test`, since Go builds a file whose name ends in `_test.go` only for tests", name)
}
dir := filepath.Join(a.Config().App.BasePath, migrationsDir)
existing, _ := filepath.Glob(filepath.Join(dir, "*_"+name+".go"))
if len(existing) > 0 {
return fmt.Errorf("a migration named `%s` already exists in `%s`", name, filepath.ToSlash(filepath.Join(migrationsDir, filepath.Base(existing[0]))))
}
migration := time.Now().UTC().Format("2006_01_02_150405") + "_" + name
list, err := addToAll(
filepath.Join(dir, "migrations.go"),
filepath.ToSlash(filepath.Join(migrationsDir, "migrations.go")),
fmt.Sprintf("{Name: %q, Run: %s},", migration, function),
migrationsFile,
)
if err != nil {
return err
}
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
if err := createFile(filepath.Join(dir, migration+".go"), migrationStub(list.pkg, function, name, create, table)); err != nil {
return err
}
if err := os.WriteFile(list.path, list.contents, 0o644); err != nil {
return err
}
c.Success("Migration created at `" + filepath.ToSlash(filepath.Join(migrationsDir, migration+".go")) + "`.")
return nil
}
// An allList is a Go file with an entry added to its All list. created
// reports whether the file is new.
type allList struct {
path, pkg string
contents []byte
created bool
}
// addToAll returns the file at path with entry added to the end of its All
// list. When there's no file, it returns newFile, with the entry in place of
// %s. display is the file's path as messages show it.
func addToAll(path, display, entry, newFile string) (allList, error) {
source, err := os.ReadFile(path)
if errors.Is(err, fs.ErrNotExist) {
contents, err := format.Source(fmt.Appendf(nil, newFile, entry))
if err != nil {
panic("laravel: the stub for " + display + " doesn't parse: " + err.Error())
}
parsed, _ := parser.ParseFile(token.NewFileSet(), path, contents, parser.PackageClauseOnly)
return allList{path: path, pkg: parsed.Name.Name, contents: contents, created: true}, nil
}
if err != nil {
return allList{}, err
}
parsed, err := parser.ParseFile(token.NewFileSet(), path, source, parser.ParseComments)
if err != nil {
return allList{}, fmt.Errorf("`%s` can't be read: %w", display, err)
}
list := findAll(parsed)
if list == nil {
return allList{}, fmt.Errorf("`%s` has no `All` list to add to", display)
}
at := int(list.Rbrace - parsed.FileStart)
if source[at-1] != '\n' {
entry = "\n" + entry
}
edited := slices.Concat(source[:at], []byte(entry+"\n"), source[at:])
contents, err := format.Source(edited)
if err != nil {
return allList{}, fmt.Errorf("`%s` can't be formatted: %w", display, err)
}
return allList{path: path, pkg: parsed.Name.Name, contents: contents}, nil
}
// findAll returns the list that var All is set to.
func findAll(file *ast.File) *ast.CompositeLit {
for _, decl := range file.Decls {
decl, ok := decl.(*ast.GenDecl)
if !ok || decl.Tok != token.VAR {
continue
}
for _, spec := range decl.Specs {
spec := spec.(*ast.ValueSpec)
for i, name := range spec.Names {
if name.Name != "All" || i >= len(spec.Values) {
continue
}
if list, ok := spec.Values[i].(*ast.CompositeLit); ok {
return list
}
}
}
}
return nil
}
// migrationsFile is a new migrations.go, with %s for its first entry.
const migrationsFile = `// Package migrations holds the application's database migrations.
// make:migration writes each one and adds it to All.
package migrations
import "go.laravel.com/db"
// All are the application's migrations, which migrate runs in name order.
var All = []db.Migration{
%s
}
`
// migrationStub returns a new migration's source. Its name says what it
// starts with: create_posts_table starts by creating posts, and
// add_slug_to_posts_table starts by changing posts. --create and --table
// name the table instead.
func migrationStub(pkg, function, name, create, table string) []byte {
if create == "" && table == "" {
if match := regexp.MustCompile(`^create_(\w+?)(_table)?$`).FindStringSubmatch(name); match != nil {
create = match[1]
} else if match := regexp.MustCompile(`^.+_(?:to|from|in)_(\w+?)(_table)?$`).FindStringSubmatch(name); match != nil {
table = match[1]
}
}
imports := "import \"context\""
body := "return nil"
switch {
case create != "":
body = fmt.Sprintf("return schema.Create(ctx, %q, func(table *schema.Blueprint) {\ntable.ID()\ntable.Timestamps()\n})", create)
case table != "":
body = fmt.Sprintf("return schema.Alter(ctx, %q, func(table *schema.Blueprint) {\n})", table)
}
if body != "return nil" {
imports = "import (\n\"context\"\n\n\"go.laravel.com/schema\"\n)"
}
var source bytes.Buffer
fmt.Fprintf(&source, "package %s\n\n%s\n\n", pkg, imports)
fmt.Fprintf(&source, "func %s(ctx context.Context) error {\n%s\n}\n", function, body)
formatted, err := format.Source(source.Bytes())
if err != nil {
panic("laravel: the migration stub doesn't parse: " + err.Error())
}
return formatted
}