Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactoring: unique constraint for contract.address and codeBundle.codeHash #437

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions src/db/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,66 @@ export class Database extends Dexie {
codeBundles: '++id, codeHash, name, date',
contracts: '++id, address, codeHash, name, date',
});

// Stores same as version 1, but with removes duplicate codeBundles and contracts during upgrade
this.version(2)
.stores({
codeBundles: '++id, codeHash, name, date',
contracts: '++id, address, codeHash, name, date',
})
.upgrade(async transaction => {
const bundleCodeHashes = new Set<string>();
const duplicateBundles: Array<CodeBundleDocument['id']> = [];

const contractAddresses = new Set<string>();
const duplicateContracts: Array<ContractDocument['id']> = [];

// Iterate over all code bundles and collect id's of duplicate code hashes
await Promise.all([
transaction.table('codeBundles').each((codeBundle: CodeBundleDocument) => {
if (bundleCodeHashes.has(codeBundle.codeHash)) {
duplicateBundles.push(codeBundle.id);
} else {
bundleCodeHashes.add(codeBundle.codeHash);
}
}),
transaction.table('contracts').each((contract: ContractDocument) => {
if (contractAddresses.has(contract.address)) {
duplicateContracts.push(contract.id);
} else {
contractAddresses.add(contract.address);
}
}),
]);

return Promise.all([
transaction.table('codeBundles').bulkDelete(duplicateBundles),
transaction.table('contracts').bulkDelete(duplicateContracts),
]);
});

// Adds unique constraint on codeHash.codeHash and contracts.address
// Needs new version because upgrade and new unique constraint throws an error,
// Two step process works fine though
this.version(3).stores({
codeBundles: '++id, &codeHash, name, date',
contracts: '++id, &address, codeHash, name, date',
});
}

/**
* Can be used to populate the initial v1 database with mock data.
*/
_populateWithMockDataV1() {
if (this.verno !== 1) return;

// Populate is only called if the database did not exist
this.on('populate', async () => {
const CodeBundlesMock = (await import('./mocks/v1/codeBundles.json')).default;
await this.table('codeBundles').bulkAdd(CodeBundlesMock);

const ContractsMock = (await import('./mocks/v1/contracts.json')).default;
await this.table('contracts').bulkAdd(ContractsMock);
});
}
}
Loading