setupSampleInstance starts a single postgres sample instance.
(ctx context.Context, databaseName string, port int, sampleData string)
| 97 | |
| 98 | // setupSampleInstance starts a single postgres sample instance. |
| 99 | func setupSampleInstance(ctx context.Context, databaseName string, port int, sampleData string) error { |
| 100 | defaultDB, err := sql.Open("pgx", fmt.Sprintf("user=%s host=%s port=%d database=postgres", SampleUser, common.GetPostgresSocketDir(), port)) |
| 101 | if err != nil { |
| 102 | return err |
| 103 | } |
| 104 | defer defaultDB.Close() |
| 105 | |
| 106 | var ok bool |
| 107 | if err := defaultDB.QueryRowContext(ctx, "SELECT EXISTS (SELECT 1 FROM pg_database WHERE datname = $1);", databaseName).Scan(&ok); err != nil { |
| 108 | return err |
| 109 | } |
| 110 | if ok { |
| 111 | slog.Info(fmt.Sprintf("Sample database %s already exists, skip setup", databaseName)) |
| 112 | return nil |
| 113 | } |
| 114 | |
| 115 | if _, err := defaultDB.ExecContext(ctx, fmt.Sprintf("CREATE DATABASE %s", databaseName)); err != nil { // NOSONAR(go:S2077) databaseName is a hardcoded constant from envDB map, not user input |
| 116 | return errors.Wrapf(err, "failed to create sample database") |
| 117 | } |
| 118 | |
| 119 | db, err := sql.Open("pgx", fmt.Sprintf("user=%s host=%s port=%d database=%s", SampleUser, common.GetPostgresSocketDir(), port, databaseName)) |
| 120 | if err != nil { |
| 121 | return err |
| 122 | } |
| 123 | defer db.Close() |
| 124 | |
| 125 | if _, err := db.ExecContext(ctx, sampleData); err != nil { |
| 126 | return err |
| 127 | } |
| 128 | return nil |
| 129 | } |
no test coverage detected