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

supabase / cli / 13390433793

18 Feb 2025 12:22PM UTC coverage: 58.287% (+0.009%) from 58.278%
13390433793

Pull #3160

github

web-flow
Merge 8aa41bb28 into ef456e312
Pull Request #3160: feat: config option for ordering declarative schemas

46 of 52 new or added lines in 4 files covered. (88.46%)

10 existing lines in 4 files now uncovered.

7793 of 13370 relevant lines covered (58.29%)

201.54 hits per line

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

67.1
/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/internal/utils/flags"
28
        "github.com/supabase/cli/pkg/migration"
29
        "github.com/supabase/cli/pkg/parser"
30
)
31

32
type DiffFunc func(context.Context, string, string, []string) (string, error)
33

34
func Run(ctx context.Context, schema []string, file string, config pgconn.Config, differ DiffFunc, fsys afero.Fs, options ...func(*pgx.ConnConfig)) (err error) {
4✔
35
        // Sanity checks.
4✔
36
        if err := flags.LoadConfig(fsys); err != nil {
5✔
37
                return err
1✔
38
        }
1✔
39
        if utils.IsLocalDatabase(config) {
3✔
40
                if container, err := createShadowIfNotExists(ctx, fsys); err != nil {
×
41
                        return err
×
42
                } else if len(container) > 0 {
×
43
                        defer utils.DockerRemove(container)
×
44
                        if err := start.WaitForHealthyService(ctx, start.HealthTimeout, container); err != nil {
×
45
                                return err
×
46
                        }
×
47
                        if err := migrateBaseDatabase(ctx, container, fsys, options...); err != nil {
×
48
                                return err
×
49
                        }
×
50
                }
51
        }
52
        // 1. Load all user defined schemas
53
        if len(schema) == 0 {
4✔
54
                schema, err = loadSchema(ctx, config, options...)
1✔
55
                if err != nil {
2✔
56
                        return err
1✔
57
                }
1✔
58
        }
59
        // 3. Run migra to diff schema
60
        out, err := DiffDatabase(ctx, schema, config, os.Stderr, fsys, differ, options...)
2✔
61
        if err != nil {
3✔
62
                return err
1✔
63
        }
1✔
64
        branch := keys.GetGitBranch(fsys)
1✔
65
        fmt.Fprintln(os.Stderr, "Finished "+utils.Aqua("supabase db diff")+" on branch "+utils.Aqua(branch)+".\n")
1✔
66
        if err := SaveDiff(out, file, fsys); err != nil {
1✔
67
                return err
×
68
        }
×
69
        drops := findDropStatements(out)
1✔
70
        if len(drops) > 0 {
1✔
71
                fmt.Fprintln(os.Stderr, "Found drop statements in schema diff. Please double check if these are expected:")
×
72
                fmt.Fprintln(os.Stderr, utils.Yellow(strings.Join(drops, "\n")))
×
73
        }
×
74
        return nil
1✔
75
}
76

77
func createShadowIfNotExists(ctx context.Context, fsys afero.Fs) (string, error) {
×
78
        if exists, err := afero.DirExists(fsys, utils.SchemasDir); err != nil {
×
79
                return "", errors.Errorf("failed to check schemas: %w", err)
×
80
        } else if !exists {
×
81
                return "", nil
×
82
        }
×
83
        if err := utils.AssertSupabaseDbIsRunning(); !errors.Is(err, utils.ErrNotRunning) {
×
84
                return "", err
×
85
        }
×
86
        fmt.Fprintf(os.Stderr, "Creating local database from %s...\n", utils.Bold(utils.SchemasDir))
×
87
        return CreateShadowDatabase(ctx, utils.Config.Db.Port)
×
88
}
89

90
func loadDeclaredSchemas(fsys afero.Fs) ([]string, error) {
1✔
91
        if schemas := utils.Config.Db.Migrations.SchemaPaths; len(schemas) > 0 {
1✔
NEW
92
                return schemas.Files(afero.NewIOFS(fsys))
×
NEW
93
        }
×
94
        var declared []string
1✔
95
        if err := afero.Walk(fsys, utils.SchemasDir, func(path string, info fs.FileInfo, err error) error {
10✔
96
                if err != nil {
9✔
97
                        return err
×
98
                }
×
99
                if info.Mode().IsRegular() && filepath.Ext(info.Name()) == ".sql" {
13✔
100
                        declared = append(declared, path)
4✔
101
                }
4✔
102
                return nil
9✔
103
        }); err != nil {
×
104
                return nil, errors.Errorf("failed to walk dir: %w", err)
×
105
        }
×
106
        return declared, nil
1✔
107
}
108

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

112
func findDropStatements(out string) []string {
2✔
113
        lines, err := parser.SplitAndTrim(strings.NewReader(out))
2✔
114
        if err != nil {
2✔
115
                return nil
×
116
        }
×
117
        var drops []string
2✔
118
        for _, line := range lines {
6✔
119
                if dropStatementPattern.MatchString(line) {
6✔
120
                        drops = append(drops, line)
2✔
121
                }
2✔
122
        }
123
        return drops
2✔
124
}
125

126
func loadSchema(ctx context.Context, config pgconn.Config, options ...func(*pgx.ConnConfig)) ([]string, error) {
1✔
127
        conn, err := utils.ConnectByConfig(ctx, config, options...)
1✔
128
        if err != nil {
1✔
129
                return nil, err
×
130
        }
×
131
        defer conn.Close(context.Background())
1✔
132
        // RLS policies in auth and storage schemas can be included with -s flag
1✔
133
        return migration.ListUserSchemas(ctx, conn)
1✔
134
}
135

136
func CreateShadowDatabase(ctx context.Context, port uint16) (string, error) {
6✔
137
        config := start.NewContainerConfig()
6✔
138
        hostPort := strconv.FormatUint(uint64(port), 10)
6✔
139
        hostConfig := container.HostConfig{
6✔
140
                PortBindings: nat.PortMap{"5432/tcp": []nat.PortBinding{{HostPort: hostPort}}},
6✔
141
                AutoRemove:   true,
6✔
142
        }
6✔
143
        networkingConfig := network.NetworkingConfig{}
6✔
144
        if utils.Config.Db.MajorVersion <= 14 {
10✔
145
                config.Entrypoint = nil
4✔
146
                hostConfig.Tmpfs = map[string]string{"/docker-entrypoint-initdb.d": ""}
4✔
147
        }
4✔
148
        return utils.DockerStart(ctx, config, hostConfig, networkingConfig, "")
6✔
149
}
150

151
func ConnectShadowDatabase(ctx context.Context, timeout time.Duration, options ...func(*pgx.ConnConfig)) (conn *pgx.Conn, err error) {
6✔
152
        // Retry until connected, cancelled, or timeout
6✔
153
        policy := start.NewBackoffPolicy(ctx, timeout)
6✔
154
        config := pgconn.Config{Port: utils.Config.Db.ShadowPort}
6✔
155
        connect := func() (*pgx.Conn, error) {
12✔
156
                return utils.ConnectLocalPostgres(ctx, config, options...)
6✔
157
        }
6✔
158
        return backoff.RetryWithData(connect, policy)
6✔
159
}
160

161
func MigrateShadowDatabase(ctx context.Context, container string, fsys afero.Fs, options ...func(*pgx.ConnConfig)) error {
7✔
162
        migrations, err := migration.ListLocalMigrations(utils.MigrationsDir, afero.NewIOFS(fsys))
7✔
163
        if err != nil {
8✔
164
                return err
1✔
165
        }
1✔
166
        conn, err := ConnectShadowDatabase(ctx, 10*time.Second, options...)
6✔
167
        if err != nil {
7✔
168
                return err
1✔
169
        }
1✔
170
        defer conn.Close(context.Background())
5✔
171
        if err := start.SetupDatabase(ctx, conn, container[:12], os.Stderr, fsys); err != nil {
7✔
172
                return err
2✔
173
        }
2✔
174
        return migration.ApplyMigrations(ctx, migrations, conn, afero.NewIOFS(fsys))
3✔
175
}
176

177
func migrateBaseDatabase(ctx context.Context, container string, fsys afero.Fs, options ...func(*pgx.ConnConfig)) error {
×
178
        migrations, err := loadDeclaredSchemas(fsys)
×
179
        if err != nil {
×
180
                return err
×
181
        }
×
182
        conn, err := utils.ConnectLocalPostgres(ctx, pgconn.Config{}, options...)
×
183
        if err != nil {
×
184
                return err
×
185
        }
×
186
        defer conn.Close(context.Background())
×
187
        if err := start.SetupDatabase(ctx, conn, container[:12], os.Stderr, fsys); err != nil {
×
188
                return err
×
189
        }
×
190
        return migration.SeedGlobals(ctx, migrations, conn, afero.NewIOFS(fsys))
×
191
}
192

193
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) {
6✔
194
        fmt.Fprintln(w, "Creating shadow database...")
6✔
195
        shadow, err := CreateShadowDatabase(ctx, utils.Config.Db.ShadowPort)
6✔
196
        if err != nil {
8✔
197
                return "", err
2✔
198
        }
2✔
199
        defer utils.DockerRemove(shadow)
4✔
200
        if err := start.WaitForHealthyService(ctx, start.HealthTimeout, shadow); err != nil {
5✔
201
                return "", err
1✔
202
        }
1✔
203
        if err := MigrateShadowDatabase(ctx, shadow, fsys, options...); err != nil {
4✔
204
                return "", err
1✔
205
        }
1✔
206
        fmt.Fprintln(w, "Diffing schemas:", strings.Join(schema, ","))
2✔
207
        source := utils.ToPostgresURL(pgconn.Config{
2✔
208
                Host:     utils.Config.Hostname,
2✔
209
                Port:     utils.Config.Db.ShadowPort,
2✔
210
                User:     "postgres",
2✔
211
                Password: utils.Config.Db.Password,
2✔
212
                Database: "postgres",
2✔
213
        })
2✔
214
        target := utils.ToPostgresURL(config)
2✔
215
        return differ(ctx, source, target, schema)
2✔
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