CRUD Operations (Create, Read, Update, Delete): examples

Advanced work with CRUD operations

In this section, we will look at examples of CRUD (Create, Read, Update, Delete) operations on the tasks table using my ORM system. Here are examples of requests to create, retrieve, update, and delete records.

Create a new record

To add a new task to the tasks table, use the following query:

const insertQueryExample = await databaseManager.queryBuilder()
    .insert({
        task_id: 1,
        title: 'Новий таск',
        description: 'Опис нового таску',
        is_completed: false,
        due_date: '2024-12-31',
        price: 100.50
    }, 'tasks')
    .execute();

A selection of records

To select records from the tasks table according to certain criteria, for example, all tasks that are not completed and have a certain price, use the following query:

const selectQueryExample = await databaseManager.queryBuilder<Tasks[]>()
    .select(['task_id', 'title', 'status'])
    .from('tasks')
    .where({
        conditions: {
            is_completed: { eq: false },
            price: { gt: 50 }
        },
        logicalOperator: 'and'
    })
    .orderBy('due_date', 'ASC')
    .execute();

Updating records

To update entries in the tasks table, such as changing the completion status for all tasks with a specific task_id, use the following query:

const updateQueryExample = await databaseManager.queryBuilder()
        .update({ is_completed: true }, 'tasks')
        .whereconst updateQueryTask = await databaseManager.queryBuilder()
    .update({ is_completed: true }, 'tasks')
    .where({ conditions: { task_id: { eq: 1 } }, logicalOperator: 'and' })
    .execute();

Deleting records

To delete records from the tasks table, for example, to delete all tasks with a certain title, use the following query:

const deleteQueryExample = await databaseManager.queryBuilder()
    .delete('tasks')
    .where({ conditions: { title: { eq: 'Завдання 2' } }})
    .execute();

It should be noted that deleteQueryExample, updateQueryExample and insertQueryExample return an empty array if successful

These examples demonstrate how you can use your ORM system to perform various CRUD operations on the tasks table, given PostgreSQL-specific options.

Last updated