Skip to content

Insert Builder

The insert builder allows you to create INSERT queries, to insert new data in your database.

.insert(map: objectOrPointer, ...othersPropertyNames: pointer[])

The insert builder factory can be used with either an object or a list of property strings. You use it with a list of strings to define the columns of you insert query. You'll need therefore to supply some values later with values method

sh
    .insert('id', 'first_name', 'last_name')
    .into('users')
    .values({id:42, first_name:'Laurent', last_name:'Renard'})
    .build();

// > { text: 'INSERT INTO "users" ( "id", "first_name", "last_name" ) VALUES
//            ( 42, 'Laurent', 'Renard' )',
//   values: [] }

The version with an object map is simply equivalent to a call with a list of strings whose values are the keys of the object and then a call to values with the object values as query values. It will likely be more convenient if you wish to insert a single row.

sh
    .insert({id: 42, first_name: 'Laurent', last_name: 'Renard'})
    .into('users')
    .build();

// is equivalent to

sh
    .insert('id', 'first_name', 'last_name')
    .into('users')
    .values({id: 42, first_name: 'Laurent', last_name: 'Renard'})
    .build();

// > { text: 'INSERT INTO "users" ( "id", "first_name", "last_name" )
//            VALUES ( 42, 'Laurent', 'Renard' )',
//      values: [] }

.into(tableName: string)

Specify the table you wish to insert rows into.

.values(rows:T | T[])

You have already seen the version where you pass a an object as argument, but you can also pass an array of objects if you wish to perform a bulk insert.

sh
    .insert('id', 'first_name', 'last_name')
    .values([
        {first_name: 'Laurent', last_name: 'Renard'},
        {first_name: 'Charlie', last_name: 'Renard'}
    ])
    .into('users')
    .build();

// > { text:
//    `INSERT INTO "users" ( "id", "first_name", "last_name" ) VALUES
//      ( DEFAULT, 'Laurent', 'Renard' ),
//      ( DEFAULT, 'Charlie', 'Renard' )`,
//   values: [] }

If the object you pass misses some key/value pairs defined in the insert factory the DEFAULT keyword will be used instead.

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

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

sh.insert('id', 'first_name', 'last_name')
    .values([
        {first_name: 'Laurent', last_name: 'Renard'},
        {first_name: 'Charlie', last_name: 'Renard'}
    ])
    .into('users')
    .returning('id','first_name')
    .build();

//> { text:
//    `INSERT INTO "users" ( "id", "first_name", "last_name" ) VALUES
//          ( DEFAULT, 'Laurent', 'Renard' ),
//          ( DEFAULT, 'Charlie', 'Renard' )
//     RETURNING "id", "first_name"`,
//    values: [] }

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