error: syntax error at or near "S" node posgres - node-postgres

My question is I can't resolve the error 42601 which is I know that a syntax error. I run the query on pgadmin and it just works fine. Here's my code
I need to concatenate process of query to solve different requests of user.
ps. im using node posgres promise
return new Promise((resolve,reject)=>{
let {searchType , searchValue , sortType , filterType , size , index} = req.params;
var select_clause = `SELECT svn_id , mobile_number , network_prefixes.prefix , network_prefixes.country_name , date_created ,
date_subscribed , expiry_date , svn_status ,
(select count(*) from svn_transactions where svn_status = 'ACTIVE') "total_active_svn",
(select count(*) from svn where status = 'UNASSIGNED') "total_available_svn",
(select count(*) from svn_transactions where (svn_status = 'INACTIVE' OR svn_status = 'INCOMING_SMS_ONLY')) "total_grace_svn"
FROM svn_transactions
LEFT JOIN network_prefixes ON network_prefixes.prefix = substr(svn_transactions.mobile_number,1,length(network_prefixes.prefix)) `;
var where_clause;
switch(searchType){
case 'MOBILE_NUMBER':
where_clause = `WHERE (mobile_number LIKE '%' || $1 || '%') `;
break;
case 'SVN_NUMBER':
where_clause = `WHERE (svn_id LIKE '%' || $1 || '%') `;
break;
default: //ALL
where_clause = `WHERE (mobile_number LIKE '%' || $1 || '%') OR (svn_id LIKE '%' || $1 || '%') `;
}
var sort_type;
switch(sortType){
case 'MOBILE_NUMBER':
sort_type = `order by mobile_number `;
break;
case 'SVN_NUMBER':
sort_type = `order by svn_id `;
break;
case 'RENEWAL_DATE':
sort_type = `order by date_subscribed `;
break;
case 'SUBSCRIPTION_DATE':
sort_type = `order by date_created `;
break;
}
var pagination = ` limit $2 offset $3`;
var query = `${select_clause} ${where_clause} ${sort_type} ${filterType} ${pagination}`;
pool.query(query[
searchValue , size , index
],function(err,result){
if(err) {
console.log(err);
reject(err);
}resolve(result);
});
});
response error is:
error: syntax error at or near "S"
at Connection.parseE (/var/www/appvno/admin/node_modules/pg/lib/connection.js:614:13)
at Connection.parseMessage (/var/www/appvno/admin/node_modules/pg/lib/connection.js:413:19)
at Socket.<anonymous> (/var/www/appvno/admin/node_modules/pg/lib/connection.js:129:22)
at Socket.emit (events.js:315:20)
at addChunk (_stream_readable.js:295:12)
at readableAddChunk (_stream_readable.js:271:9)
at Socket.Readable.push (_stream_readable.js:212:10)
at TCP.onStreamRead (internal/stream_base_commons.js:186:23) {
length: 89,
severity: 'ERROR',
code: '42601',
detail: undefined,
hint: undefined,
position: '1',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'scan.l',
line: '1134',
routine: 'scanner_yyerror'}
I tried just combining them into 1 single query and it just works fine.:
var example_query = `SELECT svn_id , mobile_number , network_prefixes.prefix , network_prefixes.country_name ,
date_created , date_subscribed , expiry_date , svn_status ,
(select count(*) from svn_transactions where svn_status = 'ACTIVE') "total_active_svn",
(select count(*) from svn where status = 'UNASSIGNED') "total_available_svn",
-- total_recycled_svn
(select count(*) from svn_transactions where (svn_status = 'INACTIVE' OR svn_status = 'INCOMING_SMS_ONLY')) "total_grace_svn"
FROM svn_transactions
left join network_prefixes on network_prefixes.prefix = substr(svn_transactions.mobile_number,1,length(prefix))
WHERE (mobile_number LIKE '%' || $1 || '%')
order by mobile_number DESC
limit $2 offset $3`;
I researched if its theres a limitation on concatenation of select query but I found nothing. Any help will do, thanks!
EDIT 1: I already checked if spaces are correct and also no missing semicolons... based on 42601 meaning
EDIT 2: Here's my console.log of concatenated query"
SELECT svn_id , mobile_number , network_prefixes.prefix , network_prefixes.country_name , date_created ,
date_subscribed , expiry_date , svn_status ,
(select count(*) from svn_transactions where svn_status = 'ACTIVE') "total_active_svn",
(select count(*) from svn where status = 'UNASSIGNED') "total_available_svn",
(select count(*) from svn_transactions where (svn_status = 'INACTIVE' OR svn_status = 'INCOMING_SMS_ONLY')) "total_grace_svn"
FROM svn_transactions
LEFT JOIN network_prefixes ON network_prefixes.prefix = substr(svn_transactions.mobile_number,1,length(network_prefixes.prefix)) WHERE (mobile_number LIKE '%' || $1 || '%') order by mobile_number DESC limit $2 offset $3
Still works fine on pgadmin but still error 42601 on node postgres

At this part:
`SELECT svn_id , mobile_number , network_prefixes.prefix , network_prefixes.country_name ,
date_created , date_subscribed , expiry_date , svn_status ,
(select count(*) from svn_transactions where svn_status = 'ACTIVE'
use \ ' instead of ' at 'ACTIVE' (no spaces between \ and ')
Also, why are you using ` to delimit a string? Shouldn't it be ' ?

I found the error. It's not the query but the error was my setup of pool.query. I just forget adding comma after the query and before the values. hehe stupid me
before: pool.query(query[..
after: pool.query(query,[..

Related

How to pass a variable in join query in Laravel

I have a variable that I would like to pass in a joined RAW query. How can I do that ?
$current_user_id = Auth::user()->id;
$query = DB::table('users as u')
->selectRaw('
ROW_NUMBER() OVER (ORDER BY u.id) AS No,
u.id,
u.username,
l.level AS Rank
')
->leftjoin(DB::raw('(
SELECT
u.id as ts_user_id,
u.username as ts_username,
u.email as ts_email,
l.downline_user_id AS ts_downline_user_id ,
outer_u.username AS ts_downline_username,
sum(o.pay_amount) AS ts_team_sales
FROM
users as u
INNER JOIN user_levels AS l
ON l.upline_user_id = u.id
INNER JOIN users as outer_u
ON outer_u.id = l.downline_user_id
LEFT JOIN user_levels as downline_level
ON l.downline_user_id = downline_level.upline_user_id
INNER JOIN users as outerdownline__u
ON outerdownline__u.id = downline_level.downline_user_id
LEFT JOIN orders as o
ON o.user_id = downline_level.downline_user_id
WHERE o.status = 1 AND downline_level.level > 1 AND u.id=1 **//HOW to pass the $current_user_id variable here**
GROUP BY l.downline_user_id
)RESULT_TEAM_SALES') , 'RESULT_TEAM_SALES.ts_downline_user_id' , 'l.downline_user_id')
->where('u.id' , $current_user_id)
->groupBy('l.downline_user_id')
->get()
I would like to replace Where u.id = $current_user_id . Is passing the variable possible ?
Please advise.
Thank you.
Do something like
DB::table('users')
->join('contacts', function ($join) {
$join->on('users.column', '=', $yourVariable);
})
->get();
https://laravel.com/docs/9.x/queries
So, this is how I solved it. I made a sub query
$current_user_id = Auth::user()->id;
$teamSales= DB::table('users as u')
->selectRaw('
u.id,
u.username as ts_username,
l.downline_user_id AS ts_downline_user_id ,
outer_u.username AS ts_downline_username,
sum(o.pay_amount) AS ts_team_sales
')
->join('user_levels as l' , 'u.id' , '=' , 'l.upline_user_id')
->join('users as outer_u' , 'outer_u.id' , '=' , 'l.downline_user_id')
->leftJoin('user_levels as downline_level' , 'l.downline_user_id' , '=' , 'downline_level.upline_user_id')
->leftJoin('orders as o' , 'o.user_id' , '=' , 'downline_level.downline_user_id')
->where('o.status' , '=' , 1)
->where('downline_level.level' , '>' , 1)
->where('u.id' , '=' , $current_user_id)
->groupBy('l.downline_user_id')
;
Then used leftJoinSub method to left join the sub query
$query = DB::table('users as u')
->selectRaw('
ROW_NUMBER() OVER (ORDER BY u.id) AS No,
u.id,
u.username,
team_sales.ts_team_sales
')
->join('user_levels as l' , 'l.upline_user_id' , '=' , 'u.id')
->leftJoinSub($teamSales , 'team_sales' , function($join) {
$join->on('l.downline_user_id', '=', 'team_sales.ts_downline_user_id');
})
->where('u.id' , $current_user_id)
->groupBy('l.downline_user_id')
->get();

SQL code error mismatched input 'from' expecting

Hi below is my SQL code and it gives me error and I do not know why. If anyone can help.
select time_dif, count(time_dif) as count
from
(
select datediff(so_so_close_time,date_closed) as time_dif
from `mbg_service_prd`.`mds_service_orders_base_cdl`
inner join `mbg_service_prd`.`rnt_incident_detail_base_cdl`
on
(srv_customer_phone = mobile_phone or srv_customer_email = email_address)
where (
(srv_customer_phone<>''or srv_customer_phone is not null)
or (srv_customer_email<>'' or srv_customer_email is not null)
or (mobile_phone<>'' or mobile_phoneis not null)
or (email_addressis<>'' or email_addressis not null)
)
)
group by time_dif
order by time_dif
It gives me error says:
org.apache.spark.sql.catalyst.parser.ParseException:
mismatched input 'from' expecting {, 'WHERE', 'GROUP', 'ORDER', 'HAVING', 'LIMIT', 'LATERAL', 'WINDOW', 'UNION', 'EXCEPT', 'INTERSECT', 'SORT', 'CLUSTER', 'DISTRIBUTE'}(line 3, pos 0)
There is an error in datediff function . We use three parameters in datediff i.e. interval,date1,date2.
DATEDIFF(interval, date1, date2).
Try with the below query
select a.time_dif, count(a.time_dif) as time_dif_count
from
(
select datediff(day,so_so_close_time,date_closed) as time_dif
from mbg_service_prd.mds_service_orders_base_cdl
inner join mbg_service_prd.rnt_incident_detail_base_cdl
on
(srv_customer_phone = mobile_phone or srv_customer_email = email_address)
where (
(srv_customer_phone <> '' or srv_customer_phone is not null)
or (srv_customer_email <> '' or srv_customer_email is not null)
or (mobile_phone <> '' or mobile_phone is not null)
or (email_address <> '' or email_address is not null)
)
)a
group by a.time_dif
order by a.time_dif

MVC SQL invalid

I have the following code in my MVC Index function. It is called from a search page that allows the user to search for various string values:
public ViewResult Index(string sortOrder, string YearString,string MonthString,string BudgetTypeString,string DescriptionString)
{
ViewBag.BudgetTypeSortParm = String.IsNullOrEmpty(sortOrder) ? "BudgetType_desc" : "";
ViewBag.MonthSortParm = sortOrder == "Date" ? "Month_desc" : "Month";
ViewBag.YearSortParm = sortOrder == "Date" ? "Year_desc" : "Year"; // 12-24-2014 JR added
ViewBag.DescriptionSortParm = sortOrder == "Description" ? "Description_desc" : "Description";
var budg = from s in db.budgets
select s;
if (!String.IsNullOrEmpty(YearString) ||
!String.IsNullOrEmpty(MonthString) ||
!String.IsNullOrEmpty(BudgetTypeString) ||
!String.IsNullOrEmpty(DescriptionString))
{
budg = budg.Where(s => s.BudgetType.ToUpper().Contains(BudgetTypeString.ToUpper()) ||
String.IsNullOrEmpty(BudgetTypeString) || s.Description.ToUpper().Contains(DescriptionString.ToUpper()) ||
String.IsNullOrEmpty(DescriptionString) ||
s.Month.ToUpper().Contains(MonthString.ToUpper()) ||
String.IsNullOrEmpty(MonthString) ||
s.Year.ToUpper().Contains(YearString.ToUpper()) ||
String.IsNullOrEmpty(YearString));
budg = budg.OrderBy(s => s.BudgetType);
return View(db.budgets.ToList());
}
}
Here is the actual SQL that is converted from the above code:
budg {SELECT
[Extent1].[id] AS [id],
[Extent1].[BudgetType] AS [BudgetType],
[Extent1].[Description] AS [Description],
[Extent1].[Amount] AS [Amount],
[Extent1].[Month] AS [Month],
[Extent1].[Year] AS [Year],
[Extent1].[DateStamp] AS [DateStamp]
FROM [dbo].[budget] AS [Extent1]
WHERE (( CAST(CHARINDEX(UPPER(#p__linq__0),
UPPER([Extent1].[BudgetType])) AS int)) > 0) OR
(( CAST(CHARINDEX(UPPER(#p__linq__1), UPPER([Extent1].[Description])) AS int)) > 0) OR
(( CAST(CHARINDEX(UPPER(#p__linq__2), UPPER([Extent1].[Month])) AS int)) > 0) OR
(( CAST(CHARINDEX(UPPER(#p__linq__3), UPPER([Extent1].[Year])) AS int)) > 0)}
Does anyone know why my strings are incorrectly being converted into integers and how to correct it so the search strings on my search page work correctly?
Let's take a look at just one of the Cast statements:
( CAST(CHARINDEX(UPPER(#p__linq__1), UPPER([Extent1].[Description])) AS int)) > 0)
Take a look at the inner statement. It's actually getting the CharIndex of one string in the other. Basically, does "Description" contain #p__linq__1. CharIndex returns 0 if if the first expression is not found in the other. The result of CharIndex is what is being Cast as int, and then compared to see if it is greater than 0. Which is exactly what you asked it to do when you use .Contains

Zend select object - building a query

How can I write the query below in Zend Select object notation so using ->join()->where() etc?
SELECT t.id, t.user_id, t.added_date, u.id, u.phone, bk.call_status
FROM `transaction` t
INNER JOIN
(
SELECT id, MAX(added_date) AS addedDate
FROM `transaction`
GROUP BY id
) gt
ON t.id = gt.id AND t.added_date = gt.addedDate
LEFT JOIN `user` u ON t.user_id = u.id
LEFT JOIN `bok_call` bk ON bk.user_id = t.user_id
WHERE NOT t.user_id = 'null'
AND addedDate BETWEEN '2008-05-04 17:51:48' AND '2009-05-04 17:51:48'
AND NOT u.phone = ''
AND bk.call_status IS null
For example this way:
$joinSelect = $model->select()
->from('transaction'), array('id', 'addedDate' => 'MAX(added_date)'))
->group('id');
$select = $model->select()
->setIntegrityCheck(false)
->from(array('t' => 'transaction'), array('id', 'user_id', 'added_date'))
->join(array('gt' => $joinSelect), 't.id = gr.id AND t.added_date = gt.addedDate', array());
->joinLeft(array('u' => 'user'), 't.user_id = u.id', array('id', 'phone'))
->joinLeft(array('bk' => 'bok_call'), 'bk.user_id = t.user_id', array('call_status'))
->where('t.user_id != ?', 'null')
->where("addedDate BETWEEN '2008-05-04 17:51:48' AND '2009-05-04 17:51:48')
->where('u.phone != ?', '')
->where('bk.call_status IS NULL');
Be aware that you won't be able to differentiate 't.id' and 'u.id' in result.

SQL to Entity Framework query for distinct instances

I need to translate the following query from SQL into an Entity Framework query. Can anyone please help.
var query3 = string.Format(#"
SELECT DISTINCT
Boxes.BoxName,
Employees.EmployeeNumber,
Boxes.Port,
Boxes.SerialNumber
FROM
Eventlog
INNER JOIN Boxes
ON Eventlog.SerialNumber = Boxes.SerialNumber
INNER JOIN Employees
ON Eventlog.EmployeeId = Employees.EmployeeId
WHERE
ActionId = {4}
AND Boxes.Deactivated = 0
AND ( ('*' = '{0}')
OR (Boxes.SerialNumber = '{0}') )
AND ( (-1 = {1})
OR (Employees.EmployeeId = '{1}') )
AND EventTime >= '{2}'
AND EventTime <= '{3}'
", boxFilter3, ReportEmployeeIdFilter, ReportStartDate, ReportEndDate, actionFilter);
Something like this should work:
var query = (from log in context.Eventlog
join box in context.Boxes
on log.SerialNumber equals box.SerialNumber
join employee in context.Employees
on log.EmployeeId equals employee.EmployeeId
where log.ActionId == actionFilter
&& box.Deactivated == 0
&& (boxFilter3 == "*" || box.SerialNumber == boxFilter3)
&& (ReportEmployeeIdFilter == -1 || employee.EmployeeId == ReportEmployeeIdFilter)
&& log.EventTime >= ReportStartDate
&& log.EventTime <= ReportEndDate
select new
{
box.BoxName,
employee.EmployeeNumber,
box.Port,
box.SerialNumber
})
.Distinct();