Skip to content
Christoph Herrmann edited this page May 13, 2019 · 14 revisions

Single row (rows is an object)

The return value is the SERIAL generated by inserting the new row located in result.rows[0][serialColumn = 'id'] of the pg result object.

const id = await sql.insert(
  'users',
  { email: 'email', name: 'name' }
)

// text: INSERT INTO "users" ("email", "name") VALUES ($1, $2) RETURNING "id"
// parameters: ['email', 'name']

Multiple rows (rows is an array of objects)

The return value is an array of the SERIALs generated by inserting the new row located in result.rows[][serialColumn = 'id'] of the pg result object.

const ids = await sql.insert(
  'users',
  [
    { email: 'emailA', name: 'nameA' },
    { email: 'emailB', name: 'nameB' },
    { email: 'emailC', name: 'nameC' }
  ]
)

// text: INSERT INTO "users" ("email", "name") 
//   VALUES ($1, $2), ($3, $4), ($5, $6) RETURNING "id"
// parameters: ['emailA', 'nameA', 'emailB', 'nameB', 'emailC', 'nameC']

The return value is also an array if the given rows array contains only one object. It only depends on the datatype of rows.

Only insert specific keys

const ids = await sql.insert(
  'users',
  [
    { email: 'emailA', name: 'nameA', active: true },
    { email: 'emailB', name: 'nameB', active: true },
    { email: 'emailC', name: 'nameC', active: true }
  ],
  { keys: ['email', 'name'] }
)

// text: INSERT INTO "users" ("email", "name") 
//   VALUES ($1, $2), ($3, $4), ($5, $6) RETURNING "id"
// parameters: ['emailA', 'nameA', 'emailB', 'nameB', 'emailC', 'nameC']

Returning another serial column

const example = await sql.insert(
  'users',
  { email: 'email', name: 'name' },
  { serialColumn: 'example' }
)

// text: INSERT INTO "users" ("email", "name") VALUES ($1, $2) RETURNING "example"
// parameters: ['email', 'name']

The default serialColumn id can be changed by setting sql.defaultSerialColumn.

Clone this wiki locally