Doctrine and Postgresql, Generate Models from DB Problem - postgresql

I have a database in Postgresql 9.0 and I'm trying to use Doctrine ORM 1.2 to generate models from db.
Here is my code:
<?php
require_once 'Doctrine.php';
spl_autoload_register(array('Doctrine', 'autoload'));
spl_autoload_register(array('Doctrine_Core', 'modelsAutoload'));
$manager = Doctrine_Manager::getInstance();
$conn = Doctrine_Manager::connection('pgsql://postgres:secret#192.168.1.108/erp','doctrine');
$conn->setAttribute( Doctrine_Core::ATTR_PORTABILITY, Doctrine_Core::PORTABILITY_FIX_CASE | PORTABILITY_RTM);
$conn->setAttribute( Doctrine_Core::ATTR_QUOTE_IDENTIFIER, true);
$manager->setAttribute(Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE, true);
Doctrine_Core::loadModels('../application/models');
Doctrine_Core::generateModelsFromDb('../application/models', array('doctrine'), array('generateTableClasses' => true));
?>
and when I run the page, I get this error:
Fatal error: Uncaught exception 'Doctrine_Connection_Pgsql_Exception' with message 'SQLSTATE[42P01]: Undefined table: 7 ERROR: missing FROM-clause entry for table "t" LINE 6: ... t.typtype ... ^. Failing Query: "SELECT ordinal_position as attnum, column_name as field, udt_name as type, data_type as complete_type, t.typtype AS typtype, is_nullable as isnotnull, column_default as default, ( SELECT 't' in D:\Doctrine-1.2.3\Doctrine-1.2.3\Doctrine\Connection.php on line 1082
It's worth to mention, this code is working perfectly for mysql (by having mysql:// ... in the connection ofcurse), but having trouble to get it working with postgresql 9.0.
Any idea?

Sounds like this bug in Doctrine: http://www.doctrine-project.org/jira/browse/DC-919

Try to add quotes to table name, or column names.
Find right naming while exporting a table.
My problem was that someone added quotes to table name.
$sql='SELECT "id","name",
("f1"=\'aaa\' OR
"f1"=\'bbb\') AS "myflag"
FROM "mytable"';

Related

Eloquent Date Query

I have a table (with soft delete) and it is a whats on table. There is a field which is just a date field with the start date.
What I am trying to do is use eloquent to get a list of what on today onwards, but my attempts throw an error:
$wo = App\WhatsOn::whereDate('startDate', '=>', date('Y-m-d') )->get();
The error I am getting is
Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '=> ? and whatson.deleted_at is null' at line 1 (SQL: select * from whatson where date(startDate) => 2019-05-05 and whatson.deleted_at is null)
Help greatly appreciated!
It should be:
$wo = App\WhatsOn::whereDate('startDate', '>=', date('Y-m-d') )->get();
Dumb mistake!

Pgsql error: You might need to add explicit type casts

My website is just working fine til i deployed it to heroku and the problem is heroku uses pgsql and I'm using mysql and laravel framework.
my query is
$patient = Patient::where('patient_address', 'ILIKE' ,'%' . $request->input)->where('patient_sex', 'ILIKE' ,'%' . $request->gender)->whereHas('users', function($q) use($vaccine_id){
$q->where('vaccine_id','ILIKE','%' . $vaccine_id);
})->get();
here's what I'm getting when I deploy it to heroku
SQLSTATE[42883]: Undefined function: 7 ERROR: operator does not exist: integer ~~* unknown
LINE 1: ...ient_id" = "patients"."PatientID" and "vaccine_id" ILIKE $3)
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. (SQL: select * from "patients" where "patient_address" ILIKE %San Francisco and "patient_sex" ILIKE % and exists (select * from "vaccines" inner join "immunizations" on "vaccines"."VaccineID" = "immunizations"."vaccine_id" where "immunizations"."patient_id" = "patients"."PatientID" and "vaccine_id" ILIKE %))
I have tried using cast like CAST(vaccine_id AS VARCHAR) and I' not getting the error but it doesnt return any result.
The problem is here:
$q->where('vaccine_id','ILIKE','%' . $vaccine_id)
looks like vaccine_id is integer, and you can not use operator ILIKE to integer. Try just '='
If you want to use LIKE, ILIKE or other text operator you must cast your data to text. In SQL it must looks like:
WHERE "vaccine_id"::text ILIKE val
instead
WHERE "vaccine_id" ILIKE val
You could do this:
$q->where('cast(vaccine_id AS VARCHAR)','LIKE','%' . $vaccine_id)
OR
$q->where('cast(vaccine_id AS TEXT)','LIKE','%' . $vaccine_id)

Get result of raw SQL query in Laravel 5 Eloquent

I need help to build a Laravel query from my raw SQL Query. I tried many way and did not find my Luck. Can anybody help me? My Raw SQL code is given bellow.
SELECT exams. * , count( question_details.exam_id ) AS qus_enter
FROM exams
INNER JOIN question_details ON exams.id = question_details.exam_id GROUP BY exams.id
This is what I've tried:
$examListsID = DB::table('exams')
->join('question_details', function($join) {
$join->on('exams.id', '=', 'question_details.exam_id as qus_enter');
})
->whereraw('count(qus_enter) = exams.total_question')
->select('exams.id as examID','qus_enter','exams.total_question')
->count('qus_enter')
->groupby('exams.id')
->get();
$examLists = Addexam::where('id','=',$examListsID->examID)
And I Get this Error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'as qus_enter where count(qus_enter) = exams.total_question' at line 1 (SQL: select count(qus_enter) as aggregate from exams inner join question_details on exams.id = question_details.exam_id as qus_enter where count(qus_enter) = exams.total_question)
$result = DB::table('exams')->join('question_details','exams.id','=','question_details.exam_id')->select([
exams.*,
DB::raw('count( question_details.exam_id ) AS qus_enter')
])->GroupBy('exams.id')->get()
Hope this helps
DB::listen(function ($data) {
var_dump($data->bindings);
dd($data->sql);
});

IF EXISTS not recognized in Derby

DROP TABLE IF EXISTS Pose ;
results in the error
Error code -1, SQL state 42X01: Syntax error: Encountered "EXISTS" at line 1, column 15.
I'm running this from inside NetBeans 7.3 using the default Derby sample db.
Derby does not currently support IF EXISTS
Are you trying to create a table? If yes, this is what you should do:
public void createTables() throws SQLException {
Statement statement = getConnection().createStatement();
System.out.println("Checking database for table");
DatabaseMetaData databaseMetadata = getConnection().getMetaData();
ResultSet resultSet = databaseMetadata.getTables(null, null, "PATIENT", null);
if (resultSet.next()) {
System.out.println("TABLE ALREADY EXISTS");
} else {
//language=MySQL
statement.execute("CREATE TABLE Patient (" +
"CardNumber CHAR(10) NOT NULL PRIMARY KEY, " +
" FirstName CHAR(50)," +
" MiddleName CHAR(50)," +
" LastName CHAR(50) )");
}
}
Remember to use all caps for the table name you pass into databaseMetadata.getTables(...)
The MySQL 6.0 syntax for declaring a table is this:
CREATE TABLE [IF NOT EXISTS] tableName ...
and the MySQL syntax for removing a table is this:
DROP TABLE [IF EXISTS] tableName ...
These clauses are MySQL extensions which are not part of the ANSI/ISO SQL Standard. This functionality may be peculiar to MySQL: I can't find anything similar documented for Derby, Postgres, Oracle, or DB2.
The best alternative I can find is to query the system tables to see if the table exists.
select count(*) from sys.systables where tablename = 'YOUR_TABLE_NAME'"
I had a similar issue dropping stored procedures. They can be queried using this statement.
select count(*) from sys.sysaliases where alias = 'YOUR_STORED_PROCEDURE_NAME'
If someone is looking to drop and create a table in an sql file that is Run with Spring test framework, Check https://stackoverflow.com/a/47459214/3584693 for an answer that ensures that no exception is thrown when drop table is invoked when said table doesn't exist.

PGSQL Error Code 42703 column does not exist

I have a database in postgreSQL. I want to read some data from there, but I get an error (column anganridref does not exist) when I execute my command.
Here is my NpgsqlCommand:
cmd.CommandText = "select * from angebot,angebotstatus,anrede where anrid=anganridref and anstaid=anganstaidref";
and my 3 tables
the names of my columns are rights. So I don't understand why that error comes. Someone can explain me why it does crash? Its not the problem of large and lowercase.
You are not prefixing your column names in the where clause:
select *
from angebot,
angebotstatus,
anrede
where anrid = anganridref <-- missing tablenames for the columns
and anstaid = anganstaidre
It's also recommended to use an explicit JOIN instead of the old SQL 89 implicit join syntax:
select *
from angebot
join angebotstatus on angebot.aaaa = angebotstatus.bbbb
join anrede on angebot.aaaa = anrede.bbbb