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

supabase / cli / 23284726315

19 Mar 2026 07:39AM UTC coverage: 61.481% (-0.4%) from 61.9%
23284726315

Pull #4894

github

web-flow
Merge b8d90d71d into 3b50e7e4b
Pull Request #4894: feat(pull): add debug logs for ssl check

50 of 150 new or added lines in 3 files covered. (33.33%)

6 existing lines in 2 files now uncovered.

8054 of 13100 relevant lines covered (61.48%)

7.34 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

199
func migrateBaseDatabase(ctx context.Context, config pgconn.Config, migrations []string, fsys afero.Fs, options ...func(*pgx.ConnConfig)) error {
×
200
        fmt.Fprintln(os.Stderr, "Creating local database from declarative schemas:")
×
201
        msg := make([]string, len(migrations))
×
202
        for i, m := range migrations {
×
203
                msg[i] = fmt.Sprintf(" • %s", utils.Bold(m))
×
204
        }
×
205
        fmt.Fprintln(os.Stderr, strings.Join(msg, "\n"))
×
206
        conn, err := utils.ConnectLocalPostgres(ctx, config, options...)
×
207
        if err != nil {
×
208
                return err
×
209
        }
×
210
        defer conn.Close(context.Background())
×
211
        return migration.SeedGlobals(ctx, migrations, conn, afero.NewIOFS(fsys))
×
212
}
213

214
func diffWithStream(ctx context.Context, env []string, script string, stdout io.Writer) error {
2✔
215
        cmd := []string{"edge-runtime", "start", "--main-service=."}
2✔
216
        if viper.GetBool("DEBUG") {
2✔
NEW
217
                cmd = append(cmd, "--verbose")
×
NEW
218
        }
×
219
        cmdString := strings.Join(cmd, " ")
2✔
220
        entrypoint := []string{"sh", "-c", `cat <<'EOF' > index.ts && ` + cmdString + `
2✔
221
` + script + `
2✔
222
EOF
2✔
223
`}
2✔
224
        var stderr bytes.Buffer
2✔
225
        if err := utils.DockerRunOnceWithConfig(
2✔
226
                ctx,
2✔
227
                container.Config{
2✔
228
                        Image:      utils.Config.EdgeRuntime.Image,
2✔
229
                        Env:        env,
2✔
230
                        Entrypoint: entrypoint,
2✔
231
                },
2✔
232
                container.HostConfig{
2✔
233
                        Binds:       []string{utils.EdgeRuntimeId + ":/root/.cache/deno:rw"},
2✔
234
                        NetworkMode: network.NetworkHost,
2✔
235
                },
2✔
236
                network.NetworkingConfig{},
2✔
237
                "",
2✔
238
                stdout,
2✔
239
                &stderr,
2✔
240
        ); err != nil && !strings.Contains(stderr.String(), "main worker has been destroyed") {
3✔
241
                return errors.Errorf("error diffing schema: %w:\n%s", err, stderr.String())
1✔
242
        }
1✔
243
        return nil
1✔
244
}
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