NodeJs PG query not executed as expected - javascript

I have the following, AWS lambda code inserting into a table:
let queryString = "INSERT INTO orders(order_id, channel, channel_order_id, channel_order_code, channel_merchant, merchant, min_time, max_time, delivery_expected_time, status, observations, total, sub_total, voucher_discount, delivery_tax, fk_customer_id, fk_address_id, order_contact, order_type, payment_pending, payment_prepaid, channel_merchant_id, order_timming, picker, delivered_by, delivery_obs, takeout, takeout_date_time, takeout_obs, indoor, table)VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, $29, $30, $31) RETURNING *";
const newOrder = await client.query(queryString, [order_id, channel, channel_order_id, channel_order_code, channel_merchant, merchant, min_time, max_time, delivery_expected_time, status, observations, total, sub_total, voucher_discount, delivery_tax, fk_customer_id, fk_address_id, order_contact, order_type, payment_pending, payment_prepaid, channel_merchant_id, order_timming, picker, delivered_by, delivery_obs, takeout, takeout_date_time, takeout_obs, indoor, table], (err, res) => {
if(err)console.log(res, err)
});
And then another insert in a table that has a foreign key that references an order(order_id), which should be the one being created at the first insert
I'm getting an error, on the second insert, that says that the order(order_id) does not exist. So it means that the order is not being created, the first insert is not being executed, but nothing is being caught in the console.log(err)
Now the interesting part. If I remove the table column from the first insert everything goes as expected
If I console.log(table) I get null
And the column is NotNull = False, which means that it can be null, just like as other values I'm using on the insert
Any hint on what could be happening here? Is there a limit of how many columns I can have on an insert?

table is a keyword in Postgres.
If you're insisting on continuing to maintain a column in your schema with the name table (not advisable), you'll need to pass it in quotes when referencing it:
INSERT INTO orders ("table") /* ... */

Related

INSERT INTO table VALUES float string from postman input

I'm trying to create a new course row into my Courses database in postman and I cannot get the syntax correct.
I've got 159 values that need to be added into a single course. Any chance I can summarise them instead of having to write down all the values?
Currently this is my query:
const addCourse = "INSERT INTO courses VALUES (value1 'value2','value3', 'value4', 'value5', 'value6', 'value7', 'value8', 'value9', 'value10', 'value11', 'value12', 'value13', 'value14', 'value15', 'value16', 'value17', 'value18', 'value19', 'value20', 'value21', 'value22', 'value23', 'value24', 'value25', 'value26', 'value27', 'value28', 'value29', 'value30', 'value31', 'value32', 'value33', 'value34', 'value35', 'value36', 'value37', 'value38', 'value39', 'value40', 'value41', 'value42', 'value43', 'value44', 'value45', 'value46', 'value47', 'value48', 'value49', 'value50', 'value51', 'value52', 'value53', 'value54', 'value55', 'value56', 'value57', 'value58', 'value59', 'value60', 'value61', 'value62', 'value63', 'value64', 'value65', 'value66', 'value67', 'value68', 'value69', 'value70', 'value71', 'value72', 'value73', 'value74', 'value75', 'value76', 'value77', 'value78', 'value79', 'value80', 'value81', 'value82', 'value83', 'value84', 'value85', 'value86', 'value87', 'value88', 'value89', 'value90', 'value91', 'value92', 'value93', 'value94', 'value95', 'value96', 'value97', 'value98', 'value99', 'value100', 'value101', 'value102', 'value103', 'value104', 'value105', 'value106', 'value107', 'value108', 'value109', 'value110', 'value111', 'value112', 'value113', 'value114', 'value115', 'value116', 'value117', 'value118', 'value119', 'value120', 'value121', 'value122', 'value123', 'value124', 'value125', 'value126', 'value127', 'value128', 'value129', 'value130', 'value131', 'value132', 'value133', 'value134', 'value135', 'value136', 'value137', 'value138', 'value139', 'value140', 'value141', 'value142', 'value143', 'value144', 'value145', 'value146', 'value147', 'value148', 'value149', 'value150', 'value151', 'value152', 'value153', 'value154', 'value155', 'value156', 'value157 ', 'value158' )"
This is my courseController code:
const addCourse = (req, res) => {
console.log(req.body);
const { id_curso } = req.body;
//check Curso exists
pool.query(queries.checkIdCursoExists, [id_curso], (error, results) => {
if (results.rows.length) {
res.send("Este curso ja existe.");
}
// add course
pool.query(queries.addCourse),
(error, results) => {
if (error) throw error;
res.status(201).send("Curso criado com sucesso");
};
});
};
The problem I encounter is this error message whether I have value1 in quotes or not:
error: type "value1" does not exist'
The course is not posted onto my database.
The path to your answer lies in your INSERT statement. I guess your courses table has 159 columns in it. (That is a great many columns and may suggest the need to normalize your table. SQL handles multiple-row data more efficiently than multiple-column data where it makes sense to do so. But you did not ask about that.)
The INSERT syntax is either this:
INSERT INTO tbl (col1, col2, col3) VALUES (const, const, const);
or this:
INSERT INTO tbl VALUES (const, const, const);
The first syntax allows you to insert a row without giving values for every column in the table. You use the second syntax. It requires you to give one constant value for each column of your table. But your insert looks like this:
INSERT INTO courses VALUES (value1 'value2', ... , 'value158' )"
I see some problems with this.
You only have 158 values, but your question says you have 159.
value1, the first value in your list, isn't a constant.
You need a comma after your first value.
All your value constants are text strings. Yet you mentioned float in the title of your question.

not able to add values to mysql table from node

I want to insert data into my table, I'm able to do it in node.js when I just put strings in my values.
var sql = INSERT INTO teachers (full_name, school, email) VALUES ('alex','bennet','alex#bennet.com);
However, when I put the value created by POST method, it gives me a syntax error.
var sql = INSERT INTO teachers (full_name, school, email) VALUES (${teacher.name},${teacher.school},${teacher.email});
code: 'ER_BAD_FIELD_ERROR',
errno: 1054,
sqlMessage: "Unknown column 'alex' in 'field list'",
sqlState: '42S22',
index: 0,
sql: "INSERT INTO teachers (full_name, school, email) VALUES (alex,bennet,alex#bennet.com) "
I dont know why it assumes alex as a column name and not value.
The immediate problem is that you are intercalating raw unescaped strings into your insert query, which won't work, since string literals in MySQL need to be escaped by quotes. The best fix here is to use a prepared statement:
let stmt = `INSERT INTO teachers (full_name, school, email) VALUES (?, ?, ?)`;
let pals = ['alex', 'bennet', 'alex#bennet.com'];
connection.query(stmt, vals, (err, results, fields) => {
if (err) {
return console.error(err.message);
}
});
You have to enclose the string with single quotes to specify as string. So your code should be like this,
var sql = INSERT INTO teachers (full_name, school, email) VALUES ('${teacher.name}','${teacher.school}','${teacher.email}');
Hope it will solve your issue.

REST API Javascript How to write condition that checks if SQL query returns 0 rows

I have db airport, there is TABLE tourists and in it COLUMN: id and also i have TABLE: flights, and there is column: listoftouristsbyid which is array of integers. I need to check if i passed to REST API request integer that is id of Tourist that not EXISTS. Means there is no tourist with given id (id is primary, autoincrementing key). I wrote something like that:
app.post('/flights', function(req, res) {
pool.connect(function(err,client,done) {
if(err) {
return console.log("Error fetching clients", err);
}
client.query("SELECT tourists.id FROM tourists WHERE tourists.id = " + req.body.listoftouristsbyid[i], function (err, result) {
done();
if (result.rows === 0) {
return console.log("Tourist "+req.body.listoftouristsbyid[i]+" you want to add does not exist" + err);
}
})
client.query('INSERT INTO flights(departuredate, arrivaldate, numberofseats, listoftouristsbyid, ticketprice) VALUES($1, $2, $3, $4, $5)',
[req.body.departuredate, req.body.arrivaldate, req.body.numberofseats, req.body.listoftouristsbyid, req.body.ticketprice]);
done();
res.redirect('/flights');
})
})
I know ITS A VALID QUERY, because when i type it in PSQL shell it returns
airport=#
SELECT tourists.id FROM tourists WHERE tourists.id = 15;
id
----
(0 rows)
But its not working as javascript code - means code should terminate with error, but condition is not fulfiled. How do i write condition in Javascript that catches when SELECT tourists.id FROM tourists WHERE tourists.id = 15 gives 0 rows?
In MySQL, When you perform a read operation, It will give you value in Array. So, get the length of the result array by result.length
check if it is equal to zero.
When you perform a write or update operation, the result will contain a property affectedRows Which will tell you the number of rows affected.
Print the result using console.sql('%j', result) and See if there is some option in PostGreSQL(Most probably there is).

column violate foreign key constraints

I'm trying to create a relationship between two tables, however i seem to get, some issues when i try to insert my object to postgres database. i keep getting following error: insert or update on table "tournament" violates foreign key constraint "tournament_league_id_foreign". which i guess is related to my knex syntax?
Insert into db
var data = {
id: id,
name: name,
league_id: leagueId
};
var query = knex('tournament').insert(data).toString();
query += ' on conflict (id) do update set ' + knex.raw('name = ?, updated_at = now()',[name]);
knex.raw(query).catch(function(error) {
log.error(error);
})
Knex tables
knex.schema.createTable('league', function(table) {
table.increments('id').primary();
table.string('slug').unique();
table.string('name');
table.timestamp('created_at').notNullable().defaultTo(knex.raw('now()'));
table.timestamp('updated_at').notNullable().defaultTo(knex.raw('now()'));
}),
knex.schema.createTable('tournament', function(table) {
table.string('id').primary();
table.integer('league_id').unsigned().references('id').inTable('league');
table.string('name');
table.boolean('resolved');
table.timestamp('created_at').notNullable().defaultTo(knex.raw('now()'));
table.timestamp('updated_at').notNullable().defaultTo(knex.raw('now()'));
})
When you created the tournament table, for the column league_id you you specified that .references('id').inTable('league'). This means that for every row in that table, there must exist a row in the table league whose id is the same as the value of the league_id field in the former row. Apparently in your insert (is this your only insert?) you are adding a row to tournament whose league_id does not exist in league. As a rule, the foreign constraint (i.e. the .references part) implies that you must create the league first and then tournaments in that league (which actually makes sense).

node-mssql Transaction insert - Returning the inserted id..?

I'm using node-mssql 3.2.0 and I need to INSERT INTO a table and return the id of the inserted record.
I can successfully use sql.Transaction() to insert data, but the only parameters given to callbacks (request.query() and transaction.commit()) are:
const request = new sql.Request();
request.query('...', (err, recordset, affected) => {});
const transaction = new sql.Transaction();
transaction.commit((err) => {});
So recordset is undefined for INSERT, UPDATE and DELETE statements, and affected is the number of rows affected, in my case 1.
Does anyone know a good way to obtain an inserted records id (just a primary key id) after a transaction.commit() using node-mssql..?
Instead of just doing an INSERT INTO... statement, you can add a SELECT... statement as well:
INSERT INTO table (...) VALUES (...); SELECT SCOPE_IDENTITY() AS id;
The SCOPE_IDENTITY() function returns the inserted identity column, which means recordset now contains the id:
const request = new sql.Request();
request.query('...', (err, recordset, affected) => {});
I don't think request.multiple = true; is required, because although this includes multiple statements, only one of them is a SELECT... and so returns.
So the answer was SQL related and is not specific to node-mssql.
I know this question has accepted answer.
I made the following way:
let pool = await sql.connect(config);
let insertItem = await pool.request()
.input('ItemId',sql.NVarChar, 'itemId1234')
.input('ItemDesc',sql.NVarChar, 'nice item')
.query("insert into itemTable (Id, ItemId,ItemDesc) OUTPUT INSERTED.ID
values (NEWID(), #ItemId, #ItemDesc);
var insertedItemId = insertItem.recordset[0].ID
This adds unique identifier to data that is saved to db (if table is created so)
create table itemTable(
Id UNIQUEIDENTIFIER primary key default NEWID(),
ItemId nvarchar(25),
ItemDesc nvarchar(25)
)

Categories

Resources