From ce1f66ccd65a4079df7fbba9d8719561cfb7fe5a Mon Sep 17 00:00:00 2001 From: bros Date: Thu, 28 Mar 2024 19:23:22 +0000 Subject: [PATCH] Add batch backup --- db/migrations/state/validium-001.sql | 32 ++++++++++++++++++++++++++ state/pgstatestorage/pgstatestorage.go | 19 +++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 db/migrations/state/validium-001.sql diff --git a/db/migrations/state/validium-001.sql b/db/migrations/state/validium-001.sql new file mode 100644 index 0000000000..d0f3fc40e7 --- /dev/null +++ b/db/migrations/state/validium-001.sql @@ -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; \ No newline at end of file diff --git a/state/pgstatestorage/pgstatestorage.go b/state/pgstatestorage/pgstatestorage.go index 090aee86c7..d8d7307cdb 100644 --- a/state/pgstatestorage/pgstatestorage.go +++ b/state/pgstatestorage/pgstatestorage.go @@ -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 {