Skip to content
Open
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
2 changes: 1 addition & 1 deletion src/utils/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ export async function getLocalDatabase(database: SqliteDatabaseConfig | D1Databa

const fetchDevelopmentCache = async () => {
const result = await db.prepare('SELECT * FROM _development_cache').all() as CacheEntry[]
return result.reduce((acc, cur) => ({ ...acc, [cur.id]: cur }), {} as Record<string, CacheEntry>)
return Object.fromEntries(result.map(cur => [cur.id, cur]))
}

const fetchDevelopmentCacheForKey = async (id: string) => {
Expand Down
53 changes: 53 additions & 0 deletions test/unit/developmentCacheIndex.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { describe, expect, test } from 'vitest'
import type { Connector } from 'db0'
import type { CacheEntry } from '../../src/types'
import { databaseVersion, getLocalDatabase } from '../../src/utils/database'

async function fetchCache(rows: CacheEntry[]) {
const connector = {
exec: async () => {},
prepare: () => ({
get: async () => ({ value: databaseVersion }),
all: async () => rows,
}),
} as unknown as Connector
const db = await getLocalDatabase({ type: 'sqlite', filename: ':cache-index-test:' }, { connector })
try {
return await db.fetchDevelopmentCache()
}
finally {
db.close()
}
}

describe('fetchDevelopmentCache', () => {
test('returns an ordinary empty object for no rows', async () => {
const cache = await fetchCache([])
expect(cache).toEqual({})
expect(Object.getPrototypeOf(cache)).toBe(Object.prototype)
})

test('indexes complete rows by id, keeping the last duplicate', async () => {
const first = { id: 'first', value: 'old', checksum: 'old-checksum' }
const second = { id: 'second', value: 'other', checksum: 'other-checksum' }
const replacement = { id: 'first', value: 'new', checksum: 'new-checksum' }
const cache = await fetchCache([first, second, replacement])
expect(Object.keys(cache)).toEqual(['first', 'second'])
expect(cache.first).toBe(replacement)
expect(cache.second).toBe(second)
})

test('preserves special ids as ordinary own properties', async () => {
const rows = ['__proto__', 'constructor'].map(id => ({ id, value: id, checksum: id }))
const cache = await fetchCache(rows)
expect(Object.getPrototypeOf(cache)).toBe(Object.prototype)
for (const row of rows) {
expect(Object.getOwnPropertyDescriptor(cache, row.id)).toEqual({
value: row,
writable: true,
enumerable: true,
configurable: true,
})
}
})
})
Loading