File size: 1,336 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package migratetest

import (
	"bytes"
	"context"
	"sync"

	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/target/goalert/devtools/pgdump-lite"
)

// Snapshot is a snapshot of a database's schema and data.
type Snapshot struct {
	Schema    *pgdump.Schema
	TableData []TableSnapshot
}

var snapshotBuf bytes.Buffer
var mx sync.Mutex

// NewSnapshotURL will create a new Snapshot from a database URL.
func NewSnapshotURL(ctx context.Context, dbURL string) (*Snapshot, error) {
	cfg, err := pgxpool.ParseConfig(dbURL)
	if err != nil {
		return nil, err
	}

	db, err := pgxpool.NewWithConfig(ctx, cfg)
	if err != nil {
		return nil, err
	}
	defer db.Close()

	return NewSnapshot(ctx, db)
}

// NewSnapshot will create a new Snapshot from a database connection.
func NewSnapshot(ctx context.Context, db *pgxpool.Pool) (*Snapshot, error) {
	mx.Lock()
	defer mx.Unlock()

	schema, err := pgdump.DumpSchema(ctx, db)
	if err != nil {
		return nil, err
	}

	snapshotBuf.Reset()
	err = pgdump.DumpDataWithSchemaParallel(ctx, db, &snapshotBuf, nil, schema)
	if err != nil {
		return nil, err
	}

	scan := NewCopyScanner(&snapshotBuf)
	var tables []TableSnapshot
	for scan.Scan() {
		tables = append(tables, scan.Table())
	}
	if scan.Err() != nil {
		return nil, scan.Err()
	}

	return &Snapshot{
		Schema:    schema,
		TableData: tables,
	}, nil
}