Skip to content

CRUD ​

Kosame provides its own CRUD operations.

How to Write CRUD Operations ​

Syntax Common to add() and find() ​

To use it, first access context, then specify the name of the table you want to work with (in this case, users), and finally enter the method you want to call.

add() ​

The add() method is used to insert values into the database. Pass the column values as an object to the add() method. The add() method returns a Model instance that includes the values generated by the database.

ts
const user = await context.users.add({ name: "kosame" });

find() ​

The find() method retrieves a value from the database. Pass only the primary key value as an argument to find(). The find() method returns a Model instance if a match is found, and undefined if no match is found.

ts
const found = await context.users.find(user.id);

update() ​

The update() method is used to update the database. Just like with add(), you pass the column values as an object to the update() method. update() does not return a value; instead, the calling instance itself is updated with the new values.

Differences from add() ​

In terms of their roles, update() handles updates, while add() handles additions, but their syntax is quite similar. Unlike add(), update() performs the operation directly rather than through the context.

ts
await user.update({ name: "ooame" });

save() ​

The save() method saves data to the database. save() takes no arguments; instead, if you modify the instance's properties directly before calling it, the current values are written to the database as-is.

ts
user.name = "gouu";
await user.save();

reload() ​

The reload() method retrieves the latest values from the database. reload() does not return a value; instead, the calling instance itself is updated with the latest values. Unlike find(), which returns undefined if no matching row is found, reload() throws an exception.

ts
await user.reload();

delete() ​

The delete() method removes an instance from the database. The behavior of delete() changes when you use a mixin called SoftDeletable. Normally, delete() actually deletes the instance from the database, but when SoftDeletable is applied, it performs a soft delete (simply setting a date and time in the deletedAt field). If you want to perform a hard delete, you use the hardDelete() method, which becomes available in this case.

ts
await user.delete();