Public
Script
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
import { sqlite as valtown_sqlite } from "https://esm.town/v/std/sqlite";
export async function migrate(
sqlite: typeof valtown_sqlite,
key: string,
migrations: string[],
) {
await sqlite.execute(`
create table if not exists ${key}_migrations (
name text primary key,
step bigint not null default 0,
updated_at datetime default CURRENT_TIMESTAMP
)
`);
const step_results = await sqlite.execute(
{ sql: `select step from ${key}_migrations where name = ?`, args: [key] },
);
let step = -1;
if (step_results.rows.length == 1) {
step = Number(step_results.rows[0][0]);
}
const batch = [];
for (let i = 0; i < migrations.length; i++) {
if (i > step) {
batch.push(migrations[i]);
}
}
if (batch.length > 0) {
batch.push({
sql: `
insert into ${key}_migrations (name, step)
values (?, ?)
on conflict (name) do update
set step = excluded.step, updated_at = CURRENT_TIMESTAMP
`,
args: [key, migrations.length - 1],
});
await sqlite.batch(batch);
}
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
September 5, 2024