Skip to content

Commit

Permalink
Add batch backup
Browse files Browse the repository at this point in the history
  • Loading branch information
arnaubennassar authored and Stefan-Ethernal committed Apr 15, 2024
1 parent 4bb2522 commit ce1f66c
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
32 changes: 32 additions & 0 deletions db/migrations/state/validium-001.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
-- +migrate Up

CREATE TABLE IF NOT EXISTS state.batch_data_backup
(
batch_num BIGINT,
data BYTEA,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (batch_num, created_at)
);

-- +migrate StatementBegin
CREATE OR REPLACE FUNCTION backup_batch() RETURNS trigger AS $$
BEGIN
INSERT INTO state.batch_data_backup (batch_num, data)
VALUES (OLD.batch_num, OLD.raw_txs_data)
ON CONFLICT (batch_num, created_at) DO UPDATE SET
data = EXCLUDED.data;
RETURN OLD;
END;
$$
LANGUAGE plpgsql;
-- +migrate StatementEnd

CREATE TRIGGER backup_batch
BEFORE DELETE ON state.batch FOR EACH ROW
EXECUTE PROCEDURE backup_batch();

-- +migrate Down

DROP TRIGGER IF EXISTS backup_batch ON state.batch;
DROP FUNCTION IF EXISTS backup_batch();
DROP TABLE IF EXISTS state.batch_data_backup;
19 changes: 19 additions & 0 deletions state/pgstatestorage/pgstatestorage.go
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,25 @@ func (p *PostgresStorage) GetBatchL2DataByNumber(ctx context.Context, batchNumbe
var batchL2Data []byte
err := q.QueryRow(ctx, getBatchL2DataByBatchNumber, batchNumber).Scan(&batchL2Data)

if errors.Is(err, pgx.ErrNoRows) {
return p.GetBatchL2DataByNumberFromBackup(ctx, batchNumber, dbTx)
} else if err != nil {
return nil, err
}
return batchL2Data, nil
}

// GetBatchL2DataByNumberFromBackup returns the batch L2 data of the given batch number from the backup table
func (p *PostgresStorage) GetBatchL2DataByNumberFromBackup(ctx context.Context, batchNumber uint64, dbTx pgx.Tx) ([]byte, error) {
getBatchL2DataByBatchNumber := `
SELECT data FROM state.batch_data_backup
WHERE batch_num = $1
ORDER BY created_at DESC
LIMIT 1
`
q := p.getExecQuerier(dbTx)
var batchL2Data []byte
err := q.QueryRow(ctx, getBatchL2DataByBatchNumber, batchNumber).Scan(&batchL2Data)
if errors.Is(err, pgx.ErrNoRows) {
return nil, state.ErrNotFound
} else if err != nil {
Expand Down

0 comments on commit ce1f66c

Please sign in to comment.