Skip to content

2) The insert method

Ana Paula Oliveira de Lima edited this page Nov 10, 2021 · 1 revision

Insert

The insert method must be called to insert new data into the database. It receives as a parameter an object containing the data to be inserted and always return an object with the following fields: data, error and success. The method is asynchronous and its use must be done using async await or promises.

Insert parameters

The insert method receives as a parameter an object with the following keys:

  • beginTransaction: boolean, if true, the transaction will be performed using begin transaction, if false, the transaction will not use begin transaction;
  • table: string with the value of the name of the table in which the insertion will be made;
  • columns: object. Each key of this object must be the name of a column, and the value of this key must be the value to be inserted in the table;
  • returning(optional): array containing the name of the columns that you want to be returned after the insert. If returning is not specified, nothing will be returned.

Structure

See a generic example of this structure:

{
    beginTransaction: true || false,
    table: "table_name",
    columns: {
        columnName: “value” || 1,
    },
    returning: ["*"],
}

Practical example

Below is an example of using the insert method:

const insert = {
        beginTransaction: true,
        table: "users",
        columns: {
            name: “Maria Flor”,
	age: 20,
        },
        returning: ["*"],
    };

// async await
const insertResult = await query.insert(insert);

// promise
query.insert(insert)
    .then( (result) => console.log(result.data))
    .catch( (error) => console.log(error));

Insert return

If everything occurs well during the insertion, data will have an array with all the values specified on the returning, if no value was specified, data will have an empty array. If something goes wrong, error will be responsible for storing the error messages of the erros found. The error field stores errors that happened during the transaction, commit and rollback errors in the case of an insert using begin transaction, and erros in passing parameters. Success stores only booleans for commit and rollback. See below the return of the insert mede earlier:

{
  error: { 
    transaction: false,
    commit: false,
    rollback: false
    params: false
  },
  success: {
    commit: true,
    rollback: false
   },
  data: [
    {
      id: 131,
      name: 'Maria Flor’,
      age: 20
    }
  ]
}

It is verified that there was no error and the commit was successful.

Clone this wiki locally