Problems with Node.js and postgresql - node.js

I'm doing an app with express in node. I thought about different DBMS before coming up with the idea of using PostgreSQL (I haven't got any NoSQL experience) but it's bugging me out due to some unexpected errors.
I'm trying to check if a user exist when he logs, but the Select statement doesn't work, don't know why:
var query = client.query('SELECT "name" FROM "User" WHERE "pass" = $1', [req.body.password]);
console.log(query.toString());
query.on('row', function(row) {
console.log('user "%s"', row.name);
});
After this the initial page should render (that actually works). I'm using the node-postgres driver, by the way.
If I put something like client.query('SELECT * FROM "User"'); the database works perfectly (and I don't need that behaviour either). I've read about the PostgreSQL identifier problems, but nevertheless it keeps happening.

Okay, turns out user table exists, and the table I created is case sensitive. It works know.
I tried select * from user on psql and it returned the current user. Tried select * from "User" and turned out I was wrong. Funny thing.

Related

Getting database names from server

I want to do a simple thing: get the database names on a RavenDB server. Looks straightforward according to the docs (https://ravendb.net/docs/article-page/4.1/csharp/client-api/operations/server-wide/get-database-names), however I'm facing a chicken-and-egg problem.
The problem comes because I want to get the database names without knowing them in advance. The code in the docs works great, but requires to have an active connection to a DocumentStore. And to get an active connection to a DocumentStore, is mandatory to select a valid database. Otherwise I can't execute the GetDatabaseNamesOperation.
That makes me think that I'm missing something. Is there any way to get the database names without having to know at least one of them?
The database isn't mandatory to open a store. Following code works with no problems:
using (var store = new DocumentStore
{
Urls = new[] { "http://live-test.ravendb.net" }
})
{
store.Initialize();
var dbs = store.Maintenance.Server.Send(new GetDatabaseNamesOperation(0, 25));
}
We send GetDatabaseNamesOperation to the ServerStore, which is common for all databases and holds common data (like database names).

Query all Table in Sails.js

I have a project that requires syncing where in syncing is to gather all the data from all tables at start up. Kinda easy.
However with Node.js with the framework Sails.js, I cant seem to find a way to do so as one model is equal to one table, all laid out in projectName/api/models/ as a single file for each.
My initial idea was to loop everything in that directory to be able to do my query for each item, however it doesn't work as I have tried.
Here is my source code for the simple query for only one model:
modelName.getDatastore().sendNativeQuery('SELECT * FROM table WHERE id = 0' ,function(err, res) {
if (err) {
console.log(err);
return exits.success(err);
}
return exits.success(res);
});
With what I have tried (not in my sample above), I changed the modelName into string to test out if looping the directory works, which it doesn't. I also tried temporarily creating a simple variable that represents one of the model's name and used it for query, which also didn't work. I'm at my wit's end and can't find a solution even in google. Any help?

KnexJS giving different response

So I have a NodeJS+KnexJS setup on a PostgreSQL DB, and am using the .whereRaw() method so I can use a CASE statement in my WHERE clause.
The query was tested in my CLI before migrating to code. Here is the code that is being used.
var qry = knex.select(....); // ignore the select, not important.
qry.with('daspecs', function(qy) {
qy.select('spec_id').from('drawings').where('uid', query.d);
}).whereRaw('CASE WHEN (select "spec_id" from "daspecs") IS NULL THEN true ELSE c.spec_id = (select "spec_id" from "daspecs") END');
The SQL that KnexJS is generating (output using qry.toString()) is correct, and I can even copy and paste this to my psql CLI and it returns the results I want (12 records), but for some wierd reason the KnexJS query seems to return a completely different set of results (1106 records).
Not sure where to go next, since KnexJS is giving me the right SQL, but seems like it's executing something else, and not sure how else to diagnose what it is actually doing (I've tried the knex.on('query'...) event).
Any alteration on the final SQL would result in an error (i've tested), so at the point of ruling out missing pieces.
Has anyone had any experience or issues with KnexJS saying one thing, but doing another, in particular, with the whereRaw command?

Key exists error while using ADD into Couchbase

I'm using Couchbase NoSQL DB but I guess this can happen with any NoSQL DB. Here's what happens:
I'm checking if a specific key exists and I'm catching the keyNotFound error to now ADD this key into the database. See the code:
// retrieve the document for this connection_id
db.get(connection_id, function(err, result) {
if (err && err.code === 13) {
// Catched a keyNotFound -> define a new document for the voice connection
var voice_c = {
voice_count: '1',
voice_duration: call_duration,
last_contact: call_start
};
// Add this new Voice_c document for this connection_id to DB
db.add(connection_id, voice_c, function(err, result) {
if (err)
throw err; // whilst adding a new voice connection
});
When I get to the db.add step I get an error "Key exists (with a different CAS value)" even though I just checked fragments of a millisecond before if the same key exist (and it didn't exist).
I couldn't replicate the error at the same place in my data feed but the second time it happened even earlier, indicating it's a random event. I'm puzzled as to how this can happen unless there's a big bug in my code which I just don't see.
There is no other code running and altering the documents in the NoSQL DB, it all runs locally on my MBP. The DB was flushed and was empty before I started to run my script.
I've checked manually in the data feed and when it happened the first time there was indeed the same connection_id about 50 records earlier. But in the second instance the error was thrown when the connection_id was showing up the first time (though it comes up some 19000 records later). Very strange, hope someone can help me how I can avoid getting this error.
have you tried using the "stale:false" option of couchbase for renewing the index? i also would recommend using async.waterfall for both statements, it increases readability and decreases callback hell.

how SQL injection is done? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
XKCD SQL injection - please explain
What is the general concept behind sql injection ?
Being a rails developer
This is unsafe
Booking.find(:all, :conditions => [ 'bookings.user_id = #{params[user_id]]}'] )
and this is safe:--
Booking.find(:all, :conditions => [ 'bookings.user_id = ?', params[user_id]] )
am i right?
So my question is how the sql injection is done?
How those guys do some stuff like that. Any live example/ tutorial where somebody is showing this kind of stuff. Anything basic for knowing the logic.
SQL Injection happens when a programmer gets lazy. A vulnerable query would look like this:
DECLARE #cmd varchar(256)
SET cmd='SELECT #col FROM Table'
EXEC #cmd
With #col being a variable passed into a stored procedure.
Usually, the user would enter a column in that already exists for that variable. But a more devious user could enter something like this:
* FROM Table; DROP DATABASE data;--
The * FROM Table; finishes off the previous statement. Then, DROP DATABASE data; is the payload that does bad things, in this case, dropping the database. Finally, the -- comments out the rest of the query so it doesn't get any errors from the injection.
So, instead of executing this:
SELECT column
FROM Table
You get this:
SELECT *
FROM Table;
DROP DATABASE data;
--
Which is not good.
And this:
All the user has to do is enter:
1234; DROP TABLE BOOKINGS
...
I don't know about rails, but by doing this Booking.find(:all, :conditions => [ 'bookings.user_id = #{params[user_id]]}'] ), you risk that the user give to user_id the value 1 OR 1=1 and as you can see, it will modify your request.
With more injection you could do something like 1; DROP TABLE BOOKINGS etc.
Basically injection is just "hijacking" a basic request to add yours.
Bobby tables
If you have a simple query like
SELECT * FROM bookings WHERE user_id = ORDER BY user_id ASC;
if you don't check user id, it can close your query, then start a new (harmful one) and discard the rest. To achieve this, generally, you would enter something like
1; DELETE FROM bookings; --
initial ; closes the good query, the bad query comes next, then it is closed with ; and -- makes sure that anything that would come next in the good query is commented out. You then end up with
SELECT * FROM bookings WHERE user_id = 1; DELETE FROM bookings; -- ORDER BY user_id ASC;
If your data in properly cleaned and sanatized, a user can try to get their own SQL code to run on the server. for example, let's say you have a query like this:
"SELECT * FROM products WHERE product_type = $type"
where type is unchanged user input from a text field. now, if I were to search for this type:
(DELETE FROM products)
You are gonna be in a world of hurt. This is why it's important to make sure all user input in sanatized before running it in the DB.
Plenty of excellent papers on the theory of SQL injection here:
sql injection filetype:pdf
Should be easy enough to hunt one down that is specific to your language/DB combination.

Resources