tediousjs / node-mssql

Microsoft SQL Server client for Node.js
https://tediousjs.github.io/node-mssql
MIT License
2.23k stars 466 forks source link

INSERT INTO query inserts two rows instead of one #1569

Closed Errichamonda closed 8 months ago

Errichamonda commented 11 months ago

I'm using this bit of code to insert into a table with two columns and no indexes or primary key (I can't modify the DB).

const pool = await sql.connect(config)
const result = await pool.request()
    .input('code', sql.NVarChar, dto.code)
    .input('description', sql.NVarChar, dto.desciption)
    .query('INSERT INTO Table (CODE, DESCRIPTION) VALUES (@code, @description)')

Expected behaviour:

I expect one row to be inserted into the table

Actual behaviour:

Two new rows are created, identical to each other. With no constraints about indexes or primary keys this doesn't throw an error.

Configuration:

server: ip,
user: user,
password: password,
database: name,
pool: {
  max: 10,
  min: 0,
  idleTimeoutMillis: 30000,
},
options: {
  port: port,
  encrypt: true,
  trustServerCertificate: true,
}

Software versions

dhensby commented 11 months ago

Without seeing more of your code, I can't really determine the problem because what you've provided will not insert 2 rows into the database.

Have you carried out any debugging, such as adding some log statements and seeing if they are also logged twice? What have you done to ascertain that the query is only being run once?

Errichamonda commented 11 months ago

I'm using NestJS and added some console.log before and after the query and they are logging just once for each. The database doesn't have any triggers or stored procedures.

This is the data I'm sending via POST { "code": "TEST3", "description": "This is a TEST" }

From this code

console.log('before');
    const pool = await sql.connect(user.mssql);
    const result = await pool
      .request()
      .input('codice', sql.NVarChar, createTipoContattoDto.code)
      .input('descrizione', sql.NVarChar, createTipoContattoDto.description)
      .on('row', (row) => console.log(row))
      .query(
        `INSERT INTO TA_CRM_TIPOCONTATTO(TA_COD, TA_DESCRI) VALUES (@codice, @descrizione)`,
      );

    console.log('after');
    console.log(result);

I get this console output.

before
after
{
  recordsets: [],
  recordset: undefined,
  output: {},
  rowsAffected: [ 1 ]
}

But in the database i found 2 identical rows.

dhensby commented 11 months ago

OK - that's interesting. Given that the DB is reporting that only 1 row has been affected, it doesn't appear that the query is adding 2 rows itself. Somehow it's either being run twice or there's something else causing a duplicate row to be added.

Are you able to replicate this in a completely vanilla DB / project to provide a minimal replication example?