MCPcopy Create free account
hub / github.com/electric-sql/electric / startSyncToDatabase

Function startSyncToDatabase

examples/linearlite/src/sync.ts:27–136  ·  view source on GitHub ↗
(pg: PGliteWithExtensions)

Source from the content-addressed store, hash-verified

25}
26
27async function startSyncToDatabase(pg: PGliteWithExtensions) {
28 // Check if there are any issues already in the database
29 const issues = await pg.query(`SELECT 1 FROM issue LIMIT 1`)
30 const hasIssuesAtStart = issues.rows.length > 0
31
32 let issueShapeInitialSyncDone = false
33 let commentShapeInitialSyncDone = false
34 let postInitialSyncDone = false
35
36 if (!hasIssuesAtStart && !postInitialSyncDone) {
37 updateSyncStatus(`initial-sync`, `Downloading shape data...`)
38 }
39
40 let postInitialSyncDoneResolver: () => void
41 const postInitialSyncDonePromise = new Promise<void>((resolve) => {
42 postInitialSyncDoneResolver = resolve
43 })
44
45 const doPostInitialSync = async () => {
46 if (
47 !hasIssuesAtStart &&
48 issueShapeInitialSyncDone &&
49 commentShapeInitialSyncDone &&
50 !postInitialSyncDone
51 ) {
52 postInitialSyncDone = true
53 updateSyncStatus(`initial-sync`, `Creating indexes...`)
54 await postInitialSync(pg)
55 postInitialSyncDoneResolver()
56 }
57 }
58
59 const issueUrl = new URL(`${ELECTRIC_URL}/v1/shape`)
60 if (ELECTRIC_SOURCE_SECRET) {
61 issueUrl.searchParams.set(`secret`, ELECTRIC_SOURCE_SECRET)
62 }
63
64 // Issues Sync
65 const issuesSync = await pg.sync.syncShapeToTable({
66 shape: {
67 url: issueUrl.toString(),
68 params: {
69 table: `issue`,
70 source_id: ELECTRIC_SOURCE_ID,
71 },
72 },
73 table: `issue`,
74 primaryKey: [`id`],
75 shapeKey: `issues`,
76 commitGranularity: `up-to-date`,
77 useCopy: true,
78 onInitialSync: async () => {
79 issueShapeInitialSyncDone = true
80 await pg.exec(`ALTER TABLE issue ENABLE TRIGGER ALL`)
81 doPostInitialSync()
82 },
83 })
84 issuesSync.subscribe(

Callers 1

startSyncFunction · 0.85

Calls 8

updateSyncStatusFunction · 0.85
doPostInitialSyncFunction · 0.85
queryMethod · 0.80
setMethod · 0.65
execMethod · 0.65
subscribeMethod · 0.65
toStringMethod · 0.45
errorMethod · 0.45

Tested by

no test coverage detected