How to make case sensitive query with nodejs + pg - node.js

How to make case sensitive query with nodejs + pg
I want to select column content == 'a#gmail.com',
but it seems become select column == 'a#gmail.com'?
[error: column "a#gmail.com" does not exist]
code
var userEmail = 'a#gmail.com';
var query = 'SELECT EXISTS(SELECT * FROM "User" WHERE "Email" = "'+userEmail+'")';
dbClient.query(query, function(error, result) {
...

For use binding parameters you must number it begining with $1 (then $2 and so), then put the parameters in an Array:
var query = 'SELECT EXISTS(SELECT * FROM "User" WHERE "Email" = $1)';
dbClient.query(query, [userEmail], function(error, result) {
Always pass the parameters in an array. Is most secure.
Remember do not pass a function to query if you have a very big table unless you want to read all the table before returns the control to de function. Else you can use the "on" event or use a promise way (like https://www.npmjs.com/package/pg-promise-strict)

This doesn't have anything to do with case. The problem is that you're putting the email address in double-quotes, and in (most varieties of) SQL double-quotes indicate a column name or table name. That's why the error message says column "a#gmail.com" does not exist.
Use single-quotes around values:
var userEmail = 'a#gmail.com';
var query = 'SELECT EXISTS(SELECT * FROM "User" WHERE "Email" = \'' + userEmail + '\')';
Ideally, though, you should just use parameter binding so you don't have to worry about quoting values at all. When you use string concatenation to build SQL queries you very often open yourself up to SQL injection attacks.

Related

Custom LIKE statement in Java Spring Data and Cassandra #Query

I need to query from a table using LIKE statement where parameters are optional.
This is custom query where I can filter employee table by which Non-Empty request param:
Select select = QueryBuilder.select().from("employee");
Where selectWhere = select.where();
if (!email.isEmpty()) {
selectWhere.and(QueryBuilder.like("email", "%" + email + "%"));
}
if (!firstName.isEmpty()) {
selectWhere.and(QueryBuilder.like("first_name", "%" + firstName + "%"));
}
//Note: User will provide either email or first_name or both.
However, the above custom query will need to manually map the Rows to the object which I find too tedious:
ResultSet rs = cassandraClient.getApplicationSession().execute( select );
return rs.all().stream().map(row -> row.getString("first_name")).collect( Collectors.toList() );
Is there a way where I can use a Query annotation like below, so it will return the entity directly?
#Query("SELECT * FROM employee WHERE email LIKE :email AND first_name LIKE :firstName")
Employee search(#Param(value="email" String email, #Param(value="firstName" String firstName)
I tried passing an empty parameter value, but I am getting the following error:
LIKE value can't be empty.

SQL injection ,why should you write 0 or 1=1

In SQL injection, why should you use 0 or 1=1, isn't this automatically evaluated as 1 in boolean operation? I don't understand why we should write it that way. Can someone explain?
Thanks in advance
Because it makes the condition always true.
For example, if someone's SQL code is:
string query = "SELECT * FROM Users WHERE Password = '" + somePassword + "'";
(Username clause omitted for brevity.)
Then you can enter something like this as the password:
' OR 1 = 1;--
Which would make the resulting query:
SELECT * FROM Users WHERE Password = '' OR 1 = 1;--'
The semicolon ends the statement, and -- denotes a comment so everything thereafter is ignored. So it simplifies to:
SELECT * FROM Users WHERE Password = '' OR 1 = 1
This will match all records in the table. Always. Because 1 = 1 is always true. Depending on how the application handles this response, you may be logged in. Perhaps even as the first user in the table, which is likely to be the admin user.
For SQL-injectable code, it's basically a universal password. (Provided you guess a correct username, which isn't difficult.)
Edit: I just noticed the 0 part of your question as well. This would be used when you expect the injected value to be looking for a number rather than a string. For example, consider a similar SQL statement:
string query = "SELECT * FROM Users WHERE Id = " + someID;
The leading 0 in the injected value prevents a syntax error. So the resulting query would be:
SELECT * FROM Users WHERE Id = 0 OR 1 = 1
Same concept as above. This will match all records every time.
Here is a brief explanation for this:-
select title, text from news where id=$id
In the example above the variable $id contains user-supplied data, while the remainder is the SQL static part supplied by the programmer; making the SQL statement dynamic.
Because the way it was constructed, the user can supply crafted input trying to make the original SQL statement execute further actions of the user's choice. The example below illustrates the user-supplied data β€œ10 or 1=1”, changing the logic of the SQL statement, modifying the WHERE clause adding a condition β€œor 1=1”.
select title, text from news where id=10 or 1=1
so the query will still get executed

Pass a list of string's in IN clause in DocumentDb Query

This query works when i try to fetch records using IN and multiple Email Id's:
var families = _client.CreateDocumentQuery<Restraunt>(_documentCollection.SelfLink,
"Select Restraunt.RestrauntId from Restraunt join Rest in Restraunt.Emails where Emails.Email IN ('abc#gmail.com','ab#gmail.com') ").AsEnumerable().ToList();
I want to know how can i pass a list of Email id's as a string in the query?
I tried passing the list of strings directly but is unable to resolve that. Is there any way out to do that?
Let's say i have
List<string> elist=new List<string>{"abc#gmail.com","b#gmail.com"}
How can i pass elist in the query?
You have to change your query to use ARRAY_CONTAINS instead, i.e. like this:
Select Restraunt.RestrauntId
from Restraunt
join Rest in Restraunt.Emails
where ARRAY_CONTAINS(['abc#gmail.com','ab#gmail.com'], Emails.Email)
Then you can parameterize that query, and send the array of emails as a parameter.
You can try this:
List<string> elist=new List<string>{"abc#gmail.com","b#gmail.com"};
string emails = string.Empty;
if (eList!= null)
{
emails = "'" + string.Join("','", eList.Select(x => x != String.Empty? x :"").Distinct().ToArray()) + "'";
emails = emails.Replace("','','", "','");
}
var families = _client.CreateDocumentQuery<Restraunt>(_documentCollection.SelfLink,
"Select Restraunt.RestrauntId FROM Restraunt join Rest in Restraunt.Emails
WHERE Emails.Email IN (" + emails + ") ").AsEnumerable().ToList();

Using string in place of property name (LINQ)

I have been able to get the values from tables using linq.
var q=(from app in context.Applicant
where app.ApplicantName=="")
Now what I want is this:
var q=(from app in context.Applicant
where app.stringIhave =="") // so instead of column name I have string which has same name as column.
Is it possible to specify string in Select as this is not sure what I will get in each case, I need different data all the time.
Is it possible to do so?
If no, then I will figure out something else.
Update
I have a GlobalString, which holds the column name of a table.
So when I query that table, I only specify from string which column value I want to get:
var q=(from app in context.Applicants
where app.ID==1013
select GlobalString //which is specifying that I want to get value from which column, as column name is not fixed.
//where GlobalString can have values like: app.FirstName..app.LastName etc
Update1:
var q = context.Applicants.Select("new(it.ApplicantFirstName as FirstName, it.ApplicantLastName as LastName)");
Error Message:
The query syntax is not valid. Near keyword 'AS'
You can use Dynamic Linq (available from NuGet) for that:
var q = context.Applicant.Where(app.stringIhave + " = #0", "");
for select you can try something like this
var q = context.Applicant.Select("new(it.FirstName as FirstName, it.LastName as LastName)");
so you only need construct string for that format

How to get last insert id when using sub query in Kohana

How do I return the correct $insert_id when using a sub query in Kohana?
I'm using the query method to return $insert_id and $affected_rows. It returns the correct value for $affected_rows but returns '1' for $insert_id which is incorrect.
Query below:
$sub = DB::select('id', 'username', 'email', 'lastVisitDate')->from('jos_users');
$qry_migrate_users = DB::insert('temp_users', array('old_id', 'username', 'email_work', 'last_login'))->select($sub);
list($insert_id, $affected_rows) = $qry_migrate_users->execute($this->conn_target);
MySQL returns only last insert id and affected rows. there is only one way to do what you want - execute your sub-select to array, and using foreach do single inserts. But it's a lilte bit slower operation! Or after inserting do something like that:
SELECT id FROM temp_users WHERE email IN (select email from jos_users)
You might understand the logic

Resources