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

supabase / cli / 23253461919

18 Mar 2026 03:45PM UTC coverage: 63.53% (+1.6%) from 61.9%
23253461919

Pull #4966

github

web-flow
Merge 7e5d417b9 into bce705147
Pull Request #4966: feat: add pg delta declarative sync command

517 of 1437 new or added lines in 17 files covered. (35.98%)

8 existing lines in 4 files now uncovered.

9156 of 14412 relevant lines covered (63.53%)

6.89 hits per line

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

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

3
import (
4
        "context"
5
        "fmt"
6
        "io"
7
        "io/fs"
8
        "os"
9
        "path/filepath"
10
        "regexp"
11
        "sort"
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/pgdelta"
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, usePgDelta bool, fsys afero.Fs, options ...func(*pgx.ConnConfig)) (err error) {
2✔
34
        out, err := DiffDatabase(ctx, schema, config, os.Stderr, fsys, differ, usePgDelta, 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
func loadDeclaredSchemas(fsys afero.Fs) ([]string, error) {
1✔
52
        // When pg-delta is enabled, declarative path is the source of truth (config or default).
1✔
53
        if utils.IsPgDeltaEnabled() {
1✔
NEW
54
                declDir := utils.GetDeclarativeDir()
×
NEW
55
                if exists, err := afero.DirExists(fsys, declDir); err == nil && exists {
×
NEW
56
                        var declared []string
×
NEW
57
                        if err := afero.Walk(fsys, declDir, func(path string, info fs.FileInfo, err error) error {
×
NEW
58
                                if err != nil {
×
NEW
59
                                        return err
×
NEW
60
                                }
×
NEW
61
                                if info.Mode().IsRegular() && filepath.Ext(info.Name()) == ".sql" {
×
NEW
62
                                        declared = append(declared, path)
×
NEW
63
                                }
×
NEW
64
                                return nil
×
NEW
65
                        }); err != nil {
×
NEW
66
                                return nil, errors.Errorf("failed to walk declarative dir: %w", err)
×
NEW
67
                        }
×
NEW
68
                        sort.Strings(declared)
×
NEW
69
                        return declared, nil
×
70
                }
71
        }
72
        if schemas := utils.Config.Db.Migrations.SchemaPaths; len(schemas) > 0 {
1✔
UNCOV
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
        // Keep file application order deterministic so diff output stays stable across
93
        // filesystems and operating systems. This is only if no schema paths in config are set.
94
        sort.Strings(declared)
1✔
95
        return declared, nil
1✔
96
}
97

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

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

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

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

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

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

162
func DiffDatabase(ctx context.Context, schema []string, config pgconn.Config, w io.Writer, fsys afero.Fs, differ DiffFunc, usePgDelta bool, options ...func(*pgx.ConnConfig)) (string, error) {
8✔
163
        fmt.Fprintln(w, "Creating shadow database...")
8✔
164
        shadow, err := CreateShadowDatabase(ctx, utils.Config.Db.ShadowPort)
8✔
165
        if err != nil {
12✔
166
                return "", err
4✔
167
        }
4✔
168
        defer utils.DockerRemove(shadow)
4✔
169
        if err := start.WaitForHealthyService(ctx, utils.Config.Db.HealthTimeout, shadow); err != nil {
5✔
170
                return "", err
1✔
171
        }
1✔
172
        if err := MigrateShadowDatabase(ctx, shadow, fsys, options...); err != nil {
4✔
173
                return "", err
1✔
174
        }
1✔
175
        shadowConfig := pgconn.Config{
2✔
176
                Host:     utils.Config.Hostname,
2✔
177
                Port:     utils.Config.Db.ShadowPort,
2✔
178
                User:     "postgres",
2✔
179
                Password: utils.Config.Db.Password,
2✔
180
                Database: "postgres",
2✔
181
        }
2✔
182
        if utils.IsLocalDatabase(config) {
2✔
183
                if declared, err := loadDeclaredSchemas(fsys); len(declared) > 0 {
×
184
                        config = shadowConfig
×
185
                        config.Database = "contrib_regression"
×
NEW
186
                        if usePgDelta {
×
NEW
187
                                declDir := utils.GetDeclarativeDir()
×
NEW
188
                                if exists, _ := afero.DirExists(fsys, declDir); exists {
×
NEW
189
                                        if err := pgdelta.ApplyDeclarative(ctx, config, fsys); err != nil {
×
NEW
190
                                                return "", err
×
NEW
191
                                        }
×
NEW
192
                                } else {
×
NEW
193
                                        if err := migrateBaseDatabase(ctx, config, declared, fsys, options...); err != nil {
×
NEW
194
                                                return "", err
×
NEW
195
                                        }
×
196
                                }
NEW
197
                        } else {
×
NEW
198
                                if err := migrateBaseDatabase(ctx, config, declared, fsys, options...); err != nil {
×
NEW
199
                                        return "", err
×
NEW
200
                                }
×
201
                        }
202
                } else if err != nil {
×
203
                        return "", err
×
204
                }
×
205
        }
206
        // Load all user defined schemas
207
        if len(schema) > 0 {
4✔
208
                fmt.Fprintln(w, "Diffing schemas:", strings.Join(schema, ","))
2✔
209
        } else {
2✔
210
                fmt.Fprintln(w, "Diffing schemas...")
×
211
        }
×
212
        return differ(ctx, shadowConfig, config, schema, options...)
2✔
213
}
214

215
func migrateBaseDatabase(ctx context.Context, config pgconn.Config, migrations []string, fsys afero.Fs, options ...func(*pgx.ConnConfig)) error {
×
216
        fmt.Fprintln(os.Stderr, "Creating local database from declarative schemas:")
×
217
        msg := make([]string, len(migrations))
×
218
        for i, m := range migrations {
×
219
                msg[i] = fmt.Sprintf(" • %s", utils.Bold(m))
×
220
        }
×
221
        fmt.Fprintln(os.Stderr, strings.Join(msg, "\n"))
×
222
        conn, err := utils.ConnectLocalPostgres(ctx, config, options...)
×
223
        if err != nil {
×
224
                return err
×
225
        }
×
226
        defer conn.Close(context.Background())
×
227
        return migration.SeedGlobals(ctx, migrations, conn, afero.NewIOFS(fsys))
×
228
}
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