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
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"export-data": "echo 'Use the /export endpoint: curl http://localhost:8787/export?table=tablename > export.sql'",
"validate": "wrangler d1 list && echo 'Validation: Check that your D1 database ID matches wrangler.toml'",
"get-schema": "echo 'Get database schema: curl http://localhost:8787/schema'",
"get-migration": "echo 'Generate migration script: curl http://localhost:8787/migration-script > postgres-migration.sql'"
"get-migration": "echo 'Generate migration script: curl http://localhost:8787/migration-script > postgres-migration.sql'",
"test": "node --import tsx --test test/**/*.test.ts"
},
"keywords": [
"cloudflare",
Expand Down
24 changes: 21 additions & 3 deletions src/auto-mirror.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Env } from './worker';
import { translateSqliteWriteToPostgres } from './sql-utils';

export class AutoMirrorDB {
constructor(private env: Env) { }
Expand Down Expand Up @@ -76,11 +77,20 @@ export class AutoMirrorDB {
private async mirrorToPostgres(sql: string, params: unknown[]) {
try {
const pgSql = this.convertPlaceholders(sql, params.length);
const translation = await translateSqliteWriteToPostgres(this.env, pgSql, params);

if (translation.type === 'skip') {
console.log(
`Skipping Postgres mirror for statement "${truncateSql(sql)}": ${translation.reason}`
);
return;
}

const opId = crypto.randomUUID();

await this.env.MIRROR_QUEUE.send({
sql: pgSql,
params,
sql: translation.sql,
params: translation.params,
opId
});
} catch (error) {
Expand All @@ -93,4 +103,12 @@ export class AutoMirrorDB {
let i = 1;
return sql.replace(/\?/g, () => `$${i++}`);
}
}
}

function truncateSql(sql: string, max = 80): string {
const normalized = sql.replace(/\s+/g, ' ').trim();
if (normalized.length <= max) {
return normalized;
}
return `${normalized.slice(0, max - 1)}…`;
}
Loading