Skip to content

Commit 45d9211

Browse files
committed
feat: sync to electric
1 parent 89be0c5 commit 45d9211

File tree

3 files changed

+34
-41
lines changed

3 files changed

+34
-41
lines changed

Diff for: server/index.js

+9-3
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { electricSync } from "@electric-sql/pglite-sync";
22
import Fastify from "fastify";
33
import validate from "uuid-validate";
44

5-
import { populate } from "./populate-pglite.js";
5+
import { generateAndSyncToElectric } from "./populate-pglite.js";
66

77
const fastify = Fastify({
88
logger: true,
@@ -17,7 +17,9 @@ const db = await PGlite.create({
1717

1818
console.log("Waiting for db to be ready");
1919
await db.waitReady;
20-
await populate(db);
20+
21+
console.log("Syncing shapes");
22+
await generateAndSyncToElectric(db);
2123

2224
fastify.get("/users", async (_req, reply) => {
2325
const res = await db.exec(
@@ -36,10 +38,14 @@ fastify.get("/users/:userId", async (req, reply) => {
3638
if (!validate(userId)) {
3739
reply.send(`The id provided ${userId} is not a valid UUID`);
3840
}
39-
const res = await db.exec(
41+
const res = await db.live.query(
4042
`
4143
SELECT * from users WHERE id = '${userId}'
4244
`,
45+
null,
46+
(res) => {
47+
JSON.stringify(res.rows, null, 2);
48+
},
4349
);
4450
const rows = res[0].rows;
4551

Diff for: server/populate-pglite.js

+15-38
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,5 @@
1-
import { generateUsers } from "../db/generate-data.js";
2-
3-
const USERS_TO_LOAD = 1000000;
4-
5-
async function makeInsertQuery(db, data) {
6-
const columns = Object.keys(data);
7-
const columnNames = columns.join(`, `);
8-
const values = columns.map((column) => data[column]);
9-
const sql = `
10-
INSERT INTO users (${columnNames})
11-
VALUES (${values.map((value) => `'${value}'`)})
12-
`;
13-
console.log("Inserting data...");
14-
return await db.exec(sql);
15-
}
16-
17-
//generate users//
18-
export async function populate(db) {
19-
//run pglite queries
1+
//generate table and sync to electric//
2+
export async function generateAndSyncToElectric(db) {
203
await db.exec(`
214
CREATE TABLE IF NOT EXISTS users (
225
id uuid PRIMARY KEY,
@@ -35,23 +18,17 @@ export async function populate(db) {
3518
)
3619
`);
3720

38-
const users = generateUsers(USERS_TO_LOAD);
39-
const userCount = users.length;
40-
const batchSize = 100;
41-
for (let i = 0; i < userCount; i += batchSize) {
42-
db.exec(`SET CONSTRAINTS ALL DEFERRED;`); // disable FK checks
43-
44-
const batch = users.slice(i, i + batchSize);
45-
const promises = batch.map(async (user, index) => {
46-
if ((i + index + 1) % 100 === 0 || i + index + 1 === userCount) {
47-
process.stdout.write(`Loading user ${i + index + 1} of ${userCount}\r`);
48-
}
49-
return await makeInsertQuery(db, user);
50-
});
51-
try {
52-
await Promise.all(promises);
53-
} catch (err) {
54-
console.error("Batch failed", err);
55-
}
56-
}
21+
const shape = await db.electric.syncShapeToTable({
22+
shape: {
23+
url: `${env.ELECTRIC_URL}/v1/shape`,
24+
params: {
25+
table: "users",
26+
sourceSecret: env.ELECTRIC_SOURCE_SECRET,
27+
sourceId: env.ELECTRIC_SOURCE_ID,
28+
},
29+
},
30+
table: "users",
31+
primaryKey: ["id"],
32+
});
33+
return shape;
5734
}

Diff for: sst.config.ts

+10
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,16 @@ export default $config({
1818
};
1919
},
2020
async run() {
21+
// env var checks
22+
if (
23+
!process.env.ELECTRIC_SOURCE_ID &&
24+
!process.env.ELECTRIC_SOURCE_SECRET
25+
) {
26+
throw new Error(
27+
`ELECTRIC_SOURCE_ID and ELECTRIC_SOURCE_SECRET is not set`,
28+
);
29+
}
30+
2131
const { getNeonConnectionString, createNeonDb } = await import("./neon");
2232
// Create a db in Neon
2333
const project = neon.getProjectOutput({ id: `square-flower-52864146` });

0 commit comments

Comments
 (0)