Skip to content

Commit

Permalink
Add ownership to items and session
Browse files Browse the repository at this point in the history
  • Loading branch information
magnetised committed Nov 30, 2022
1 parent d711685 commit cf39fd8
Show file tree
Hide file tree
Showing 7 changed files with 68 additions and 23 deletions.
3 changes: 2 additions & 1 deletion web/migrations/1666288253_create_items/migration.sql
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@ ElectricDB Migration
{"metadata": {"title": "create_items", "name": "1666288253_create_items"}}
*/
CREATE TABLE IF NOT EXISTS main.items (
value TEXT PRIMARY KEY
value TEXT PRIMARY KEY,
user_id TEXT NOT NULL
);
5 changes: 3 additions & 2 deletions web/migrations/1666288253_create_items/postgres.sql
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
/*
ElectricDB Migration
{"metadata": {"title": "create_items", "name": "1666288253_create_items", "sha256": "ddf6ba15a0c6c8a5955ad8c29bc0a785416a47e4d22e0aa8f5f5e2be2e70b46c"}}
{"metadata": {"title": "create_items", "name": "1666288253_create_items", "sha256": "e3dcdc0789d179d44d6a8107e6fb389eb205016a65f5117600def029728c3845"}}
*/

CREATE TABLE public.items (
value text PRIMARY KEY);
value text PRIMARY KEY,
user_id text NOT NULL);
11 changes: 6 additions & 5 deletions web/migrations/1666288253_create_items/satellite.sql
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
/*
ElectricDB Migration
{"metadata": {"title": "create_items", "name": "1666288253_create_items", "sha256": "ddf6ba15a0c6c8a5955ad8c29bc0a785416a47e4d22e0aa8f5f5e2be2e70b46c"}}
{"metadata": {"title": "create_items", "name": "1666288253_create_items", "sha256": "e3dcdc0789d179d44d6a8107e6fb389eb205016a65f5117600def029728c3845"}}
*/
CREATE TABLE IF NOT EXISTS main.items (
value TEXT PRIMARY KEY
value TEXT PRIMARY KEY,
user_id TEXT NOT NULL
);

/*---------------------------------------------
Expand Down Expand Up @@ -39,7 +40,7 @@ CREATE TRIGGER insert_main_items_into_oplog
WHEN 1 == (SELECT flag from _electric_trigger_settings WHERE tablename == 'main.items')
BEGIN
INSERT INTO _electric_oplog (namespace, tablename, optype, primaryKey, newRow, oldRow, timestamp)
VALUES ('main', 'items', 'INSERT', json_object('value', new.value), json_object('value', new.value), NULL, NULL);
VALUES ('main', 'items', 'INSERT', json_object('value', new.value), json_object('value', new.value, 'user_id', new.user_id), NULL, NULL);
END;

DROP TRIGGER IF EXISTS update_main_items_into_oplog;
Expand All @@ -48,7 +49,7 @@ CREATE TRIGGER update_main_items_into_oplog
WHEN 1 == (SELECT flag from _electric_trigger_settings WHERE tablename == 'main.items')
BEGIN
INSERT INTO _electric_oplog (namespace, tablename, optype, primaryKey, newRow, oldRow, timestamp)
VALUES ('main', 'items', 'UPDATE', json_object('value', new.value), json_object('value', new.value), json_object('value', old.value), NULL);
VALUES ('main', 'items', 'UPDATE', json_object('value', new.value), json_object('value', new.value, 'user_id', new.user_id), json_object('value', old.value, 'user_id', old.user_id), NULL);
END;

DROP TRIGGER IF EXISTS delete_main_items_into_oplog;
Expand All @@ -57,7 +58,7 @@ CREATE TRIGGER delete_main_items_into_oplog
WHEN 1 == (SELECT flag from _electric_trigger_settings WHERE tablename == 'main.items')
BEGIN
INSERT INTO _electric_oplog (namespace, tablename, optype, primaryKey, newRow, oldRow, timestamp)
VALUES ('main', 'items', 'DELETE', json_object('value', old.value), NULL, json_object('value', old.value), NULL);
VALUES ('main', 'items', 'DELETE', json_object('value', old.value), NULL, json_object('value', old.value, 'user_id', old.user_id), NULL);
END;


Expand Down
10 changes: 5 additions & 5 deletions web/migrations/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,22 @@ export const data = {
},
{
"body": [
"CREATE TABLE IF NOT EXISTS main.items (\n value TEXT PRIMARY KEY\n);",
"CREATE TABLE IF NOT EXISTS main.items (\n value TEXT PRIMARY KEY,\n user_id TEXT NOT NULL\n);",
"-- These are toggles for turning the triggers on and off\nDROP TABLE IF EXISTS _electric_trigger_settings;",
"CREATE TABLE _electric_trigger_settings(tablename STRING PRIMARY KEY, flag INTEGER);",
"INSERT INTO _electric_trigger_settings(tablename,flag) VALUES ('main.items', 1);",
"-- Ensures primary key is immutable\nDROP TRIGGER IF EXISTS update_ensure_main_items_primarykey;",
"CREATE TRIGGER update_ensure_main_items_primarykey\n BEFORE UPDATE ON main.items\nBEGIN\n SELECT\n CASE\n WHEN old.value != new.value THEN\n RAISE (ABORT,'cannot change the value of column value as it belongs to the primary key')\n END;\nEND;",
"-- Triggers that add INSERT, UPDATE, DELETE operation to the _opslog table\n\nDROP TRIGGER IF EXISTS insert_main_items_into_oplog;",
"CREATE TRIGGER insert_main_items_into_oplog\n AFTER INSERT ON main.items\n WHEN 1 == (SELECT flag from _electric_trigger_settings WHERE tablename == 'main.items')\nBEGIN\n INSERT INTO _electric_oplog (namespace, tablename, optype, primaryKey, newRow, oldRow, timestamp)\n VALUES ('main', 'items', 'INSERT', json_object('value', new.value), json_object('value', new.value), NULL, NULL);\nEND;",
"CREATE TRIGGER insert_main_items_into_oplog\n AFTER INSERT ON main.items\n WHEN 1 == (SELECT flag from _electric_trigger_settings WHERE tablename == 'main.items')\nBEGIN\n INSERT INTO _electric_oplog (namespace, tablename, optype, primaryKey, newRow, oldRow, timestamp)\n VALUES ('main', 'items', 'INSERT', json_object('value', new.value), json_object('value', new.value, 'user_id', new.user_id), NULL, NULL);\nEND;",
"DROP TRIGGER IF EXISTS update_main_items_into_oplog;",
"CREATE TRIGGER update_main_items_into_oplog\n AFTER UPDATE ON main.items\n WHEN 1 == (SELECT flag from _electric_trigger_settings WHERE tablename == 'main.items')\nBEGIN\n INSERT INTO _electric_oplog (namespace, tablename, optype, primaryKey, newRow, oldRow, timestamp)\n VALUES ('main', 'items', 'UPDATE', json_object('value', new.value), json_object('value', new.value), json_object('value', old.value), NULL);\nEND;",
"CREATE TRIGGER update_main_items_into_oplog\n AFTER UPDATE ON main.items\n WHEN 1 == (SELECT flag from _electric_trigger_settings WHERE tablename == 'main.items')\nBEGIN\n INSERT INTO _electric_oplog (namespace, tablename, optype, primaryKey, newRow, oldRow, timestamp)\n VALUES ('main', 'items', 'UPDATE', json_object('value', new.value), json_object('value', new.value, 'user_id', new.user_id), json_object('value', old.value, 'user_id', old.user_id), NULL);\nEND;",
"DROP TRIGGER IF EXISTS delete_main_items_into_oplog;",
"CREATE TRIGGER delete_main_items_into_oplog\n AFTER DELETE ON main.items\n WHEN 1 == (SELECT flag from _electric_trigger_settings WHERE tablename == 'main.items')\nBEGIN\n INSERT INTO _electric_oplog (namespace, tablename, optype, primaryKey, newRow, oldRow, timestamp)\n VALUES ('main', 'items', 'DELETE', json_object('value', old.value), NULL, json_object('value', old.value), NULL);\nEND;"
"CREATE TRIGGER delete_main_items_into_oplog\n AFTER DELETE ON main.items\n WHEN 1 == (SELECT flag from _electric_trigger_settings WHERE tablename == 'main.items')\nBEGIN\n INSERT INTO _electric_oplog (namespace, tablename, optype, primaryKey, newRow, oldRow, timestamp)\n VALUES ('main', 'items', 'DELETE', json_object('value', old.value), NULL, json_object('value', old.value, 'user_id', old.user_id), NULL);\nEND;"
],
"encoding": "escaped",
"name": "1666288253_create_items",
"sha256": "ddf6ba15a0c6c8a5955ad8c29bc0a785416a47e4d22e0aa8f5f5e2be2e70b46c",
"sha256": "e3dcdc0789d179d44d6a8107e6fb389eb205016a65f5117600def029728c3845",
"title": "create_items"
}
]
Expand Down
2 changes: 1 addition & 1 deletion web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"@aphro/absurd-sql": "^0.0.53",
"@aphro/sql.js": "^1.7.0",
"base-64": "^1.0.0",
"electric-sql": "^0.2.2",
"electric-sql": "^0.3.0",
"fs-extra": "^10.0.0",
"react": "^17.0.2",
"react-dom": "^17.0.2"
Expand Down
40 changes: 35 additions & 5 deletions web/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,42 @@ import { initElectricSqlJs, ElectrifiedDatabase} from "electric-sql/browser"
import { ElectricProvider, useElectric, useElectricQuery } from 'electric-sql/react'
import config from '../electric-config'

const key = 'electric-demo-username'
const ls = window.localStorage

const setUserId = () => {
const id = Date.now() + '-' + Math.random().toString(16).substring(2)
ls.setItem(key, id)
return id
}

// if the query string has a `user_id` value, then use that. this allows us to
// open up multiple separate sessions with the same effective user
const getUserId = () => {
const urlParams = new URLSearchParams(window.location.search);
const user_id = urlParams.get('user_id');
if (user_id) {
return user_id
} else {
return ls.getItem(key) || setUserId()
}
}

const user_id: string = getUserId()

const worker = new Worker("./worker.js", { type: "module" });

console.log('using user_id', user_id)

export const ElectrifiedExample = () => {
const [ db, setDb ] = useState<ElectrifiedDatabase>()

useEffect(() => {
const init = async () => {
const SQL = await initElectricSqlJs(worker, {locateFile: (file: string) => `/${file}`})
const electrified = await SQL.openDatabase('example.db', config)
// the dev-mode authentication accepts a user id as the authentication token value
// and logs the session on as that user id
const electrified = await SQL.openDatabase('example.db', {...config, token: user_id})

setDb(electrified)
}
Expand All @@ -25,13 +52,16 @@ export const ElectrifiedExample = () => {

return (
<ElectricProvider db={db}>
<div style={{fontSize: '0.6em'}}>
User ID: <a style={{ color: '#fff' }} href={ `?user_id=${ user_id }` }>{user_id}</a>
</div>
<ExampleComponent />
</ElectricProvider>
)
}

const ExampleComponent = () => {
const { results, error } = useElectricQuery('SELECT value FROM items', [])
const { results, error } = useElectricQuery('SELECT user_id, value FROM items', [])
const db = useElectric() as ElectrifiedDatabase

if (error !== undefined) {
Expand All @@ -49,9 +79,9 @@ const ExampleComponent = () => {
}

const addItem = () => {
const randomValue = Math.random().toString(16).substr(2)
const randomValue = Math.random().toString(16).substring(2)

db.exec('INSERT INTO items VALUES(?)', [randomValue])
db.exec('INSERT INTO items (user_id, value) VALUES(?, ?)', [user_id, randomValue])
}

const clearItems = () => {
Expand All @@ -61,7 +91,7 @@ const ExampleComponent = () => {
return (
<div>
{results.map((item: any, index: any) => (
<p key={ index } className='item'>
<p key={ index } className='item' title={ `belongs to user ${item.user_id}` }>
Item: { item.value }
</p>
))}
Expand Down
20 changes: 16 additions & 4 deletions web/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -460,19 +460,21 @@ ee-first@1.1.1:
resolved "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz"
integrity sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=

electric-sql@^0.2.0:
version "0.2.0"
resolved "https://registry.npmjs.org/electric-sql/-/electric-sql-0.2.0.tgz"
integrity sha512-DUlOHZ5pex97OHeaP/NBRZsFpXT0wFRBtpV6PCpCI7O/DpyUzuqqzlu4tyenynd5IN1BlLtdxGkI7K+4r6qnEQ==
electric-sql@^0.3.0:
version "0.3.0"
resolved "https://registry.yarnpkg.com/electric-sql/-/electric-sql-0.3.0.tgz#5ca6ddeba2ad256b7fa6d62d270c860ba796d79b"
integrity sha512-Z8zbsvlACjAXFu9mMWGT1GIpayh4BH04YDGNRIJK7Deey5t4pq8gTAi1CN/C84GvjfD2trxqmXsbTZS5+OUUHQ==
dependencies:
base-64 "^1.0.0"
events "^3.3.0"
exponential-backoff "^3.1.0"
fastestsmallesttextencoderdecoder "^1.0.22"
frame-stream "^3.0.1"
lodash.throttle "^4.1.1"
long "^5.2.0"
protobufjs "^7.1.1"
sqlite-parser "^1.0.1"
uuid "^9.0.0"
walkjs "^3.2.4"
ws "^8.8.1"

Expand Down Expand Up @@ -558,6 +560,11 @@ events@^3.3.0:
resolved "https://registry.npmjs.org/events/-/events-3.3.0.tgz"
integrity sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==

exponential-backoff@^3.1.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/exponential-backoff/-/exponential-backoff-3.1.0.tgz#9409c7e579131f8bd4b32d7d8094a911040f2e68"
integrity sha512-oBuz5SYz5zzyuHINoe9ooePwSu0xApKWgeNzok4hZ5YKXFh9zrQBEM15CXqoZkJJPuI2ArvqjPQd8UKJA753XA==

fastestsmallesttextencoderdecoder@^1.0.22:
version "1.0.22"
resolved "https://registry.npmjs.org/fastestsmallesttextencoderdecoder/-/fastestsmallesttextencoderdecoder-1.0.22.tgz"
Expand Down Expand Up @@ -1239,6 +1246,11 @@ utils-merge@1.0.1:
resolved "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz"
integrity sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=

uuid@^9.0.0:
version "9.0.0"
resolved "https://registry.yarnpkg.com/uuid/-/uuid-9.0.0.tgz#592f550650024a38ceb0c562f2f6aa435761efb5"
integrity sha512-MXcSTerfPa4uqyzStbRoTgt5XIe3x5+42+q1sDuy3R5MDk66URdLMOZe5aPX/SQd+kuYAh0FdP/pO28IkQyTeg==

vary@^1:
version "1.1.2"
resolved "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz"
Expand Down

0 comments on commit cf39fd8

Please sign in to comment.