Skip to content

Commit

Permalink
Fix database returning stale data after calling overwriteDatabaseFile…
Browse files Browse the repository at this point in the history
… on it
  • Loading branch information
DallasHoff committed Jul 31, 2024
1 parent 4148bfa commit 8017f99
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,7 @@ export class SQLocalProcessor {
this.config.databasePath,
database
);
await this.init();
this.emitMessage({
type: 'success',
queryKey,
Expand Down
2 changes: 2 additions & 0 deletions test/get-database-file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@ describe('getDatabaseFile', () => {

await sql`CREATE TABLE nums (num REAL NOT NULL)`;
const file = await getDatabaseFile();
const now = new Date().getTime();

expect(file).toBeInstanceOf(File);
expect(file.name).toBe(fileName);
expect(file.size).toBe(16384);
expect(file.type).toBe('application/x-sqlite3');
expect(now - file.lastModified).toBeLessThan(50);

let dirHandle = await navigator.storage.getDirectory();

Expand Down
29 changes: 29 additions & 0 deletions test/overwrite-database-file.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { describe, it, expect, afterAll } from 'vitest';
import { SQLocal } from '../src/index';

describe('overwriteDatabaseFile', async () => {
const db1 = new SQLocal('overwrite-test-db1.sqlite3');
const db2 = new SQLocal('overwrite-test-db2.sqlite3');

await db1.sql`CREATE TABLE letters (letter TEXT NOT NULL)`;
await db1.sql`INSERT INTO letters (letter) VALUES ('a'), ('b'), ('c')`;

await db2.sql`CREATE TABLE nums (num INTEGER NOT NULL)`;
await db2.sql`INSERT INTO nums (num) VALUES (1), (2), (3)`;

afterAll(async () => {
const opfs = await navigator.storage.getDirectory();
await opfs.removeEntry('overwrite-test-db1.sqlite3');
await opfs.removeEntry('overwrite-test-db2.sqlite3');
});

it('should replace the contents of a database', async () => {
const db2File = await db2.getDatabaseFile();
await db1.overwriteDatabaseFile(db2File);

const letters = db1.sql`SELECT * FROM letters`;
expect(letters).rejects.toThrow();
const nums = db1.sql`SELECT * FROM nums`;
expect(nums).resolves.toEqual([{ num: 1 }, { num: 2 }, { num: 3 }]);
});
});

2 comments on commit 8017f99

@pycanis
Copy link

@pycanis pycanis commented on 8017f99 Aug 1, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fixed a bug in my app, thank you!

@DallasHoff
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fixed a bug in my app, thank you!

Sure thing! Glad to hear it

Please sign in to comment.