Issue in Sqlite while using Node js. Like operator and parameters - sql

So I am trying to select rows based on user input, as shown below:
db.all(
'SELECT * FROM houses WHERE location LIKE "%$input%"',
{
$input: name,
},
(error, rows) => {
res.send(rows);
}
);
However, the database responds with an undefined value. What can I do?

You are not using query parameters properly. Consider:
db.all(
"SELECT * FROM houses WHERE location LIKE '%' || ? || '%",
[name],
(error,rows) => { ... }
);
It might be slightly more efficient to concatenate the variable in the js code:
db.all(
"SELECT * FROM houses WHERE location LIKE ?",
['%' + name + '%'],
(error,rows) => { ... }
);

Related

Getting sum complete (without pagination) of particular columns in backpack for laravel

I followed the recommendations I found here
jQuery(document).ready(function($) {
jQuery.fn.dataTable.Api.register( 'sum()', function ( ) {
return this.flatten().reduce( function ( a, b ) {
if ( typeof a === 'string' ) {
a = a.replace(/[^\d.-]/g, '') * 1;
}
if ( typeof b === 'string' ) {
b = b.replace(/[^\d.-]/g, '') * 1;
}
return a + b;
}, 0 );
} );
$("#crudTable tfoot").css("display", "table-footer-group");
crud.table.on("draw.dt", function ( row, data, start, end, display ) {
total = crud.table.rows( function ( idx, data, node ) {
return data[11].includes('Cancelado') ? false : true;} ).data().pluck(10).sum();
total = "$" + total.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
$("#crudTable tfoot tr th").html(
" <br> "
);
$("#crudTable tfoot tr").children().eq(10).html(
"Total <br>"+ total
);
});
});
And I added some modifications to get the total of the column by skipping the items that have canceled status, but I have not been able to get the total of the records but without paging. With Datatable I get the records that are being drawn, but I can't find how to intercept the ajax query or modify it to get the full total on that column including filter modifications.
Currently if in the pagination I request "show all records" obviously I get the value I need. But the requirement is that this value is displayed even if the table is visually paginated.
one way to achieve that would be to overwrite the search() function of the ListOperation (it's the table ajax endpoint).
You would need do do the full query without the pagination part to get the full data, and then pass the calculation along with the paginated response for display.
Cheers

Can Laravel automatically switch between column = ? and column IS NULL depending on value?

When building a complex SQL query for Laravel, using ? as placeholders for parameters is great. However when the value is null, the SQL syntax needs to be changed from = ? to IS NULL. Plus, since the number of parameters is one less, I need to pass a different array.
To get it to work, I have written it like this, but there must be a better way:
if ($cohortId === null) {
// sql should be: column IS NULL
$sqlCohortString = "IS NULL";
$params = [
Carbon::today()->subDays(90),
// no cohort id here
];
} else {
// sql should be: column = ?
$sqlCohortString = "= ?";
$params = [
Carbon::today()->subDays(90),
$cohortId
];
}
$query = "SELECT items.`name`,
snapshots.`value`,
snapshots.`taken_at`,
FROM snapshots
INNER JOIN (
SELECT MAX(id) AS id, item_id
FROM snapshots
WHERE `taken_at` > ?
AND snapshots.`cohort_id` $sqlCohortString
GROUP BY item_id
) latest
ON latest.`id` = snapshots.`id`
INNER JOIN items
ON items.`id` = snapshots.`item_id`
ORDER by media_items.`slug` ASC
";
$chartData = DB::select($query, $params);
My question is: does Laravel have a way to detect null values and replace ? more intelligently?
PS: The SQL is for a chart, so I need the single highest snapshot value for each item.
You can use ->when to create a conditional where clause:
$data = DB::table('table')
->when($cohortId === null, function ($query) {
return $query->whereNull('cohort_id');
}, function ($query) use ($cohortId) {
// the "use" keyword provides access to "outer" variables
return $query->where('cohort_id', '=', $cohortId);
})
->where('taken_at', '>', $someDate)
->toSql();

Oracle and Nodejs - can't bind parameters in SQL statement

Hi I have the following statement that I execute using node-oracle
await connection.execute(`SELECT * FROM TABLE WHERE NAME LIKE '%And%'`)
But now I want to bind a parameter instead of using a hard coded value
const queryText = 'And';
await connection.execute(`SELECT * FROM TABLE WHERE NAME LIKE '%:queryText%'`, {queryText});
it throws Error: ORA-01036: illegal variable name/number
What is the correct way of binding a parameter here, since the documentation doesn't cover this situation?
Try with the following:
const queryText = 'And';
await connection.execute(
"SELECT * FROM TABLE WHERE NAME LIKE :queryText",
{
queryText: { dir: oracledb.BIND_IN, val: '%'+ queryText +'%', type: oracledb.STRING }
});
Use string concatenation:
SELECT * FROM TABLE WHERE NAME LIKE '%' || :queryText || '%'
Here is a working example.
let queryText = "John"
let sql = "SELECT * FROM TABLE WHERE NAME LIKE :queryText"
let binds = {queryTarget: {dir: oracledb.BIND_IN, val: queryText, type: oracledb.STRING}}
let result = await connection.execute(sql, binds, options)
Do not add '%' like the other people suggested.

In typescript, how to sort exactly like MSSQL's 'order by' clause for special characters like * , + - etc

I have a Angular5 based front-end which needs to show a list of persons. A similar list is shown at the back-end application. Both lists need to be sorted exactly the same. The back-end list is fetched via a query in MSSQL DB which uses an 'order by' clause like this :
select * from PERSON where GROUP=1 order by PERSON.LAST_NAME ASC, PERSON.INITIALS ASC, PERSON.PREFIX ASC, PERSON.FIRSTNAME ASC
On the frontend, my person model looks like :
export interface Person {
id?: number;
fullName?: string;
}
The fullName here is as per this format : [LastName, Initials Prefix FirstName] eg : Adams, Mr P John.
I am using this method to sort it :
public sortByName(aPersonArr: Person[]) {
aPersonArr.sort((p1, p2) => {
let name1 = p1.fullName;
let name2 = p2.fullName;
// If both names are blank, consider them equal, If one name is blank, place it at the last
if (!name1 && !name2) {
return 0;
} else if (name1 && !name2) {
return -1;
} else if (name2 && !name1) {
return 1;
}
name1 = name1.toLowerCase();
name2 = name2.toLowerCase();
if (name1 < name2) {
return -1;
}
if (name1 > name2) {
return 1;
}
return 0;
});
}
}
But the problem occurs when a person's fullName begins with a special character because SQL Query fetches the names in this order : (Showing only the lastNames here)
*Account
,Adams
.Alkin
+Account
-Adams
Whereas my typescript code sorts them like this : (Showing only the lastNames here)
*Account
+Account
,Adams
-Adams
.Alkin
The reason that I need to have this logic at frontend is that many a times my person list is dynamically prepared and needs to be sorted right away. Is there a way to know what exact logic is used by SQL query to compare strings, so that i can use the same in my sorting method.

Conditions in JOINed tables shows error CakePHP

I have two tables employee_personals where all the personal record of the employee is stored and telephone_bills where the telephone bills paid to a particular employee is stored for each month. Now in my employeePersonalsController.php I have a function called api_show_employees() which is similar to below :
function api_show_employees() {
//$this->autoRender = false;
//Configure::write("debug",0);
$office_id = '';
$cond = '';
if(isset($_GET['office_id']) && trim($_GET['office_id']) != '') {
$office_id = $_GET['office_id'];
$cond['EmployeePersonal.office_id'] = $office_id;
}
if(isset($_GET['telephoneBillTo']) && isset($_GET['telephoneBillFrom']) ) {
if($_GET['telephoneBillTo'] != '' && $_GET['telephoneBillFrom'] != '') {
$cond['TelephoneBill.bill_from'] = $_GET['telephoneBillFrom'];
$cond['TelephoneBill.bill_to'] = $_GET['telephoneBillTo'];
}
}
$order = 'EmployeePersonal.name';
// $employee = $this->EmployeePersonal->find('all');
$employee = $this->EmployeePersonal->find('all',array('order' => $order,'conditions'=>$cond));
//return json_encode($employee);
}
This functions basically finds all the employees who paid bills in the given period. But I am getting an error
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'TelephoneBill.bill_from' in 'where clause'
Models : EmployeePersonal.php:
var $hasMany = array(
'TelephoneBill' => array(
'className' => 'TelephoneBill',
)
);
TelephoneBill.php
public $name = 'TelephoneBill';
var $hasMany = array('EmployeePersonal');
NB: If I skip the bill_from and bill_to conditions, I am getting the results , with TelephoneBill array !
TLDR: use Joins instead.
Details/Notes:
1) it looks like you're using recursive. Don't do that. Use Containable instead.
2) You can't limit the parent model based on conditions against data from a contained/recursive-included table - instead, use Joins.
2b) Or, you could query from the other direction, and query your TelephoneBill with conditions, then contain the EmployeePersonal.