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

supabase / cli / 16171299294

09 Jul 2025 01:55PM UTC coverage: 55.524%. First build
16171299294

Pull #3829

github

web-flow
Merge 411bf1e33 into 5713d2046
Pull Request #3829: fix: allow diff to run with stopped db

1 of 4 new or added lines in 1 file covered. (25.0%)

6076 of 10943 relevant lines covered (55.52%)

6.26 hits per line

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

64.83
/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/gen/keys"
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, string, string, []string) (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 := keys.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
func loadDeclaredSchemas(fsys afero.Fs) ([]string, error) {
1✔
52
        if schemas := utils.Config.Db.Migrations.SchemaPaths; len(schemas) > 0 {
1✔
53
                return schemas.Files(afero.NewIOFS(fsys))
×
54
        }
×
55
        if exists, err := afero.DirExists(fsys, utils.SchemasDir); err != nil {
1✔
56
                return nil, errors.Errorf("failed to check schemas: %w", err)
×
57
        } else if !exists {
1✔
58
                return nil, nil
×
59
        }
×
60
        var declared []string
1✔
61
        if err := afero.Walk(fsys, utils.SchemasDir, func(path string, info fs.FileInfo, err error) error {
10✔
62
                if err != nil {
9✔
63
                        return err
×
64
                }
×
65
                if info.Mode().IsRegular() && filepath.Ext(info.Name()) == ".sql" {
13✔
66
                        declared = append(declared, path)
4✔
67
                }
4✔
68
                return nil
9✔
69
        }); err != nil {
×
70
                return nil, errors.Errorf("failed to walk dir: %w", err)
×
71
        }
×
72
        return declared, nil
1✔
73
}
74

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

78
func findDropStatements(out string) []string {
2✔
79
        lines, err := parser.SplitAndTrim(strings.NewReader(out))
2✔
80
        if err != nil {
2✔
81
                return nil
×
82
        }
×
83
        var drops []string
2✔
84
        for _, line := range lines {
6✔
85
                if dropStatementPattern.MatchString(line) {
6✔
86
                        drops = append(drops, line)
2✔
87
                }
2✔
88
        }
89
        return drops
2✔
90
}
91

92
func loadSchema(ctx context.Context, config pgconn.Config, options ...func(*pgx.ConnConfig)) ([]string, error) {
×
93
        conn, err := utils.ConnectByConfig(ctx, config, options...)
×
94
        if err != nil {
×
95
                return nil, err
×
96
        }
×
97
        defer conn.Close(context.Background())
×
98
        // RLS policies in auth and storage schemas can be included with -s flag
×
99
        return migration.ListUserSchemas(ctx, conn)
×
100
}
101

102
func CreateShadowDatabase(ctx context.Context, port uint16) (string, error) {
13✔
103
        // Disable background workers in shadow database
13✔
104
        config := start.NewContainerConfig("-c", "max_worker_processes=0")
13✔
105
        hostPort := strconv.FormatUint(uint64(port), 10)
13✔
106
        hostConfig := container.HostConfig{
13✔
107
                PortBindings: nat.PortMap{"5432/tcp": []nat.PortBinding{{HostPort: hostPort}}},
13✔
108
                AutoRemove:   true,
13✔
109
        }
13✔
110
        networkingConfig := network.NetworkingConfig{}
13✔
111
        if utils.Config.Db.MajorVersion <= 14 {
18✔
112
                hostConfig.Tmpfs = map[string]string{"/docker-entrypoint-initdb.d": ""}
5✔
113
        }
5✔
114
        return utils.DockerStart(ctx, config, hostConfig, networkingConfig, "")
13✔
115
}
116

117
func ConnectShadowDatabase(ctx context.Context, timeout time.Duration, options ...func(*pgx.ConnConfig)) (conn *pgx.Conn, err error) {
9✔
118
        // Retry until connected, cancelled, or timeout
9✔
119
        policy := start.NewBackoffPolicy(ctx, timeout)
9✔
120
        config := pgconn.Config{Port: utils.Config.Db.ShadowPort}
9✔
121
        connect := func() (*pgx.Conn, error) {
18✔
122
                return utils.ConnectLocalPostgres(ctx, config, options...)
9✔
123
        }
9✔
124
        return backoff.RetryWithData(connect, policy)
9✔
125
}
126

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

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

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

192
func migrateBaseDatabase(ctx context.Context, config pgconn.Config, migrations []string, fsys afero.Fs, options ...func(*pgx.ConnConfig)) error {
×
193
        fmt.Fprintln(os.Stderr, "Creating local database from declarative schemas:")
×
194
        msg := make([]string, len(migrations))
×
195
        for i, m := range migrations {
×
196
                msg[i] = fmt.Sprintf(" • %s", utils.Bold(m))
×
197
        }
×
198
        fmt.Fprintln(os.Stderr, strings.Join(msg, "\n"))
×
199
        conn, err := utils.ConnectLocalPostgres(ctx, config, options...)
×
200
        if err != nil {
×
201
                return err
×
202
        }
×
203
        defer conn.Close(context.Background())
×
204
        return migration.SeedGlobals(ctx, migrations, conn, afero.NewIOFS(fsys))
×
205
}
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

© 2025 Coveralls, Inc