Skip to content

Commit

Permalink
Get ready to handle optimistic concurrency control at the resource level
Browse files Browse the repository at this point in the history
Refs #1973
  • Loading branch information
thewilkybarkid committed Oct 10, 2024
1 parent 0b3ee7e commit 9ec18fd
Showing 1 changed file with 32 additions and 3 deletions.
35 changes: 32 additions & 3 deletions src/LibsqlEventStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ export const make: Effect.Effect<EventStore.EventStore, SqlError.SqlError, SqlCl
yield* sql`
CREATE TABLE IF NOT EXISTS resources (
id TEXT NOT NULL PRIMARY KEY,
type TEXT NOT NULL
type TEXT NOT NULL,
version INTEGER NOT NULL
)
`

Expand Down Expand Up @@ -107,6 +108,7 @@ export const make: Effect.Effect<EventStore.EventStore, SqlError.SqlError, SqlCl
const encoded = yield* Schema.encode(ResourcesTable)({
id: resourceId,
type: 'Feedback',
version: lastKnownVersion,
})

if (lastKnownVersion === 0) {
Expand All @@ -115,11 +117,13 @@ export const make: Effect.Effect<EventStore.EventStore, SqlError.SqlError, SqlCl
INSERT INTO
resources (
id,
type
type,
version
)
SELECT
${encoded.id},
${encoded.type}
${encoded.type},
${encoded.version}
WHERE
NOT EXISTS (
SELECT
Expand Down Expand Up @@ -210,6 +214,30 @@ export const make: Effect.Effect<EventStore.EventStore, SqlError.SqlError, SqlCl
}),
),
),
Effect.tap(newVersion =>
Effect.gen(function* () {
const encoded = yield* Schema.encode(ResourcesTable)({
id: resourceId,
type: 'Feedback',
version: newVersion,
})

const results = yield* pipe(
sql`
UPDATE resources
SET
version = ${encoded.version}
WHERE
id = ${resourceId}
`.raw,
Effect.andThen(Schema.decodeUnknown(LibsqlResults)),
)

if (results.rowsAffected !== 1) {
yield* new EventStore.ResourceHasChanged()
}
}),
),
),
)
.pipe(
Expand All @@ -232,6 +260,7 @@ export const make: Effect.Effect<EventStore.EventStore, SqlError.SqlError, SqlCl
const ResourcesTable = Schema.Struct({
id: Uuid.UuidSchema,
type: Schema.String,
version: Schema.Number,
})

const EventsTable = Schema.transformOrFail(
Expand Down

0 comments on commit 9ec18fd

Please sign in to comment.