• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

supabase / cli / 21910847926

11 Feb 2026 03:16PM UTC coverage: 61.773%. First build
21910847926

Pull #4834

github

web-flow
Merge ad9a424b4 into b76a550db
Pull Request #4834: Prod deploy

302 of 355 new or added lines in 44 files covered. (85.07%)

7705 of 12473 relevant lines covered (61.77%)

7.44 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

67.11
/internal/db/diff/diff.go
1
package diff
2

3
import (
4
        "context"
5
        _ "embed"
6
        "fmt"
7
        "io"
8
        "io/fs"
9
        "os"
10
        "path/filepath"
11
        "regexp"
12
        "strconv"
13
        "strings"
14
        "time"
15

16
        "github.com/cenkalti/backoff/v4"
17
        "github.com/docker/docker/api/types/container"
18
        "github.com/docker/docker/api/types/network"
19
        "github.com/docker/go-connections/nat"
20
        "github.com/go-errors/errors"
21
        "github.com/jackc/pgconn"
22
        "github.com/jackc/pgx/v4"
23
        "github.com/spf13/afero"
24
        "github.com/supabase/cli/internal/db/start"
25
        "github.com/supabase/cli/internal/migration/new"
26
        "github.com/supabase/cli/internal/utils"
27
        "github.com/supabase/cli/pkg/migration"
28
        "github.com/supabase/cli/pkg/parser"
29
)
30

31
type DiffFunc func(context.Context, pgconn.Config, pgconn.Config, []string, ...func(*pgx.ConnConfig)) (string, error)
32

33
func Run(ctx context.Context, schema []string, file string, config pgconn.Config, differ DiffFunc, fsys afero.Fs, options ...func(*pgx.ConnConfig)) (err error) {
2✔
34
        out, err := DiffDatabase(ctx, schema, config, os.Stderr, fsys, differ, options...)
2✔
35
        if err != nil {
3✔
36
                return err
1✔
37
        }
1✔
38
        branch := utils.GetGitBranch(fsys)
1✔
39
        fmt.Fprintln(os.Stderr, "Finished "+utils.Aqua("supabase db diff")+" on branch "+utils.Aqua(branch)+".\n")
1✔
40
        if err := SaveDiff(out, file, fsys); err != nil {
1✔
41
                return err
×
42
        }
×
43
        drops := findDropStatements(out)
1✔
44
        if len(drops) > 0 {
1✔
45
                fmt.Fprintln(os.Stderr, "Found drop statements in schema diff. Please double check if these are expected:")
×
46
                fmt.Fprintln(os.Stderr, utils.Yellow(strings.Join(drops, "\n")))
×
47
        }
×
48
        return nil
1✔
49
}
50

51
var warnDiff = `WARNING: The diff tool is not foolproof, so you may need to manually rearrange and modify the generated migration.
52
Run ` + utils.Aqua("supabase db reset") + ` to verify that the new migration does not generate errors.`
53

54
func SaveDiff(out, file string, fsys afero.Fs) error {
1✔
55
        if len(out) < 2 {
1✔
NEW
56
                fmt.Fprintln(os.Stderr, "No schema changes found")
×
57
        } else if len(file) > 0 {
2✔
58
                path := new.GetMigrationPath(utils.GetCurrentTimestamp(), file)
1✔
59
                if err := utils.WriteFile(path, []byte(out), fsys); err != nil {
1✔
NEW
60
                        return err
×
NEW
61
                }
×
62
                fmt.Fprintln(os.Stderr, warnDiff)
1✔
NEW
63
        } else {
×
NEW
64
                fmt.Println(out)
×
NEW
65
        }
×
66
        return nil
1✔
67
}
68

69
func loadDeclaredSchemas(fsys afero.Fs) ([]string, error) {
1✔
70
        if schemas := utils.Config.Db.Migrations.SchemaPaths; len(schemas) > 0 {
1✔
71
                return schemas.Files(afero.NewIOFS(fsys))
×
72
        }
×
73
        if exists, err := afero.DirExists(fsys, utils.SchemasDir); err != nil {
1✔
74
                return nil, errors.Errorf("failed to check schemas: %w", err)
×
75
        } else if !exists {
1✔
76
                return nil, nil
×
77
        }
×
78
        var declared []string
1✔
79
        if err := afero.Walk(fsys, utils.SchemasDir, func(path string, info fs.FileInfo, err error) error {
10✔
80
                if err != nil {
9✔
81
                        return err
×
82
                }
×
83
                if info.Mode().IsRegular() && filepath.Ext(info.Name()) == ".sql" {
13✔
84
                        declared = append(declared, path)
4✔
85
                }
4✔
86
                return nil
9✔
87
        }); err != nil {
×
88
                return nil, errors.Errorf("failed to walk dir: %w", err)
×
89
        }
×
90
        return declared, nil
1✔
91
}
92

93
// https://github.com/djrobstep/migra/blob/master/migra/statements.py#L6
94
var dropStatementPattern = regexp.MustCompile(`(?i)drop\s+`)
95

96
func findDropStatements(out string) []string {
2✔
97
        lines, err := parser.SplitAndTrim(strings.NewReader(out))
2✔
98
        if err != nil {
2✔
99
                return nil
×
100
        }
×
101
        var drops []string
2✔
102
        for _, line := range lines {
6✔
103
                if dropStatementPattern.MatchString(line) {
6✔
104
                        drops = append(drops, line)
2✔
105
                }
2✔
106
        }
107
        return drops
2✔
108
}
109

110
func CreateShadowDatabase(ctx context.Context, port uint16) (string, error) {
14✔
111
        // Disable background workers in shadow database
14✔
112
        config := start.NewContainerConfig("-c", "max_worker_processes=0")
14✔
113
        hostPort := strconv.FormatUint(uint64(port), 10)
14✔
114
        hostConfig := container.HostConfig{
14✔
115
                PortBindings: nat.PortMap{"5432/tcp": []nat.PortBinding{{HostPort: hostPort}}},
14✔
116
                AutoRemove:   true,
14✔
117
        }
14✔
118
        networkingConfig := network.NetworkingConfig{}
14✔
119
        if utils.Config.Db.MajorVersion <= 14 {
20✔
120
                hostConfig.Tmpfs = map[string]string{"/docker-entrypoint-initdb.d": ""}
6✔
121
        }
6✔
122
        return utils.DockerStart(ctx, config, hostConfig, networkingConfig, "")
14✔
123
}
124

125
func ConnectShadowDatabase(ctx context.Context, timeout time.Duration, options ...func(*pgx.ConnConfig)) (conn *pgx.Conn, err error) {
9✔
126
        // Retry until connected, cancelled, or timeout
9✔
127
        policy := start.NewBackoffPolicy(ctx, timeout)
9✔
128
        config := pgconn.Config{Port: utils.Config.Db.ShadowPort}
9✔
129
        connect := func() (*pgx.Conn, error) {
18✔
130
                return utils.ConnectLocalPostgres(ctx, config, options...)
9✔
131
        }
9✔
132
        return backoff.RetryWithData(connect, policy)
9✔
133
}
134

135
// Required to bypass pg_cron check: https://github.com/citusdata/pg_cron/blob/main/pg_cron.sql#L3
136
const CREATE_TEMPLATE = "CREATE DATABASE contrib_regression TEMPLATE postgres"
137

138
func MigrateShadowDatabase(ctx context.Context, container string, fsys afero.Fs, options ...func(*pgx.ConnConfig)) error {
7✔
139
        migrations, err := migration.ListLocalMigrations(utils.MigrationsDir, afero.NewIOFS(fsys))
7✔
140
        if err != nil {
8✔
141
                return err
1✔
142
        }
1✔
143
        conn, err := ConnectShadowDatabase(ctx, 10*time.Second, options...)
6✔
144
        if err != nil {
7✔
145
                return err
1✔
146
        }
1✔
147
        defer conn.Close(context.Background())
5✔
148
        if err := start.SetupDatabase(ctx, conn, container[:12], os.Stderr, fsys); err != nil {
7✔
149
                return err
2✔
150
        }
2✔
151
        if _, err := conn.Exec(ctx, CREATE_TEMPLATE); err != nil {
3✔
152
                return errors.Errorf("failed to create template database: %w", err)
×
153
        }
×
154
        return migration.ApplyMigrations(ctx, migrations, conn, afero.NewIOFS(fsys))
3✔
155
}
156

157
func DiffDatabase(ctx context.Context, schema []string, config pgconn.Config, w io.Writer, fsys afero.Fs, differ DiffFunc, options ...func(*pgx.ConnConfig)) (string, error) {
8✔
158
        fmt.Fprintln(w, "Creating shadow database...")
8✔
159
        shadow, err := CreateShadowDatabase(ctx, utils.Config.Db.ShadowPort)
8✔
160
        if err != nil {
12✔
161
                return "", err
4✔
162
        }
4✔
163
        defer utils.DockerRemove(shadow)
4✔
164
        if err := start.WaitForHealthyService(ctx, utils.Config.Db.HealthTimeout, shadow); err != nil {
5✔
165
                return "", err
1✔
166
        }
1✔
167
        if err := MigrateShadowDatabase(ctx, shadow, fsys, options...); err != nil {
4✔
168
                return "", err
1✔
169
        }
1✔
170
        shadowConfig := pgconn.Config{
2✔
171
                Host:     utils.Config.Hostname,
2✔
172
                Port:     utils.Config.Db.ShadowPort,
2✔
173
                User:     "postgres",
2✔
174
                Password: utils.Config.Db.Password,
2✔
175
                Database: "postgres",
2✔
176
        }
2✔
177
        if utils.IsLocalDatabase(config) {
2✔
178
                if declared, err := loadDeclaredSchemas(fsys); len(declared) > 0 {
×
179
                        config = shadowConfig
×
180
                        config.Database = "contrib_regression"
×
181
                        if err := migrateBaseDatabase(ctx, config, declared, fsys, options...); err != nil {
×
182
                                return "", err
×
183
                        }
×
184
                } else if err != nil {
×
185
                        return "", err
×
186
                }
×
187
        }
188
        // Load all user defined schemas
189
        if len(schema) > 0 {
4✔
190
                fmt.Fprintln(w, "Diffing schemas:", strings.Join(schema, ","))
2✔
191
        } else {
2✔
192
                fmt.Fprintln(w, "Diffing schemas...")
×
193
        }
×
194
        return differ(ctx, shadowConfig, config, schema, options...)
2✔
195
}
196

197
func migrateBaseDatabase(ctx context.Context, config pgconn.Config, migrations []string, fsys afero.Fs, options ...func(*pgx.ConnConfig)) error {
×
198
        fmt.Fprintln(os.Stderr, "Creating local database from declarative schemas:")
×
199
        msg := make([]string, len(migrations))
×
200
        for i, m := range migrations {
×
201
                msg[i] = fmt.Sprintf(" • %s", utils.Bold(m))
×
202
        }
×
203
        fmt.Fprintln(os.Stderr, strings.Join(msg, "\n"))
×
204
        conn, err := utils.ConnectLocalPostgres(ctx, config, options...)
×
205
        if err != nil {
×
206
                return err
×
207
        }
×
208
        defer conn.Close(context.Background())
×
209
        return migration.SeedGlobals(ctx, migrations, conn, afero.NewIOFS(fsys))
×
210
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc