coumn reference is ambiguous - postgresql

Im getting error
"org.postgresql.util.PSQLException: ERROR: column reference "date_created" is ambiguous"
I have a Base class that defines the date_created field and then all the other classes extend it.
Im makeing a set of REST controllers. All of them use
"sqlRestriction("GREATEST(date_created, last_updated) >= ?", [fromLastUpdated])"
All of them use the same piece of code. All the other 10 cases it works, but with the 11th case it does not work. I dont get why. Ist nearly identical to all the other cases(difference is the other columns).
Where can this issue come from?
SOLUTION
Grails domain classes allow you to have refrences to other Tables
like
Table2 table
within your domain class.
This causes the hilbernate to create a join clause between table1 and table2.
So printed out the criteria created and made small modifications to fix the issue with ambiguiti
"sqlRestriction("GREATEST(this_.date_created, this_.last_updated) >= ?", [fromLastUpdated])"
this_ is the alias given to the domain on whitch you create the criteria.

Related

Cannot use Named Parameters with SSRS and PostgreSQL

I'm trying to add named parameters to a dataset query in a SSRS report (I'm using Report Builder), but I have had no luck discovering the correct syntax. I have tried #parameter, $1, $parameter and others, all without success. I suspect the syntax is just different for PostgreSQL versus normal SQL.
The only success I have had with passing parameters was based on this answer.
It involves using ? for every single parameter.
My query might look something like this:
SELECT address, code, remarks FROM table_1 WHERE date BETWEEN ? AND ? AND apt_num IS NULL AND ADDRESS = ?
This does work, but in the case of a query where I pass the same parameter to more than one part of the SELECT statement, I have to add the same parameter to the list multiple times as shown here. They are passed in this order, so adding a new parameter to an existing query results in having to reshuffle, and sometimes completely rebuild, the query parameters tab.
What are the proper syntax and naming requirements for adding named Parameters when using a PostgreSQL data source in SSRS?
From my comment, this is what it would look like with a regular join:
with inparms as (
select ? as from_date, ? as to_date, ? as address
)
select t.address, t.code, t.remarks
from inparms i
join table_1 t
on t.date between i.from_date and i.to_date
and t.apt_num is null
and t.address = i.address;
I said cross join in my comment because it is sometimes quicker when retrofitting somebody else's SQL instead of trying to untangle things (thinking of a friend who uses right join sometimes just to ruin my day).

SQL Error: 0, SQLState: 42703 with message "The column name str_id was not found in this ResultSet"

this is my first question ever in StackOverflow and as suggested, I have looked at other similar questions and attempted to use their responses for my problem. So far, no luck.
The situation is as follows:
I have a custom query in JPA.
#Query(value="SELECT u.str_id,u.str_exercise_name, u.str_target_body_part,u.char_effect FROM training_schema.exercise_entity u WHERE u.str_exercise_name = ?1 and u.str_target_body_part= ?2", nativeQuery=true)
ExerciseEntity findExerciseEntityByNameAndTargetBodyPart(String str_exercise_name,String str_target_body_part);
If I remove the name of the columns (u.str_id, u.str_exercise_name, u.str_target_body_part, u.char_effect) and replace the query with:
#Query(value="SELECT u FROM training_schema.exercise_entity u WHERE u.str_exercise_name = ?1 and u.str_target_body_part= ?2", nativeQuery=true)
ExerciseEntity findExerciseEntityByNameAndTargetBodyPart(String str_exercise_name,String str_target_body_part);
I get the following error:
"The column name str_id was not found in this ResultSet"
The fact that the error doesn't come when I mention all the columns and is generated when I use alias 'u' doesn't make sense because this would mean that if I ever had to work with a larger table with, say, 10 columns, I would have to write them all out.
One more piece of information that hopefully helps: With the version of the query where I am using 'u' instead of the column names, the error is ONLY generated when a matching record is found. For a null return from the database, there is no problem.
Using Java Spring and PostgresSQL.
I was able to figure out the problem.
In the query where I am using the alias 'u' ALONE, I had to make a slight change. Instead of just saying 'u', I changed it to:
#Query(value="SELECT u.* FROM training_schema.exercise_entity u WHERE u.str_exercise_name = ?1 and u.str_target_body_part= ?2", nativeQuery=true)
ExerciseEntity findExerciseEntityByNameAndTargetBodyPart(String str_exercise_name,String str_target_body_part);
Using only 'u', was returning a record set WITHOUT any headers. Adding the '*' caused the query to return a resultset with column names which made the error go away.

What is the proper way to translate a complicated SQL query with custom columns and rdbms-specific functions to Doctrine

I have been a Propel user for years and only recently started switching to Doctrine. It's still quite new to me and sometimes Propel habits kick in and make it hard form me to "think in Doctrine". Below is a specific case. You don't have to know Propel to answer my question - I also present my case in raw SQL.
Simplified structure of the tables that my query refers is like this:
Application table has FK to Admin which has FK to User (fos_user in the DB)
ApplicationUser table has FK to Application
My query gets all Application records with custom columns containing additional info retrieved from related User records (through Admin) and some COUNTs of related ApplicationUser objects, one of which is additionally filtered (adminname, usercount, usercountperiod columns added to the query).
I have a Propel query like this:
ApplicationQuery::create()
->leftJoinApplicationUser()
->useAdminQuery()
->leftJoinUser()
->endUse()
->withColumn('fos_user.username', 'adminname')
->withColumn('COUNT(application_user.id)', 'usercount')
->withColumn('COUNT(application_user.id) FILTER '
. '(WHERE score > 0 AND '
. ' application_user.created_at >= to_timestamp('.strtotime($users_scored['begin']).') and '
. ' application_user.created_at < to_timestamp('.strtotime($users_scored['end']).') )', 'usercountperiod')
->groupById()
->groupBy('User.Id')
->orderById('DESC')
->paginate( ....
This is how it translates to SQL (PostgreSQL):
SELECT application.id, application.name, ...,
fos_user.username AS "adminname",
COUNT(socialscore_application_user.id) AS "usercount",
COUNT(application_user.id) FILTER (
WHERE score > 0 AND
application_user.created_at >= to_timestamp(1491004800) and
application_user.created_at < to_timestamp(1498780800) ) AS "usercountperiod"
FROM application
LEFT JOIN application_user ON (application.id=application_user.application_id)
LEFT JOIN admin ON (application.admin_id=admin.id)
LEFT JOIN fos_user ON (admin.id=fos_user.id)
GROUP BY application.id,fos_user.id
ORDER BY application.id DESC
LIMIT 15
As you can see it's quite complex (in terms of translating it to Doctrine ORM, when you're a Doctrine newbie like me :) ). It uses specific features of PostgreSQL:
being able to include only Primary Key in GROUP BY statement, while other columns from the same table can be used in SELECT without aggregating function or inclusion in GROUP BY (because they are "dependent" on the PK);
FILTER which allows you to further filter records that are fed into aggregate functions
It also uses some joins and adds custom columns (adminname, usercount, usercountperiod) which I can access in my resulting Propel Model objects (with functions like $result->getAdminname().
My question is: what is the "Doctrine way" to achieve as similar thing as possible as simply as possible (use some PostgreSQL-specific or any RDBMS-specific features, add some custom columns which will be accessible through ORM objects and so on)?
Thank you for help.

Transact-SQL Ambiguous column name

I'm having trouble with the 'Ambiguous column name' issue in Transact-SQL, using the Microsoft SQL 2012 Server Management Studio.
I´ve been looking through some of the answers already posted on Stackoverflow, but they don´t seem to work for me, and parts of it I simply don´t understand or loses the general view of.
Executing the following script :
USE CDD
SELECT Artist, Album_title, track_title, track_number, Release_Year, EAN_code
FROM Artists AS a INNER JOIN CD_Albumtitles AS c
ON a.artist_id = c.artist_id
INNER JOIN Track_lists AS t
ON c.title_id = t.title_id
WHERE track_title = 'bohemian rhapsody'
triggers the following error message :
Msg 209, Level 16, State 1, Line 3
Ambiguous column name 'EAN_code'.
Not that this is a CD database with artists names, album titles and track lists. Both the tables 'CD_Albumtitles' and 'Track_lists' have a column, with identical EAN codes. The EAN code is an important internationel code used to uniquely identify CD albums, which is why I would like to keep using it.
You need to put the alias in front of all the columns in your select list and your where clause. You're getting that error because one of the columns you have currently is coming from multiple tables in your join. If you alias the columns, it will essentially pick one or the other of the tables.
SELECT a.Artist,c.Album_title,t.track_title,t.track_number,c.Release_Year,t.EAN_code
FROM Artists AS a INNER JOIN CD_Albumtitles AS c
ON a.artist_id = c.artist_id
INNER JOIN Track_lists AS t
ON c.title_id = t.title_id
WHERE t.track_title = 'bohemian rhapsody'
so choose one of the source tables, prefixing the field with the alias (or table name)
SELECT Artist,Album_title,track_title,track_number,Release_Year,
c.EAN_code -- or t.EAN_code, which should retrieve the same value
By the way, try to prefix all the fields (in the select, the join, the group by, etc.), it's easier for maintenance.

Struggling with Lambda expression (VB .net)

I have a relatively simple thing that I can do easily in SQL, but I'm trying to get used to using Lambda expressions, and having a hard time.
Here is a simple example. Basically I have 2 tables.
tblAction (ActionID, ActionName)
tblAudit (AuditID, ActionID, Deleted)
tblAudit may have an entry regarding tblAction with the Deleted flag set to 1.
All I want to do is select actions where we don't have a Deleted entry in tblAudit. So the SQL statement is:
Select tblAction.*
From tblAction LEFT JOIN tblAudit on tblAction.ActionID=tblAudit.ActionID
where tblAudit.Deleted <> 1
What would be the equivalent of the above in VB.Net's LINQ? I tried:
Context.Actions.Where(Function(act) Context.Audit
.Where(Function(aud) aud.Deleted=False AndAlso aud.ActionID=act.ActionID)).ToList
But that is really an inner join type scenario where it requires that each entry in tblAction also has an Entry in tblAudit. I am using Entity Framework Code First to do the database mapping. Is there a way to define the mapping in a way where you can do this?
You should add
Public Property Audits As DbSet<Audit>
into your action entity class (to register the association between those tables).
Now you can just write what you mean:
(From act in Context.Actions Where Not act.Audits.Any(Function(audit) audit.Deleted)).ToArray
which is equivalent to
Context.Actions.Where(Function(act) Not act.Audits.Any(Function(audit) audit.Deleted)).ToArray
and let the LINQ parser do the hard SQL work.