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

supabase / cli / 13392899334

18 Feb 2025 02:28PM UTC coverage: 58.349% (+0.07%) from 58.278%
13392899334

push

github

sweatybridge
chore: remove unnecessary config load

2 of 4 new or added lines in 2 files covered. (50.0%)

252 existing lines in 9 files now uncovered.

7789 of 13349 relevant lines covered (58.35%)

201.84 hits per line

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

66.45
/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
        // Sanity checks.
3✔
35
        if utils.IsLocalDatabase(config) {
3✔
UNCOV
36
                if container, err := createShadowIfNotExists(ctx, fsys); err != nil {
×
37
                        return err
×
38
                } else if len(container) > 0 {
×
39
                        defer utils.DockerRemove(container)
×
40
                        if err := start.WaitForHealthyService(ctx, start.HealthTimeout, container); err != nil {
×
41
                                return err
×
42
                        }
×
43
                        if err := migrateBaseDatabase(ctx, container, fsys, options...); err != nil {
×
44
                                return err
×
45
                        }
×
46
                }
47
        }
48
        // 1. Load all user defined schemas
49
        if len(schema) == 0 {
4✔
50
                schema, err = loadSchema(ctx, config, options...)
1✔
51
                if err != nil {
2✔
52
                        return err
1✔
53
                }
1✔
54
        }
55
        // 3. Run migra to diff schema
56
        out, err := DiffDatabase(ctx, schema, config, os.Stderr, fsys, differ, options...)
2✔
57
        if err != nil {
3✔
58
                return err
1✔
59
        }
1✔
60
        branch := keys.GetGitBranch(fsys)
1✔
61
        fmt.Fprintln(os.Stderr, "Finished "+utils.Aqua("supabase db diff")+" on branch "+utils.Aqua(branch)+".\n")
1✔
62
        if err := SaveDiff(out, file, fsys); err != nil {
1✔
63
                return err
×
64
        }
×
65
        drops := findDropStatements(out)
1✔
66
        if len(drops) > 0 {
1✔
67
                fmt.Fprintln(os.Stderr, "Found drop statements in schema diff. Please double check if these are expected:")
×
68
                fmt.Fprintln(os.Stderr, utils.Yellow(strings.Join(drops, "\n")))
×
69
        }
×
70
        return nil
1✔
71
}
72

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

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

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

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

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

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

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

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

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

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