node js sql output - javascript

I am trying to come up with the node.js code to get the output of this query:
const viewAllEmployees = () => {
let sql = 'SELECT e.id, e.first_name, e.Last_name, r.title, d.name as "Department", salary, CONCAT (m.first_name," ", m.last_name) AS "Manager"
FROM employee e ' + connection.escape('INNER JOIN employee m
ON e.manager_id = m.id
LEFT JOIN role r
ON e.role_id = r.id
LEFT JOIN department d
on r.department_id = d.id');
connection.query(sql, (err, res) => {
if (err) throw err;
console.table(res);
// console.log(res);
//connection.end();
});
The problem is that when I use it without the connection.escape(), I get the output, but with single quotes like this:
How can I (1) get rid of the (index) column, and (2) get rid of the single quotes?
Getting rid of the single quotes is really the priority.
Thanks!

Index column and quotes are added by console.table function itself.
You can check it running console.table with any static data like here:
https://developer.mozilla.org/en-US/docs/Web/API/Console/table#collections_of_primitive_types
To print it in a way you want it, implement printing function on your own.

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.

node: managing SQL files with variable replacement

I have large SQL statements that I would like to store as separate files (with syntax highlighting etc). I like the accepted solution proposed here.
In my use case, I write SQL in Javascript Template Literal syntax for variable replacement. So my file looks like
-- some_file.sql
select col1, col2, col3
from my_table
where col1 = '${val1}'
and col2 between ${val2} and ${val3}
In fact this way of writing queries started from using template literals initially before the queries grew and demanded their own file.
The question is how to achieve template literals like evaluation for a query string read using fs.readFileSync without having to do the dreaded eval? I looked into es6-template-render, however that implementation is not suited for variables in the execution context; i.e. not specifying a separate context parameter, but implicitly using the variables (global/local) available in the environment during runtime.
Any pointers?
Apologies if my assumption is incorrect, but the quotes around '${val1}' suggest you're planning to use string substitution rather than parameterized queries. Don't do that. :-) Never use string substitution to put values into SQL queries. Let me introduce you to my friend Bobby:
Use parameterized queries instead.
For instance, you might use a format very much like you have, just without any quotes around ${val1}:
select col1, col2, col3
from my_table
where col1 = ${val1}
and col2 between ${val2} and ${val3}
Then your code could convert that into a query appropriate to your DB API. Many of them use ? placeholders, so for instance (here I'm using node-mysql2 as the DB API, but the specific API isn't the point):
const rexParam = /(?<!\$)\$\{([^}]+)\}/g;
function doQuery(sql, params) {
return new Promise((resolve, reject) => {
const values = [];
const preppedSql = sql.replace(rexParam, (_, paramName) => {
const value = params[paramName];
if (value === undefined) { // Or do an `in` check if you want to allow `undefined`
throw new Error(`Missing parameter ${paramName}`);
}
values.push(value);
return "?";
});
return connection.execute(
preppedSql,
values,
function(err, results, fields) {
if (err) {
reject(err);
} else {
resolve({results, fields});
}
}
);
});
}
That spins through the string, replacing the ${val1} and such tokens with ? and at the same time filling in an array of values to pass to the parameterized query function.
(Note the negative lookbehind so that $${...} isn't expanded, just like in template literals. The regex is a bit primitive, but should suffice for SQL I'd think...)
Live example just dumping out the string and values:
const sql =
"select col1, col2, col3\n" +
"from my_table\n" +
"where col1 = ${val1}\n" +
"and col2 between ${val2} and ${val3}";
const rexParam = /(?<!\$)\$\{([^}]+)\}/g;
function doQuery(sql, params) {
const values = [];
const preppedSql = sql.replace(rexParam, (_, paramName) => {
const value = params[paramName];
if (value === undefined) { // Or do an `in` check if you want to allow `undefined`
throw new Error(`Missing parameter '${paramName}'`);
}
values.push(value);
return "?";
});
console.log(preppedSql);
console.log(values);
}
doQuery(sql, {val1: "one", val2: 2, val3: 20});

How to find "By Name" in mongoose

I am trying to get database values using a specific name. I want to get all the books an author written.
This is my code to get the first name of the author and search for all the books he's written in BookDB using Like operator as in mysql
//get books by author name
router.route('/authorName').get((req, res) => {
let authorName = req.params.authorName; //how can i pass this value to below regex command
BookDB.find({"firstName": /authorName/}, (err, books) => {
if(err) throw err;
res.status(200).send(books);
});
});
Problem: How can I pass authorName to the {"firstName": /authorName/}.
The way I have written, it is not set the authorName properly.
I am not sure in the mongoose part, but you can also create regular expressions as:
new RegExp(exp: string, flags: string)
Note if you use this format, the start and end slash has no special meaning, they would mean the string starts with a slash
I did some research and found $regex.
//get books by author name
router.route('/authorName').get((req, res) => {
let authorName = req.params.authorName;
BookDB.find({firstName: {$regex: `${authorName}`}}, (err, books) => {
if(err) throw err;
res.status(200).send(books);
});
});
This will find all the results that containing this particular string authorName in BookDB database

Nodejs Subselect in sql select

Ola!
I'm doing a node.js application. I have this table structure in my MySql DB:
My task is to get the table_4 names and the related table_7 names. I know the Table_1 username and password. Is it possible to create one query - using subselect - not calling all the time callback with a new select after getting values? - like below -
con.connect(function(err) {
if (err)
{throw err }
con.query("SELECT id FROM Table_1 WHERE username = xyz AND password = aaa",
function (err, result) {
if (err) {throw err};
con.query("SELECT table_3_id FROM table2 WHERE Table_1_id = "+(result)+")",
function(/*bla-bla*/){
};
});
}
);
Thanks!
Here it is how you can achieve that with one query :
SELECT Table_4.*
FROM Table_1 , Table_2 , Table_3 , Table_4
WHERE Table_1.username and Table_1.password and
Table_2.Table_1_id = Table_1.id and
Table_2.Table_3_id = Table_3.id and
Table_3.Table_4_id = Table_4.id
I couldn't found proper relations for Table_7 names. But I think you will get idea how to do it further from this.
I just talked to my lead dev, hwho gave me a correct solution - similar to #Vivek Doshi answer - :
SELECT Table_4.names, Table_7.names
FROM Table_1 , Table_2 , Table_3 , Table_4, Table_5, Table_6, Table_7
WHERE Table_1.username and Table_1.password and
Table_2.Table_1_id = Table_1.id and
Table_2.Table_3_id = Table_3.id and
Table_3.Table_4_id = table_4.id and
Table_3.table_5_id = table_5.id and
table_6.table_5_id = Table_5.id and
table_6.table_7_id = table_7.id;

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