Skip to content

Update Builder

The update builder allows you to create UPDATE queries, to update a set of rows in your database.

.update(tableName: pointer)

The update builder takes the name of the table to update as argument, eventually with an alias.

.set(map: objectOrString, value: any)

The set method allows you to specify the column(s) to update and their(its) new value(s). If you use the version with two arguments, the first one will be a string pointer to the column to update and the second one the new value. You can call multiple times the set method if you have various columns to update

If you use the version with one argument (the map object), it will be equivalent to call the first version of the method with each key/value pair

sh
    .update('posts')
    .set('title', 'foo')
    .set('published_at', new Date(2000))
    .build();

// will be equivalent to

sh
    .update('posts')
    .set({title: 'foo', published_at: new Date(2000)})
    .build();

// > { text: `UPDATE "posts" SET "title" = 'foo', "published_at" = '1970-01-01T00:00:02.000Z'`,
//     values: [] }

Of course, both version support parameterized queries.

.from(...pointers[])

The from method allows you to use others table columns in the where clause or in the new set value.

sh
    .update('posts')
    .set('title', `"posts"."title" || ' by ' || "users"."first_name"`)
    .from('users')
    .where('posts.user_id', '"users"."user_id"')
    .and('posts.post_id', 2)
    .build();

//{ text:
//    `UPDATE "posts" SET "title" = "posts"."title" || ' by ' || "users"."first_name"
//     FROM "users" WHERE "posts"."user_id" = "users"."user_id" AND "posts"."post_id" = 2`,
//   values: [] }

.where(leftOperand, ?operator, ?rightOperand)

This method returns a proxy of a condition builder which will be revoked whenever you call a method which does not belong to the condition builder. See conditions builder for more details. You use it to create where clause in your update query

sh
    .update('posts')
    .set('title', `"posts"."title" || ' (old)'`)
    .where('posts.user_id', 42)
    .and('published_at', '<', new Date(2015))
    .build();

// >  { text:
//    `UPDATE "posts" SET "title" = "posts"."title" || ' (old)' WHERE
//     "posts"."user_id" = 42 AND "published_at" < '1970-01-01T00:00:02.015Z'`,
//   values: [] }

.returning(...properties: pointers[])

Specify a returning close to your update query. It is useful if you want to get back the freshly updated rows

sh
    .update('posts')
    .set('title', 'new title')
    .where('posts.user_id', 42)
    .returning('*')
    .build();

// > { text:
//    `UPDATE "posts" SET "title" = 'new title' WHERE "posts"."user_id" = 42 RETURNING *`,
//   values: [] }

You can use the '*' character if you wish to return all the columns the updated rows.