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

supabase / cli / 15821228673

23 Jun 2025 10:01AM UTC coverage: 55.517% (+0.05%) from 55.466%
15821228673

push

github

web-flow
fix: diff declarative schemas without supabase stop (#3747)

* fix: diff declarative schemas without supabase stop

* fix: refactor entrypoint for older pg images

* chore: update unit tests

* chore: show stacktrace when developing locally

27 of 52 new or added lines in 3 files covered. (51.92%)

1 existing line in 1 file now uncovered.

6028 of 10858 relevant lines covered (55.52%)

6.27 hits per line

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

71.43
/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) {
3✔
34
        // 1. Load all user defined schemas
3✔
35
        if len(schema) == 0 {
4✔
36
                schema, err = loadSchema(ctx, config, options...)
1✔
37
                if err != nil {
2✔
38
                        return err
1✔
39
                }
1✔
40
        }
41
        // 3. Run migra to diff schema
42
        out, err := DiffDatabase(ctx, schema, config, os.Stderr, fsys, differ, options...)
2✔
43
        if err != nil {
3✔
44
                return err
1✔
45
        }
1✔
46
        branch := keys.GetGitBranch(fsys)
1✔
47
        fmt.Fprintln(os.Stderr, "Finished "+utils.Aqua("supabase db diff")+" on branch "+utils.Aqua(branch)+".\n")
1✔
48
        if err := SaveDiff(out, file, fsys); err != nil {
1✔
49
                return err
×
50
        }
×
51
        drops := findDropStatements(out)
1✔
52
        if len(drops) > 0 {
1✔
53
                fmt.Fprintln(os.Stderr, "Found drop statements in schema diff. Please double check if these are expected:")
×
54
                fmt.Fprintln(os.Stderr, utils.Yellow(strings.Join(drops, "\n")))
×
55
        }
×
56
        return nil
1✔
57
}
58

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

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

86
func findDropStatements(out string) []string {
2✔
87
        lines, err := parser.SplitAndTrim(strings.NewReader(out))
2✔
88
        if err != nil {
2✔
89
                return nil
×
90
        }
×
91
        var drops []string
2✔
92
        for _, line := range lines {
6✔
93
                if dropStatementPattern.MatchString(line) {
6✔
94
                        drops = append(drops, line)
2✔
95
                }
2✔
96
        }
97
        return drops
2✔
98
}
99

100
func loadSchema(ctx context.Context, config pgconn.Config, options ...func(*pgx.ConnConfig)) ([]string, error) {
1✔
101
        conn, err := utils.ConnectByConfig(ctx, config, options...)
1✔
102
        if err != nil {
1✔
103
                return nil, err
×
104
        }
×
105
        defer conn.Close(context.Background())
1✔
106
        // RLS policies in auth and storage schemas can be included with -s flag
1✔
107
        return migration.ListUserSchemas(ctx, conn)
1✔
108
}
109

110
func CreateShadowDatabase(ctx context.Context, port uint16) (string, error) {
13✔
111
        // Disable background workers in shadow database
13✔
112
        config := start.NewContainerConfig("-c", "max_worker_processes=0")
13✔
113
        hostPort := strconv.FormatUint(uint64(port), 10)
13✔
114
        hostConfig := container.HostConfig{
13✔
115
                PortBindings: nat.PortMap{"5432/tcp": []nat.PortBinding{{HostPort: hostPort}}},
13✔
116
                AutoRemove:   true,
13✔
117
        }
13✔
118
        networkingConfig := network.NetworkingConfig{}
13✔
119
        if utils.Config.Db.MajorVersion <= 14 {
18✔
120
                hostConfig.Tmpfs = map[string]string{"/docker-entrypoint-initdb.d": ""}
5✔
121
        }
5✔
122
        return utils.DockerStart(ctx, config, hostConfig, networkingConfig, "")
13✔
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✔
NEW
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 func(context.Context, string, string, []string) (string, error), options ...func(*pgx.ConnConfig)) (string, error) {
7✔
158
        fmt.Fprintln(w, "Creating shadow database...")
7✔
159
        shadow, err := CreateShadowDatabase(ctx, utils.Config.Db.ShadowPort)
7✔
160
        if err != nil {
10✔
161
                return "", err
3✔
162
        }
3✔
163
        defer utils.DockerRemove(shadow)
4✔
164
        if err := start.WaitForHealthyService(ctx, start.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✔
NEW
178
                if declared, err := loadDeclaredSchemas(fsys); err != nil {
×
NEW
179
                        return "", err
×
NEW
180
                } else if len(declared) > 0 {
×
NEW
181
                        config = shadowConfig
×
NEW
182
                        config.Database = "contrib_regression"
×
NEW
183
                        if err := migrateBaseDatabase(ctx, config, declared, fsys, options...); err != nil {
×
NEW
184
                                return "", err
×
NEW
185
                        }
×
186
                }
187
        }
188
        fmt.Fprintln(w, "Diffing schemas:", strings.Join(schema, ","))
2✔
189
        source := utils.ToPostgresURL(shadowConfig)
2✔
190
        target := utils.ToPostgresURL(config)
2✔
191
        return differ(ctx, source, target, schema)
2✔
192
}
193

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