Database migration syntax - postgresql

I am unsure how to rewrite this. I understand the issue or at least I think I do. I am unable to use instances of t before it is defined by the follow "AS" statement. How can I resolve this so that so that it works the same way without using the instance of t before definition?
The error that I am getting thrown from the converter is "unable to convert .t"
Converted code
INSERT INTO t$trades_long (portfolio_name, fund, cusip, td_num, desc_instmt, trd_price, trd_trade_dt, t.trd_settle_dt, trd_counterparty, trd_td_par, tran_type, sec_type, trd_type, t.trd_trader)
SELECT
p.portfolio_name, t.fund, t.cusip, t.td_num, a.desc_instmt, t.trd_price, t.trd_trade_dt, t.trd_settle_dt, t.trd_counterparty, t.trd_td_par, t.tran_type, a.sec_type, 'long' AS trd_type, trd_trader
FROM pfi_pilot.br_transaction AS t, pfi_pilot.br_portfolio_group AS p, pfi_pilot.br_asset AS a
WHERE t.fund = p.fund AND p.portfolio_group = 'ALL_FUNDS' AND t.cusip = a.cusip AND t.tran_type IN ('BUY', 'SELL', 'ISSUE', 'ALLOC') AND t.trd_status <> 'C' AND a.sm_sec_group NOT IN ('CASH', 'FUTURE', 'FX', 'FUND', 'SWAP', 'OPTION') AND a.sec_type != 'MBS_TBA' AND t.trd_counterparty NOT IN ('IFUND', 'GHOST', 'SPO', 'SPOBO', 'CONV', 'ASSGN') AND t.trd_trade_dt >= par_from_dt AND t.trd_trade_dt <= par_to_dt AND t.cusip NOT IN (SELECT DISTINCT
cusip
FROM pfi_pilot.br_asset
WHERE (COALESCE(risk_country, country) = 'US' AND sm_sec_type IN ('GOVT', 'TBILL'))) AND t.trd_td_par > 0;
Original code
insert into #trades_long(portfolio_name, fund, cusip, td_num, desc_instmt, trd_price, trd_trade_dt, t.trd_settle_dt,
trd_counterparty, trd_td_par, tran_type , sec_type, trd_type, t.trd_trader)
select p.portfolio_name, t.fund, t.cusip, t.td_num, a.desc_instmt, t.trd_price, t.trd_trade_dt, t.trd_settle_dt,
t.trd_counterparty, t.trd_td_par, t.tran_type, a.sec_type,'long' as trd_type, trd_trader
from br_transaction t, br_portfolio_group p, br_asset a
where t.fund = p.fund
and p.portfolio_group = 'ALL_FUNDS'
and t.cusip = a.cusip
and t.tran_type in ('BUY','SELL','ISSUE','ALLOC')
and t.trd_status <> 'C'
and a.sm_sec_group not in ('CASH','FUTURE','FX','FUND','SWAP','OPTION')
and a.sec_type != 'MBS_TBA'
and t.trd_counterparty not in ('IFUND','GHOST','SPO','SPOBO','CONV','ASSGN')
and t.trd_trade_dt >= #from_dt
and t.trd_trade_dt <= #to_dt
and t.cusip not in (select distinct cusip from br_asset where (isnull(risk_country,country) = 'US'
and sm_sec_type in ('GOVT','TBILL')))
and t.trd_td_par > 0

Related

Why does the gorm postgresql throws pq: syntax error at or near ")"?

SELECT_QUERY = `SELECT * FROM events WHERE c_id = ? AND start_time > ? and
end_time < ?`
query := sr.db.Raw(SELECT_QUERY, request.GetCId(), startTime, endTime)
var v = request.GetVIds()
if len(v) > 0 {
query = query.Where(` v_id IN (?) `, v)
} //Only this block introduces first ) after end_time
var c = request.GetStatus().String()
if len(c) > 0 {
query = query.Where( " status = ? ", c) // this introduces the other opening brace //after AND
}
Following is the query generated and found in logs
SELECT * FROM events WHERE c_id = 1 AND start_time > '2020-04-16 18:42:00' and
end_time < '2020-04-16 18:45:50' ) AND ( v_id IN (1,2)) AND ( status = 'STATUS_MIDDLE_CLASS' ORDER BY start_time DESC LIMIT 5 OFFSET 1
The other solution in stackoverflow and internet article doesn't help.
PS: Is it because I mix db.Raw( ) and query.Where() ?
Changing ? to $1 doesn't fix the issue.
Basically a few things fixed the issue.
1) Mixing Raw and query.Where was one issue.
After making the Raw query to sr.db.Where
2)
SELECT_QUERY = `SELECT * FROM events WHERE c_id = ? AND start_time > ? and
end_time < ?`
already has select * from. And then using query := sr.db.Raw(SELECT_QUERY, request.GetCId(), startTime, endTime) introduces nested select *.
So, changed SELECT_QUERY as follows
SELECT_QUERY = `events WHERE c_id = ? AND start_time > ? and
end_time < ?`
solved the issue.
I found a workaround to the error which I received when I tried to add a timestamp filed in Go/Gorm solution with PostgreSQL equivalent to default: now() which is default: time.Now().Format(time.RFC3339)
I received the error because I use AutoMigrate() to create the tables in PostgreSQL. The one problem I found is when trying to use the default value of a function instead of a string (which one can use for a fixed timestamp).
So I had to go into DataGrid (since I use JetBrains, but you can use any PostgreSQL admin tool like pgAdmin) and manually add the timestamp field with default of now() or merely update the existing field to add the default of now(). Then the error goes away when doing your next build in Go.

Kentico document query API always returns empty result

I have the following query:
var newsItems = tree.SelectNodes()
.Types(pageTypesArray)
.Path(path)
.OrderBy(orderBy)
.CombineWithDefaultCulture(false)
.Page(page, count)
.OnCurrentSite()
.NestingLevel(-1)
.Culture(CurrentDocument.DocumentCulture)
.InCategories(categories)
.TopN(topN)
.Where("ListableDocumentImage is not null AND ListableDocumentImage != ''")
.Columns(columns);
Which translates like so:
WITH AllData AS
(
SELECT TOP 6 * for brevity, ROW_NUMBER() OVER (ORDER BY [NewsOccurrenceDate] DESC) AS [CMS_RN]
FROM View_CMS_Tree_Joined AS V WITH (NOLOCK, NOEXPAND) INNER JOIN SOS_News AS C WITH (NOLOCK) ON [V].[DocumentForeignKeyValue] =
[C].[NewsID] AND V.ClassName = N'News' LEFT OUTER JOIN COM_SKU AS S WITH (NOLOCK) ON [V].[NodeSKUID] = [S].[SKUID]
WHERE [NodeSiteID] = #NodeSiteID AND (([DocumentCanBePublished] = 1 AND ([DocumentPublishFrom] IS NULL OR [DocumentPublishFrom] <= #Now)
AND ([DocumentPublishTo] IS NULL OR [DocumentPublishTo] >= #Now))
AND [NodeAliasPath] LIKE #NodeAliasPath AND [DocumentCulture] = #DocumentCulture
**AND 0 = 1)** <<<------------------- WHERE DID THIS COME FROM?????
)
SELECT *, (SELECT COUNT(*) FROM AllData) AS [CMS_TOT]
FROM AllData
WHERE CMS_RN BETWEEN 4 AND 6
ORDER BY CMS_RN
Has anyone ever come across anything like this before? I can't figure out why they're sticking in the AND 0=1 in my where clause.
Properly structuring your document API call will help with this. In your query results, you can see your WHERE condition is not even being added so it does make a difference the order of the methods being called.
For instance:
var newsItems = tree.SelectNodes()
.Types(pageTypesArray)
.Path(path)
.Where("ListableDocumentImage is not null AND ListableDocumentImage != ''")
.TopN(topN)
.OrderBy(orderBy)
.CombineWithDefaultCulture(false)
.Page(page, count)
.NestingLevel(-1)
.Culture(CurrentDocument.DocumentCulture)
.InCategories(categories)
.OnCurrentSite()
.Columns(columns);

How to create an Update statement from a subquery in TSQL

I need to update all records that match my criteria. But the Sql below is giving this error:
Subquery returned more than 1 value. This is not permitted when the
subquery follows =, !=, <, <= , >, >= or when the subquery is used as
an expression.
-- Set MasterAccountId = NULL where there is no Receivable with equivalent BillingAccountId and TaskAccountId
UPDATE R
SET R.MasterAccountId = NULL
FROM Receivable R
WHERE EXISTS ( SELECT * FROM MasterAccount M
WHERE (ISNULL(M.BillingAccountId, 0) > 0 AND M.BillingAccountId = R.BillingAccountId) OR
(ISNULL(M.TaskAccountId, 0) > 0 AND M.TaskAccountId = R.TaskAccountId))
Basically, I need to update all records that return in that subquery.
Does any one know how to fix it?
Can you give a try on this. This is base from the repond of https://stackoverflow.com/users/40655/robin-day on this link How do I UPDATE from a SELECT in SQL Server?.
UPDATE
R
SET
R.MasterAccountId = NULL
FROM
Receivable R
INNER JOIN
MasterAccount M
ON
(ISNULL(M.BillingAccountId, 0) > 0 AND M.BillingAccountId = R.BillingAccountId) OR
(ISNULL(M.TaskAccountId, 0) > 0 AND M.TaskAccountId = R.TaskAccountId))
I don't think you are getting the said error in posted query May be somewhere else. Again in your EXISTS subquery, instead of saying select * ... it's always better to say WHERE EXISTS ( SELECT 1 FROM MasterAccount M
Also try using the JOIN version of this query instead like
UPDATE R
SET R.MasterAccountId = NULL
FROM Receivable R
JOIN MasterAccount M ON M.BillingAccountId = R.BillingAccountId
OR M.TaskAccountId = R.TaskAccountId
WHERE ISNULL(M.BillingAccountId, 0) > 0
OR ISNULL(M.TaskAccountId, 0) > 0;

T-SQL 'AND' keyword not short-circuiting it seems

The below stored proc works fine except for the fact that when I uncomment the second part of the date check in the 'where' clause it blows up on a date conversion even if the passed in keyword is null or '111'.
I'm open to any suggestions on how to do this dynamic where clause differently.
I appreciate any help.
ALTER PROCEDURE [SurveyEngine].[GetPageOf_CommentsOverviewRowModel]
#sortColumn varchar(50),
#isASC bit,
#keyword varchar(50)
AS
BEGIN
declare #keywordType varchar(4)
set #keywordType = null
if ISDATE(#keyword) = 1
set #keywordType = 'date'
else if ISNUMERIC(#keyword) = 1
set #keywordType = 'int'
select c.CommentBatch BatchID, c.CreatedDate DateReturned, COUNT(c.CommentID) TotalComments
from SurveyEngine.Comment c
where (#keywordType is null)
or (#keywordType = 'date') --and c.CreatedDate = #keyword)
or (#keywordType = 'int' and (CONVERT(varchar(10), c.CommentBatch) like #keyword+'%'))
group by c.CommentBatch, c.CreatedDate
order by case when #sortColumn = 'BatchID' and #isASC = 0 then c.CommentBatch end desc,
case when #sortColumn = 'BatchID' and #isASC = 1 then c.CommentBatch end,
case when #sortColumn = 'DateReturned' and #isASC = 0 then c.CreatedDate end desc,
case when #sortColumn = 'DateReturned' and #isASC = 1 then c.CreatedDate end,
case when #sortColumn = 'TotalComments' and #isASC = 0 then COUNT(c.CommentID) end desc,
case when #sortColumn = 'TotalComments' and #isASC = 1 then COUNT(c.CommentID) end
END
EDIT Sorry, brain cloud. Things need to be initialized differently.
Change the setup to:
declare #keywordType varchar(4)
declare #TargetDate as DateTime = NULL
set #keywordType = null
if ISDATE(#keyword) = 1
begin
set #keywordType = 'date'
set #TargetDate = Cast( #keyword as DateTime )
end
else if ISNUMERIC(#keyword) = 1
set #keywordType = 'int'
Then change:
and c.CreatedDate = #keyword
to:
and c.CreatedDate = Coalesce( #TargetDate, c.CreatedDate )
That will result in a NOP if you are not searching by date.
Based on this guy's blog: http://blogs.msdn.com/b/bartd/archive/2011/03/03/don-t-depend-on-expression-short-circuiting-in-t-sql-not-even-with-case.aspx it looks like you can't guarantee the order of operations in the where clause, even though short circuiting is supported. The execution plan may choose to evaluate the second statement first.
He recommends using a case structure instead (like pst mentioned before) as it is "more" gauranteed. But I don't think I can rewrite your where clause as a case because you're using three different operators (is null, =, and LIKE).

T-SQL: returning VARCHAR in a derived column

I am having problems returning a VARCHAR out of a derived column.
Below are extremely simplified code examples.
I have been able to do this before:
SELECT *, message =
CASE
WHEN (status = 0)
THEN 'aaa'
END
FROM products
But when I introduce a Common Table Expression or Derived Table:
WITH CTE_products AS (SELECT * from products)
SELECT *, message =
CASE WHEN (status = 0)
THEN 'aaa'
END
FROM CTE_products
this seems to fail with the following message:
Conversion failed when converting the varchar value 'aaa' to data type int.
When I tweak the line to say:
WITH CTE_products AS (SELECT * from products)
SELECT *, message =
CASE WHEN (status = 0)
THEN '123'
END
FROM CTE_products
It returns correctly.
...
When I remove all the other clauses prior to it, it also works fine returning 'aaa'.
My preference would be to keep this as a single, stand-alone query.
The problem is that the column is an integer dataype and sql server is trying to convert 'aaa' to integer
one way
WITH CTE_products AS (SELECT * from products)
SELECT *, message =
CASE WHEN (status = 0)
THEN 'aaa' else convert(varchar(50),status)
END
FROM CTE_products
I actually ended up finding the answer.
One of my CASE/WHEN clauses used a derived column from the CTE and that ended up causing the confusion.
Before:
WITH CTE_products AS (SELECT *, qty_a + qty_b as qty_total FROM products)
SELECT *, message =
CASE WHEN (status = 0)
THEN 'Status is 0, the total is: ' + qty_total + '!'
END
FROM CTE_products
Corrected:
WITH CTE_products AS (SELECT *, qty_a + qty_b as qty_total FROM products)
SELECT *, message =
CASE WHEN (status = 0)
THEN 'Status is 0, the total is: ' + CAST(qty_total AS VARCHAR) + '!'
END
FROM CTE_products
I ended up removing WHEN/THEN clauses within the CASE statement right afterwards to see if it was a flukey parentheses error when I realized that in the absence of any of the WHEN/THEN clauses that included the derived column from the CTE, it was able to return VARCHAR.