Unwanted square brackets inserted in SQL statement from ORM - sql-server

I'm trying to make a simple select on my table mapped with sqlalchemy but I can't get it to match the exact table name.
As I noticed, the output of this:
class Users(base):
__tablename__ = "users"
[...]
was
[Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid object name 'users'
And I tried to fix the error by explicitly writing the database I'm refering to
class Users(base):
__tablename__ = "[homework-3-cc-database].users"
[...]
giving the output:
[Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near ']'.
I noticed that it inserted some square brackets, unwanted. Here is their SQL statement:
[SQL: SELECT TOP 1 [[homework-3-cc-database].users].user_id AS [[homework-3-cc-database].users_user_id]
FROM [[homework-3-cc-database].users]]
This statement, ran from DataGrip works just fine:
SELECT TOP 1 [homework-3-cc-schema].users.user_id
FROM [homework-3-cc-schema].users
Do you have any suggestions regarding how should I fix this?

I had to specify the schema name in the following way:
__table_args__ = {"schema": "homework-3-cc-schema"}

Related

How to use order_by with UNION in SQLAlchemy

I'm using SQLAlchemy UNION, ORDER_BY is not working, it throwing this
error
Can't resolve label reference for ORDER BY/ GROUP BY/ DISTINCT etc. Textual SQL expression 'LastName' should be explictly declared as text('LastName')
query1 = db.query(Employee.LastName).filter(Employee.Age == 30)
query2 = db.query(Employee.LastName).filter(Employee.Salary > 25000)
result = query1.union(query2).order_by('LastName').all()
Then I tried the below line too, but it didn't work, its throwing this error
(pyodbc.ProgrammingError)('42S22',"[42S22][Microsoft][ODBC Driver 17 for SQL Server][SQL Server] invalid column name 'LastName'. [SQL Server] Statement(s) could not be prepared. (8180)
result = query1.union(query2).order_by(text('LastName').all()

Ambigous column name, cannot get table by group_id

I have SQL code to call my table in my Laravel controller like this:
elseif(auth()->user()->group_id){
$media = MediaOrder::memberOf(auth()->user()->group_id)
->join('users','users.nik','=','media_order.created_by')
->select('media_order.*','users.nickname')
->get();
But when I tried it it come up with an ambiguous column error, like this:
LOG.error: SQLSTATE[42000]: [Microsoft][ODBC Driver 11 for SQL
Server][SQL Server]Ambiguous column name 'group_id'. (SQL: select
[media_order].*, [users].[nickname] from [media_order] inner join
[users] on [users].[nik] = [media_order].[created_by] where [group_id]
= 6) {"userId":"101","exception":{"errorInfo":["42000",209,"[Microsoft][ODBC
Driver 11 for SQL Server][SQL Server]Ambiguous column name
'group_id'."]}
Does anyone has an solution to this? For joining between tables is working, but I just don't know how to use where to get the table based on group_id.
Thank you!.
It seems like both the media_order and users tables have a group_id column, so perhaps something like the following will allow you to distiguish between them...
$media = DB::table('media_order')
->join('users','users.nik','=','media_order.created_by')
->select('media_order.*','users.nickname')
->where('media_order.group_id', '=', auth()->user()->group_id)
->get();

Laravel MS SQL DB::RAW Query returns "Invalid column name"

I'm using SQL Server within my Laravel application. I need to group/sum a table for the month/year. My query looks like this:
$positions = BelegPos::select(
DB::raw("YEAR(Datum) as year"),
DB::raw("MONTH(Datum) as month"),
DB::raw("SUM(Menge) as stunden")
)->groupBy("year", "month")
->get();
I'll get the following error message:
SQLSTATE[42S22]: [Microsoft][ODBC Driver 17 for SQL Server][SQL
Server]Invalid column name 'year'.
I don't know what's wrong, as the query the way I build it works fine with MySQL servers.
Thanks for any hint in the right direction.
UPDATE
I researched a bit more and read about somthing that points out, that the Select Statement isn't available in the GROUP BY section and that you have to add the same query there. so my query looks now like this:
$positions = selectlineBelegPos::select(
DB::raw("YEAR(Datum) as the_year"),
DB::raw("MONTH(Datum) as the_month"),
DB::raw("SUM(Menge) as stunden")
)
->groupBy(DB::raw("YEAR(Datum) as the_year"),DB::raw("MONTH(Datum) as the_month"))
->get();
Still not the solution but the error message has changed to this:
SQLSTATE[42000]: [Microsoft][ODBC Driver 17 for SQL Server][SQL
Server]Incorrect syntax near the keyword (SQL: select
YEAR(Datum) as the_year, MONTH(Datum) as the_month, SUM(Menge) as
stunden from [BELEGP]
So I think there is just one small thing wrong but can't figure out what.
Any ideas?
Solution
Just found the the solution:
$positions = selectlineBelegPos::select(
DB::raw("YEAR(Datum) AS year"),
DB::raw("MONTH(Datum) AS month"),
DB::raw("SUM(Menge) AS stunden")
)
->groupBy(DB::raw("YEAR([Datum])"),DB::raw("MONTH([Datum])"))
->get();
Indeed isn't the dynamically value names (year and month) unavailable in the GROUPBY clause, instead you have to call the DB::raw again but now without generating the key words again.
thank you all for the support!

Get a Sql Server error on Order By - Symfony2

Using Symfony with Sql Server and from what I've read, it seems that the connection to the database is not stable.
As soon as I use the orderBy method I get an error :
Here's an example :
$qStores =
$this->getManager()
->createQueryBuilder()
->select('rpdv')
->from('MainBundle:PointDeVenteReference', 'rpdv')
->andWhere( 'rpdv.partenaireClient = :id_partner ' )
->setParameter( 'id_partner', $this->getUser()->getPartenaire()->getIdPartenaire() )
->orderBy( 'rpdv.idPointDeVenteReference' , 'DESC' )
->setFirstResult( 0 )
->setMaxResults( 30 );
$stores = new Paginator( $qStores, FALSE );
And the error :
An exception has been thrown during the rendering of a template ("An exception occurred while executing
'SELECT DISTINCT TOP 30 id_point_de_vente_reference0
FROM ( SELECT p0_.id_point_de_vente_reference AS id_point_de_vente_reference0,
p0_.reference AS reference1,
p0_.date_derniere_modification AS date_derniere_modification2,
p0_.blocage AS blocage3
FROM point_de_vente_reference p0_
WHERE p0_.id_partenaire_client = ?
ORDER BY p0_.id_point_de_vente_reference DESC ) dctrn_result
ORDER BY id_point_de_vente_reference0 DESC'
with params [2829]:SQLSTATE[42000]:
[Microsoft][SQL Server Native Client 11.0][SQL Server]
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions,
unless TOP, OFFSET or FOR XML is also specified.") in MainBundle:Default:store/list.html.twig at line 79.
I tried to change the class SQLServerPlatform with corrections found on the net, without success.
Do you have any idea?
Thx !
Edit :
This bug appears to be related to the Paginator with the second parameter to true. Passing it to false, I have no error
The dctrn_result is a derived table. From the error message, you can not use an order by. I do not know symfony2, but the code going to the database engine is invalid.
Craftydba

Doctrine2 issue with running GROUP BY against a MSSQL

I'm trying to run a custom query on my DB with Doctrine2 using the following:
$qb = $em->createQueryBuilder();
$qb->select(array('c', 'count(uc) as numMembers'))
->from('AcmeGroupBundle:Group', 'c')
->leftJoin('c.members', 'uc', 'WITH', 'uc.community = c.id')
->groupBy('c')
->orderBy('numMembers', 'DESC')
->setFirstResult( $offset )
->setMaxResults( $limit );
$entities = $qb->getQuery()->getResult();
This query runs flawlessly on my local MySQL DB. But when I try to run it against my production DB (MSSQL), i get the following error:
SQLSTATE[42000]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Column 'Group.discr' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
I do have a discriminator column because I have classes inheriting from Group.
Any suggestions on how should I change the query to make it compatible with MSSQL?
Thanks!

Resources