Effect CommunityEC
Effect Community•17mo ago•
1 reply
Paweł Błaszczyk

Questions on SQL Updates, Model Schema Derivation, and Partial Schema Creation in effect/sql

Hello, I've started playing with effect/sql and I've got a few questions:

1) Should updating based on previous value work with sql.update? I'm trying to do something like this:
sql`UPDATE ${sql("todo")} SET ${sql.update({ isCompleted: request.isCompleted, version: sql`${sql("version")} + 1` })}`

In theory types for sql.update accept a sql expression inside of object (besides primitive) but I see that it's compiled incorrectly and doesn't update. Currently I just moved this part out of the helper and it works.

2) Is there a way to get column/entity names from Model schemas? I'm declaring my entity with Model.Class and instead of writing sql("version") I'd really like to somehow derrive it from Model.Class struct key. Same with entitiy name sql("todo").

3) Is something like this a correct way to extract fields to create a partial schema for SqlSchema Request:
export const updateTodoCompletion = SqlSchema.void({
    execute: (request) => {
          ...
    },
    Request: Schema.Struct(Todo.fields).pick("id", "owner", "isCompleted"),
});

Normally struct has pick method but it looks like Todo defined by model isn't really a struct, should I convert it like this or is there an easier way?

4) Is something like this a best way to know whether conditional update found something to update?

export const deleteTodo = SqlSchema.single({
    execute: (request) => {
        return Effect.gen(function* () {
            ...
            return yield* sql`SELECT changes() as ${sql("rowsAffected")}`;
        });
    },
    Request: Schema.Struct(Todo.fields).pick("id", "owner"),
    Result: Schema.Struct({
        rowsAffected: Schema.Number,
    }),
});


Thanks a lot in advance, awesome job with the library! Sorry if any question is dumb, I actually usually used really simple ORMs, my first experience with writing raw SQL 😄
Was this page helpful?