-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathlibsql.test.ts
More file actions
160 lines (131 loc) · 5.13 KB
/
libsql.test.ts
File metadata and controls
160 lines (131 loc) · 5.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
import { type Client, createClient } from '@libsql/client';
import retry from 'async-retry';
import type { MutationOption } from 'drizzle-orm/cache/core';
import { Cache } from 'drizzle-orm/cache/core';
import { sql } from 'drizzle-orm';
import { drizzle, type LibSQLDatabase } from 'drizzle-orm/libsql';
import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';
import { migrate } from 'drizzle-orm/libsql/migrator';
import { afterAll, beforeAll, beforeEach, expect, test } from 'vitest';
import { skipTests } from '~/common';
import { randomString } from '~/utils';
import { anotherUsersMigratorTable, tests, usersMigratorTable } from './sqlite-common';
import { TestCache, TestGlobalCache, tests as cacheTests } from './sqlite-common-cache';
const ENABLE_LOGGING = false;
let db: LibSQLDatabase;
let dbGlobalCached: LibSQLDatabase;
let cachedDb: LibSQLDatabase;
let roundTripCachedDb: LibSQLDatabase;
let client: Client;
// eslint-disable-next-line drizzle-internal/require-entity-kind
class JsonRoundTripCache extends Cache {
private data = new Map<string, string>();
override strategy(): 'explicit' | 'all' {
return 'explicit';
}
override async get(key: string): Promise<any[] | undefined> {
const stored = this.data.get(key);
return stored === undefined ? undefined : JSON.parse(stored);
}
override async put(key: string, response: any): Promise<void> {
this.data.set(key, JSON.stringify(response));
}
override async onMutate(_params: MutationOption): Promise<void> {}
}
const cacheRoundTripUsers = sqliteTable('cache_roundtrip_users', {
id: integer('id').primaryKey({ autoIncrement: true }),
payload: text('payload', { mode: 'json' }).$type<{ a: number }>().notNull(),
});
beforeAll(async () => {
const url = process.env['LIBSQL_URL'];
const authToken = process.env['LIBSQL_AUTH_TOKEN'];
if (!url) {
throw new Error('LIBSQL_URL is not set');
}
client = await retry(async () => {
client = createClient({ url, authToken });
return client;
}, {
retries: 20,
factor: 1,
minTimeout: 250,
maxTimeout: 250,
randomize: false,
onRetry() {
client?.close();
},
});
db = drizzle(client, { logger: ENABLE_LOGGING });
cachedDb = drizzle(client, { logger: ENABLE_LOGGING, cache: new TestCache() });
dbGlobalCached = drizzle(client, { logger: ENABLE_LOGGING, cache: new TestGlobalCache() });
roundTripCachedDb = drizzle(client, { logger: ENABLE_LOGGING, cache: new JsonRoundTripCache() });
});
afterAll(async () => {
client?.close();
});
beforeEach((ctx) => {
ctx.sqlite = {
db,
};
ctx.cachedSqlite = {
db: cachedDb,
dbGlobalCached,
};
});
test('migrator', async () => {
await db.run(sql`drop table if exists another_users`);
await db.run(sql`drop table if exists users12`);
await db.run(sql`drop table if exists __drizzle_migrations`);
await migrate(db, { migrationsFolder: './drizzle2/sqlite' });
await db.insert(usersMigratorTable).values({ name: 'John', email: 'email' }).run();
const result = await db.select().from(usersMigratorTable).all();
await db.insert(anotherUsersMigratorTable).values({ name: 'John', email: 'email' }).run();
const result2 = await db.select().from(anotherUsersMigratorTable).all();
expect(result).toEqual([{ id: 1, name: 'John', email: 'email' }]);
expect(result2).toEqual([{ id: 1, name: 'John', email: 'email' }]);
await db.run(sql`drop table another_users`);
await db.run(sql`drop table users12`);
await db.run(sql`drop table __drizzle_migrations`);
});
test('migrator : migrate with custom table', async () => {
const customTable = randomString();
await db.run(sql`drop table if exists another_users`);
await db.run(sql`drop table if exists users12`);
await db.run(sql`drop table if exists ${sql.identifier(customTable)}`);
await migrate(db, { migrationsFolder: './drizzle2/sqlite', migrationsTable: customTable });
// test if the custom migrations table was created
const res = await db.all(sql`select * from ${sql.identifier(customTable)};`);
expect(res.length > 0).toBeTruthy();
// test if the migrated table are working as expected
await db.insert(usersMigratorTable).values({ name: 'John', email: 'email' });
const result = await db.select().from(usersMigratorTable);
expect(result).toEqual([{ id: 1, name: 'John', email: 'email' }]);
await db.run(sql`drop table another_users`);
await db.run(sql`drop table users12`);
await db.run(sql`drop table ${sql.identifier(customTable)}`);
});
test('libsql cache hit should keep row values after JSON roundtrip', async () => {
await db.run(sql`drop table if exists cache_roundtrip_users`);
await db.run(
sql`
create table cache_roundtrip_users (
id integer primary key AUTOINCREMENT,
payload text not null
)
`,
);
await db.insert(cacheRoundTripUsers).values({
payload: { a: 1 },
});
const first = await roundTripCachedDb.select().from(cacheRoundTripUsers).$withCache();
const second = await roundTripCachedDb.select().from(cacheRoundTripUsers).$withCache();
expect(first).toEqual([{ id: 1, payload: { a: 1 } }]);
expect(second).toEqual(first);
await db.run(sql`drop table if exists cache_roundtrip_users`);
});
skipTests([
'delete with limit and order by',
'update with limit and order by',
]);
cacheTests();
tests();