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

supabase / cli / 19987703178

06 Dec 2025 11:15AM UTC coverage: 56.191%. First build
19987703178

Pull #4589

github

web-flow
Merge 5cd5c42f4 into 03a9671e4
Pull Request #4589: fix(db diff): filter inherited constraints for partitioned tables

15 of 20 new or added lines in 2 files covered. (75.0%)

6830 of 12155 relevant lines covered (56.19%)

6.31 hits per line

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

70.13
/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, 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
        out = filterInheritedConstraints(out)
1✔
39
        branch := keys.GetGitBranch(fsys)
1✔
40
        fmt.Fprintln(os.Stderr, "Finished "+utils.Aqua("supabase db diff")+" on branch "+utils.Aqua(branch)+".\n")
1✔
41
        if err := SaveDiff(out, file, fsys); err != nil {
1✔
42
                return err
×
43
        }
×
44
        drops := findDropStatements(out)
1✔
45
        if len(drops) > 0 {
1✔
46
                fmt.Fprintln(os.Stderr, "Found drop statements in schema diff. Please double check if these are expected:")
×
47
                fmt.Fprintln(os.Stderr, utils.Yellow(strings.Join(drops, "\n")))
×
48
        }
×
49
        return nil
1✔
50
}
51

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

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

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

93
var inheritedConstraintPattern = regexp.MustCompile(`(?i)alter\s+table\s+[^;]+\s+(drop|add)\s+constraint\s+"[^"]*fkey\d+"`)
94

95
func filterInheritedConstraints(out string) string {
8✔
96
        lines, err := parser.SplitAndTrim(strings.NewReader(out))
8✔
97
        if err != nil {
8✔
NEW
98
                return out
×
NEW
99
        }
×
100
        var filtered []string
8✔
101
        for _, line := range lines {
29✔
102
                if !inheritedConstraintPattern.MatchString(line) {
29✔
103
                        filtered = append(filtered, line)
8✔
104
                }
8✔
105
        }
106
        if len(filtered) == 0 {
11✔
107
                return ""
3✔
108
        }
3✔
109
        result := strings.Join(filtered, ";\n\n") + ";"
5✔
110
        if strings.HasSuffix(out, "\n") {
5✔
NEW
111
                result += "\n"
×
NEW
112
        }
×
113
        return result
5✔
114
}
115

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

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

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

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

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

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