K
K
kr_ilya2020-06-23 15:13:27
PostgreSQL
kr_ilya, 2020-06-23 15:13:27

How to convert several queries to the database into 1?

There is a function to add a user to the database

Actions.addTgUser = async (data) => {
  var exist = await Actions.checkTgUserExist(data.chat.id);
  if(!exist){
    pg.Query('INSERT INTO tg_users (username, is_bot, language_code, first_name, date_start, chat_id) VALUES ($1, $2, $3, $4, $5, $6)', [data.from.username, data.from.is_bot, data.from.language_code, data.from.first_name, data.date, data.chat.id]);
    pg.Query('INSERT INTO tg_users_settings (chat_id, bot_lang) VALUES ($1, $2)', [data.chat.id, data.from.language_code]);
    pg.Query('INSERT INTO tg_users_stats (chat_id, last_active) VALUES ($1, $2)', [data.chat.id, data.date]);
  }else{
    Actions.updateTgUser(data);
    Actions.updateTgUserLastActive(data);
  }
  return true;
};


I think it would be better for performance if instead of three INSERT queries to make one general one? Or am I wrong?

Here only as it is all to write down one request?

Here is the query function
const Pool = require('pg').Pool
const pool = new Pool({
  user: config.base.user,
  host: config.base.host,
  database: config.base.database,
  password: config.base.password,
  port: config.base.port,
});

  Query: function (sql, values, singleItem) {
      return new Promise((resolve, reject) => {
              try {
                  pool.query(sql, values, function (err, result) {
                      if (err) {
                          reject(err);
                      } else {
                      	// console.log('Результат: ', result)
                          resolve(singleItem ? result.rows[0] : result);
                      }
                  });
              }
              catch (e) {
                  reject(e);
              }
      });
  },

Answer the question

In order to leave comments, you need to log in

1 answer(s)
_
_, 2020-06-23
@kr_ilya

You are inserting into different tables, and you cannot do them in one query.
But you can wrap it all up in a transaction to ensure data consistency.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question