MCPcopy Create free account
hub / github.com/chainreactors/EvilProxy / NewPostgresStore

Function NewPostgresStore

internal/store/postgresstore.go:49–100  ·  view source on GitHub ↗

NewPostgresStore establishes a connection to PostgreSQL and prepares the local workspace.

(ctx context.Context, cfg PostgresStoreConfig)

Source from the content-addressed store, hash-verified

47
48// NewPostgresStore establishes a connection to PostgreSQL and prepares the local workspace.
49func NewPostgresStore(ctx context.Context, cfg PostgresStoreConfig) (*PostgresStore, error) {
50 trimmedDSN := strings.TrimSpace(cfg.DSN)
51 if trimmedDSN == "" {
52 return nil, fmt.Errorf("postgres store: DSN is required")
53 }
54 cfg.DSN = trimmedDSN
55 if cfg.ConfigTable == "" {
56 cfg.ConfigTable = defaultConfigTable
57 }
58 if cfg.AuthTable == "" {
59 cfg.AuthTable = defaultAuthTable
60 }
61
62 spoolRoot := strings.TrimSpace(cfg.SpoolDir)
63 if spoolRoot == "" {
64 if cwd, err := os.Getwd(); err == nil {
65 spoolRoot = filepath.Join(cwd, "pgstore")
66 } else {
67 spoolRoot = filepath.Join(os.TempDir(), "pgstore")
68 }
69 }
70 absSpool, err := filepath.Abs(spoolRoot)
71 if err != nil {
72 return nil, fmt.Errorf("postgres store: resolve spool directory: %w", err)
73 }
74 configDir := filepath.Join(absSpool, "config")
75 authDir := filepath.Join(absSpool, "auths")
76 if err = os.MkdirAll(configDir, 0o700); err != nil {
77 return nil, fmt.Errorf("postgres store: create config directory: %w", err)
78 }
79 if err = os.MkdirAll(authDir, 0o700); err != nil {
80 return nil, fmt.Errorf("postgres store: create auth directory: %w", err)
81 }
82
83 db, err := sql.Open("pgx", cfg.DSN)
84 if err != nil {
85 return nil, fmt.Errorf("postgres store: open database connection: %w", err)
86 }
87 if err = db.PingContext(ctx); err != nil {
88 _ = db.Close()
89 return nil, fmt.Errorf("postgres store: ping database: %w", err)
90 }
91
92 store := &PostgresStore{
93 db: db,
94 cfg: cfg,
95 spoolRoot: absSpool,
96 configPath: filepath.Join(configDir, "config.yaml"),
97 authDir: authDir,
98 }
99 return store, nil
100}
101
102// Close releases the underlying database connection.
103func (s *PostgresStore) Close() error {

Callers 1

mainFunction · 0.92

Calls 2

OpenMethod · 0.65
CloseMethod · 0.65

Tested by

no test coverage detected