db.go 1.53 KB
Newer Older
Hamdi Allam's avatar
Hamdi Allam committed
1
// Database module defines the data DB struct which wraps specific DB interfaces for L1/L2 block headers, contract events, bridging schemas.
2 3 4 5 6
package database

import (
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
7
	"gorm.io/gorm/logger"
8 9 10 11 12 13 14 15 16 17 18 19
)

type DB struct {
	gorm *gorm.DB

	Blocks         BlocksDB
	ContractEvents ContractEventsDB
	Bridge         BridgeDB
}

func NewDB(dsn string) (*DB, error) {
	gorm, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
Hamdi Allam's avatar
Hamdi Allam committed
20
		// The indexer will explicitly manage the transaction
21 22
		// flow processing blocks
		SkipDefaultTransaction: true,
23 24 25 26

		// We may choose to create an adapter such that the
		// logger emits to the geth logger when on DEBUG mode
		Logger: logger.Default.LogMode(logger.Silent),
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
	})

	if err != nil {
		return nil, err
	}

	db := &DB{
		gorm:           gorm,
		Blocks:         newBlocksDB(gorm),
		ContractEvents: newContractEventsDB(gorm),
		Bridge:         newBridgeDB(gorm),
	}

	return db, nil
}
42 43 44 45 46 47 48 49 50

// Transaction executes all operations conducted with the supplied database in a single
// transaction. If the supplied function errors, the transaction is rolled back.
func (db *DB) Transaction(fn func(db *DB) error) error {
	return db.gorm.Transaction(func(tx *gorm.DB) error {
		return fn(dbFromGormTx(tx))
	})
}

51 52 53 54 55 56 57 58 59
func (db *DB) Close() error {
	sql, err := db.gorm.DB()
	if err != nil {
		return err
	}

	return sql.Close()
}

60 61 62 63 64 65 66 67
func dbFromGormTx(tx *gorm.DB) *DB {
	return &DB{
		gorm:           tx,
		Blocks:         newBlocksDB(tx),
		ContractEvents: newContractEventsDB(tx),
		Bridge:         newBridgeDB(tx),
	}
}