code.vegaprotocol.io/vega@v0.79.0/blockexplorer/store/store.go (about)

     1  // Copyright (C) 2023 Gobalsky Labs Limited
     2  //
     3  // This program is free software: you can redistribute it and/or modify
     4  // it under the terms of the GNU Affero General Public License as
     5  // published by the Free Software Foundation, either version 3 of the
     6  // License, or (at your option) any later version.
     7  //
     8  // This program is distributed in the hope that it will be useful,
     9  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    10  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    11  // GNU Affero General Public License for more details.
    12  //
    13  // You should have received a copy of the GNU Affero General Public License
    14  // along with this program.  If not, see <http://www.gnu.org/licenses/>.
    15  
    16  package store
    17  
    18  import (
    19  	"context"
    20  	"fmt"
    21  
    22  	"code.vegaprotocol.io/vega/logging"
    23  
    24  	"github.com/jackc/pgx/v4/pgxpool"
    25  )
    26  
    27  type Store struct {
    28  	log      *logging.Logger
    29  	pool     *pgxpool.Pool
    30  	migrator *Migrator
    31  }
    32  
    33  func (s *Store) Close() {
    34  	if s.pool != nil {
    35  		s.log.Info("Closing connection to database")
    36  		s.pool.Close()
    37  	}
    38  }
    39  
    40  func NewStore(config Config, log *logging.Logger) (*Store, error) {
    41  	log = log.Named(namedLogger)
    42  
    43  	log.Info("Initiating connection to database")
    44  
    45  	poolConfig, err := config.Postgres.ToPgxPoolConfig()
    46  	if err != nil {
    47  		return nil, fmt.Errorf("creating connection source: %w", err)
    48  	}
    49  
    50  	pool, err := pgxpool.ConnectConfig(context.Background(), poolConfig)
    51  	if err != nil {
    52  		return nil, fmt.Errorf("error connecting to database: %w", err)
    53  	}
    54  
    55  	migrator := NewMigrator(pool, config)
    56  
    57  	store := &Store{
    58  		log:      log,
    59  		pool:     pool,
    60  		migrator: migrator,
    61  	}
    62  	return store, nil
    63  }
    64  
    65  func MustNewStore(config Config, log *logging.Logger) *Store {
    66  	store, err := NewStore(config, log)
    67  	if err != nil {
    68  		log.Fatal("creating store", logging.Error(err))
    69  	}
    70  	return store
    71  }
    72  
    73  func (s *Store) Migrate(ctx context.Context) error {
    74  	err := s.migrator.Migrate(ctx)
    75  	if err != nil {
    76  		s.log.Errorf("error migrating database: %v", err)
    77  		return err
    78  	}
    79  
    80  	return nil
    81  }