select query postgreqs fails on nodejs - node.js

i am super new to postgres and trying to do a simple select query.
my table looks like:
create table push_table
(
seq_id int,
device_id text,
primary key (seq_id),
user_id varchar(100)
);
and my nodejs code as follows:
pool.connect(function (err, client, done)
{
if (err) console.log(err)
myClient = client
//query if the user exists
var ageQuery = format('SELECT * from push_table WHERE user_id = ' + userId);
myClient.query(ageQuery, function (err, result) {
if (err) {
console.log(err)
}
console.log("number of rows:" + result.rows.length);
});
});
on running nodejs server log prints:
{ [error: missing FROM-clause entry for table "catherine"]
name: 'error',
length: 113,
severity: 'ERROR',
code: '42P01',
detail: undefined,
hint: undefined,
position: '42',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'parse_relation.c',
line: '3129',
routine: 'errorMissingRTE' }
/data/OSC_Push_OOW/releases/20170703215021/api/controllers/pushcontroller.js:58
console.log("number of rows:" + result.rows.length);
^
TypeError: Cannot read property 'rows' of undefined
at null.callback (/data/OSC_Push_OOW/releases/20170703215021/api/controllers/pushcontroller.js:58:46)
at Query.handleError (/data/OSC_Push_OOW/shared/node_modules/pg/lib/query.js:161:17)
at null.<anonymous> (/data/OSC_Push_OOW/shared/node_modules/pg/lib/client.js:188:26)
at emitOne (events.js:77:13)
at emit (events.js:169:7)
at Socket.<anonymous> (/data/OSC_Push_OOW/shared/node_modules/pg/lib/connection.js:133:12)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at readableAddChunk (_stream_readable.js:153:18)
at Socket.Readable.push (_stream_readable.js:111:10)

The column user_id is varchar:
user_id varchar(100)
so a valid SQL query must use single quotes to define the varchar value, e.g.:
SELECT * from push_table WHERE user_id = 'Vik'
Your code does not provide the quotes needed.

Related

Insert data into postgreSQL using nodejs typescript

My code looks like this
signup.post('/signup', urlendcodedParser, async(req: Request, res: Response) => {
const username = req.body.username;
const password = req.body.password;
const age = req.body.age;
const email = req.body.email;
const fullname = req.body.fullname;
console.log(req.body)
await pool.query("INSERT INTO (username, userpassword, email, fullname, age) VALUES ($1, $2, $3, $4, $5) RETURNING *", [username, password ,email, fullname, age]).catch(err => console.log(err))
await res.json("Akaunt napravljen")
})
But when I try to submit a POST request I get this error:
error: syntax error at or near "("
at Parser.parseErrorMessage (C:\Users\prcap\Desktop\liveno-t\server\node_modules\pg-protocol\src\parser.ts:369:69)
at Parser.handlePacket (C:\Users\prcap\Desktop\liveno-t\server\node_modules\pg-protocol\src\parser.ts:188:21)
at Parser.parse (C:\Users\prcap\Desktop\liveno-t\server\node_modules\pg-protocol\src\parser.ts:103:30)
at Socket. (C:\Users\prcap\Desktop\liveno-t\server\node_modules\pg-protocol\src\index.ts:7:48)
at Socket.emit (events.js:375:28)
at Socket.emit (domain.js:470:12)
at addChunk (internal/streams/readable.js:290:12)
at readableAddChunk (internal/streams/readable.js:265:9)
at Socket.Readable.push (internal/streams/readable.js:204:10)
at TCP.onStreamRead (internal/stream_base_commons.js:188:23) {
length: 90,
severity: 'ERROR',
code: '42601',
detail: undefined,
hint: undefined,
position: '13',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'scan.l',
line: '1180',
routine: 'scanner_yyerror'
}
How can I fix this?
You're missing the table name.
INSERT INTO table_name (username, userpassword, email)...

Delete request nodejs typescript

My code looks like this:
app.delete("/delete/:id", urlencodedParser, (req: Request, res: Response) => {
const id: any = req.params
console.log(req.params)
pool.query(`DELETE FROM allusers WHERE userid = $1`, [id]).catch(err => {
console.log(err)
})
})
But when I test it whit postman and go on e.g localhost:5000/delete/1 it logs:
error: syntax error at or near "["
at Parser.parseErrorMessage (C:\Users\prcap\Desktop\ucim\server\node_modules\pg-protocol\src\parser.ts:369:69)
at Parser.handlePacket (C:\Users\prcap\Desktop\ucim\server\node_modules\pg-protocol\src\parser.ts:188:21)
at Parser.parse (C:\Users\prcap\Desktop\ucim\server\node_modules\pg-protocol\src\parser.ts:103:30)
at Socket. (C:\Users\prcap\Desktop\ucim\server\node_modules\pg-protocol\src\index.ts:7:48)
at Socket.emit (events.js:375:28)
at Socket.emit (domain.js:470:12)
at addChunk (internal/streams/readable.js:290:12)
at readableAddChunk (internal/streams/readable.js:265:9)
at Socket.Readable.push (internal/streams/readable.js:204:10)
at TCP.onStreamRead (internal/stream_base_commons.js:188:23) {
length: 90,
severity: 'ERROR',
code: '42601',
detail: undefined,
hint: undefined,
position: '37',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'scan.l',
line: '1180',
routine: 'scanner_yyerror'
}
How can I fix this?

Select * from table with NodeJS // ERROR: { error: relation "mytable" does not exist

I get the following error during my SELECT query from PostgreSQL DB
ERROR: { error: relation "free_subnets" does not exist
at Connection.parseE (/home/ec2-user/environment/node_modules/pg/lib/connection.js:604:11)
at Connection.parseMessage (/home/ec2-user/environment/node_modules/pg/lib/connection.js:401:19)
at Socket.<anonymous> (/home/ec2-user/environment/node_modules/pg/lib/connection.js:121:22)
at Socket.emit (events.js:198:13)
at addChunk (_stream_readable.js:288:12)
at readableAddChunk (_stream_readable.js:269:11)
at Socket.Readable.push (_stream_readable.js:224:10)
at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
name: 'error',
length: 103,
severity: 'ERROR',
code: '42P01',
detail: undefined,
hint: undefined,
position: '15',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'parse_relation.c',
line: '874',
routine: 'parserOpenTable' }
If I use psql command and do a select there, it works.
\dt provides me the relation:
Schema | Name | Type | Owner
-------------+--------------+-------+----------
subnet_calc | free_subnets | table | postgres
Search_path has been set to: subnet_calc, public
I've created the table with user postgres, so I am the owner of the schema subnet_calc and the table free_subnets.
My dummy nodejs code is the following:
const pg = require('pg');
const cs = 'postgres://postgres:password#anydb.rds.amazonaws.com:5432/subnet_calculator';
const client = new pg.Client(cs);
client.connect();
client.query('SELECT * FROM subnet_calc.free_subnets', function(result) {
console.log(result);
});
What could be the issue?
Thanks for your help in advance!
I could resolve the issue. It was my failure, the tables were created in DB postgres not in subnet_calculator.
I will close this question.
you need to set search path for it like this:
db.query("SET search_path TO 'subnet_calc';")
and then do the query :
const query = `SELECT * FROM free_subnets`
db.query(query)

Node.js and PostgresSQL with Express

I've written a code to fetch the data from postgres database using express and NODE.js. the database is connected with the backend code but still it is showing error like relation does not exit.
Please check the code and error that I got:
var express = require('express');
var pg = require("pg");
var app = express();
var connectionString = "postgres://postgres:postgres#localhost:5432/testDatabase?currentSchema=testSchema";
app.get('/', function(req, res, next) {
pg.connect(connectionString, function(err, client, done) {
if (err) {
console.log("Not able to get Connection " + err);
res.status(400).send(err);
} else {
console.log("Connected.!");
}
const
query = {
// give the query a unique name
name : 'fetch-user-details',
text : 'SELECT * FROM loginTable',
}
client.query(query, function(err, result) {
done(); // closing the connection;
if (err) {
console.log(err);
res.status(400).send(err);
}
res.status(200).send(result.rows);
});
});
});
app.listen(4000, function() {
console.log('Server is running.. on Port 4000');
});
and the error response that I got is like:
Server is running.. on Port 4000
Connected.!
{ error: relation "logintable" does not exist
at Connection.parseE (C:\Users\sumit_srivastava\Desktop\Java_WorkSpace\SimpleNodeAppln\node_modules\pg\lib\connection.js:554:11)
at Connection.parseMessage (C:\Users\sumit_srivastava\Desktop\Java_WorkSpace\SimpleNodeAppln\node_modules\pg\lib\connection.js:381:17)
at Socket.<anonymous> (C:\Users\sumit_srivastava\Desktop\Java_WorkSpace\SimpleNodeAppln\node_modules\pg\lib\connection.js:117:22)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
at Socket.Readable.push (_stream_readable.js:208:10)
at TCP.onread (net.js:594:20)
name: 'error',
length: 120,
severity: 'ERROR',
code: '42P01',
detail: undefined,
hint: undefined,
position: '15',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'src\\backend\\parser\\parse_relation.c',
line: '986',
routine: 'parserOpenTable' }
just run this db dump at my Postgres
CREATE SCHEMA "testSchema";
ALTER SCHEMA "testSchema" OWNER TO postgres;
SET search_path = "testSchema", pg_catalog;
SET default_tablespace = '';
SET default_with_oids = false;
CREATE TABLE "loginTable" ( "ID" numeric NOT NULL, "Name" text );
ALTER TABLE "loginTable" OWNER TO postgres;
this was the problem
change your query to this
query = {
// give the query a unique name
name : 'fetch-user-details',
text : `SELECT * FROM "testSchema".logintable`,
}
you should mention the schema name
tasted on
Ubuntu
postgres 10.6
pg: 6.4.2
node v10.14.1

Error: column "undefined" does not exist

Hy everyone
I'm a new developer ReactJS. I tried to set up Firebase into my backend and I've a problem with my frontend. If I'm running my API using a postman, my API work and send a message from my backend but if I running my code from frontend I got error like this Column in the table is users and is not undefined
{ error: column "undefined" does not exist
at Connection.parseE (C:\fordg\node_modules\pg\lib\connection.js:567:11)
at Connection.parseMessage (C:\fordg\node_modules\pg\lib\connection.js:391:17)
at Socket.<anonymous> (C:\fordg\node_modules\pg\lib\connection.js:129:22)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at Socket.Readable.push (_stream_readable.js:134:10)
at TCP.onread (net.js:547:20)
name: 'error',
length: 109,
severity: 'ERROR',
code: '42703',
detail: undefined,
hint: undefined,
position: '55',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'parse_relation.c',
line: '3183',
routine: 'errorMissingColumn' }
and this is my backend code
Orders.patch([ Object.assign({id: req.params.id}, req.body) ])
.then(orders => {
DB.query("SELECT oauth FROM users WHERE id = "+req.body.driver+" OR id = "+req.body.customer+"").then(res=>{
res.map((row,i)=>{
let tmp = {
token: row.oauth.token
}
res[i] = tmp;
});
// console.log(res);
const arrayToken = res.map(function (obj) {
return obj.token;
});
// console.log(arrayToken);
const message = {
// to: res[0].token,
registration_ids: arrayToken,
notification: {
body: "Hey! you got update order notification."
}
};
fcm.send(message, function(err, response){
console.log(response);
})
}).catch(err => console.log(err));
jsonData = util.jsonData(null, orders);
res.json(jsonData);
})
.catch(err => {
jsonData = util.jsonData(400);
res.status(jsonData.code).json(jsonData);
})
})
So how to fixed it and can you help me explain error of my code ?
Error is here
WHERE id = "+req.body.driver+" OR id = "+req.body.customer+"
You need to use defined variables in this scope

Resources