Laravel - Where Condition on Multiple Database - php

I'm using laravel with multiple DB connection. Oracle and PostgreSQL. I can do query from both of instance.
But the problem is I have to look inside my Oracle DB WHERE NOT EXISTS on my postgreSQL.
This is my current Query :
DB::connection('ora')->table('ora_purch')
->whereExists(function($query)
{
$query->select(DB::connection('pgs')->raw(1))
->from('pg_purch')
->whereRaw('ora_purch.id = pg_purch.id');
})
->get();
From this query, I get error "database pg_purch is not exists". It's just like laravel reads pg_purch as an oracle instance.
I also do simulation with the same query and the same instance (multiple database on postgreSQL only), the query is fine and produces correct data.
Is it possible to makes the laravel reads pg_purch refer to the connection?
Or maybe i've missing something?
Please advise, thank you.

Your code generates query like this:
SELECT * FROM ora_purch WHERE EXISTS (SELECT 1 FROM pg_purch WHERE ora_purch.id = pg_purch.id);
And make it with "ora" connection, ignoring "pgs" connection.
You can't use multiple connections inside one query.
Try to split them:
$ids = DB::connection('pgs')->from('pg_purch')->pluck('id');
$result = DB::connection('ora')->from('ora_purch')->whereIn('id', $ids)->get();

Related

Selecting MySQL views using $wpdb class

I am building a Wordpress site and it is connected to a MySQL database. I am using the wordpress class wpdb (https://codex.wordpress.org/Class_Reference/wpdb) to interact with the database. With that class, I am able to query TABLES of my database, but not Views.
I need to be able to select Views of my database. Is this something that is not allowed with wpdb, or is my code just wrong? Is there a way to query views the same way I can query tables using wpdb?
I have tried using the query function, as well as treating a view the same way I treat a table, but it does not work. It returns empty.
Query method:
$test = $mydb->query(
$mydb->prepare(
"
SELECT name FROM $mydb->$view_name
WHERE id = 1"
)
);
echo $test; //returns empty; should return a name
Table method:
$test = $mydb->get_var(
"select name from $view_name WHERE id = 1"
);
echo $test; //returns empty; should return a name
Any suggestions? Am I able to connect to my database using something other than $wpdb (does Wordpress allow that?).
name seems to be a reserved word in MySQL (reference). Try surrounding it with back-ticks (`) like this:
SELECT `name` FROM ...
You should be seeing some errors, do you keep an eye on the logs? Also, when you have doubts in your queries, you can simply copy the raw query and execute it into phpMyAdmin or whatever tool you are using to access your database manually

Weird alias [0_ added by doctrine while trying to run with SQL SERVER

I'm trying to implement APYDataGridBundle on Symfony, with SQL Server. Symfony throws in this exception:
SQLSTATE[HY000]: General error: 105 General SQL Server error: Check messages from the SQL Server [105] (severity 15) [SELECT TOP 50 [0_.PI_PK AS PI_PK0, [0_.ProductName AS ProductName1, [0_.ProductDetails AS ProductDetails2 FROM [TSOFT_LEARN].[dbo].[tblProductDemo] [0_]
I tried:
$repo = $em->getRepository("ProductOrderLookupBundle:Product");
$product = $repo->findAll();
and everything worked fine, but it breaks for over 1 million records. Someone suggested to me to use APYDatagridBundle like here. I have tried ThraceDataGrid Bundle before and it gave me this same problem.
If I remove the "[0_" and everything worked fine while running the query on SQL Server.
Can anybody tell me what might be the problem?
Doctrine always create alias for tables in the generated queries. I always had the same kind of queries, i don't know if it can be disabled or not but better not because i don't know how it will react for joins , what you can do is to add a function in your repository :
public function getAllProducts(){
$qb = $this->_em->createQueryBuilder()
->select('partial p.{ /*add all fields needed separated by coma optimized for big queries get only whats needed */ }')
->from('Product', 'p');
$results = $qb->getQuery()->getResult();
return $results;
}
**SOLVED:**The problem was with how I defined my table names in the doctrine entities. I gave the name
[TSOFT_LEARN].[dbo].[tblOrders]
and it should be
TSOFT_LEARN.dbo.tblOrders
Because of that my alias was becoming [0_ instead of t0_. I suppose its how doctrine creates its aliases by taking the first character of the table name. Since the table name was starting with "[" the alias got converted to [0_.

Symfony2 - Show all tables from database

I would like to retrieve all the tables of my database as a list.
i tried to do a "Show databases" on a query but as i'm not using a class I defined (entity) in symfony it's not working.
And with DQL :
$em = $this->getDoctrine()->getEntityManager();
$query = $em->createQuery(
'show databases');
$result = $query->getResult();
This error :
[Syntax Error] line 0, col 0: Error: Expected SELECT, UPDATE or DELETE, got 'show'
Any idea to help me ?
As mentioned in a different answer, you can use Doctrine\DBAL for that:
/** #type \Doctrine\DBAL\Connection $connection */
$connection = ...;
/** #type \Doctrine\DBAL\Schema\MySqlSchemaManager $sm */
$sm = $connection->getSchemaManager();
And then just list the tables as Array:
var_dump( $sm->listDatabases() );
My 2 cents:
getContainer()->get('doctrine.dbal.default_connection')->getSchemaManager()->listTableNames()
This will give you an array of table names.
i have a couple cases where I need to use complex sql statements/functions that I just couldn't do in DQL. Luckily, Symfony2/doctrine provide a method to grab the current database connection and bypass doctrine entirely.
//get connection
$conn = $this->get('database_connection');
//run a query
$users= $conn->fetchAll('select * from users');
Be very careful when using this method, however. Since you are bypassing doctrine, you need to handle any security concerns like SQL injection yourself.
You can add Doctrine DBAL to your project and it will give you the tools you need. You can list databases, tables from a database, columns from a table etc etc
More in Doctrine DBAL documentation: http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/schema-manager.html
Doctrine is a ORM, it is not intended to list all the databases. Beside that, usually for the current user you don't have the right to show all databases in the server, this can prove to be a big security breach.
Basicly, doctrine does not know how to interpret your query, you have to use a native query for this: Doctrine Native Query

CREATE and DROP TABLE using Zend Adapter

I'm trying to do some SQL queries using Zend adapter. The code that I'm trying to use is something like this:
$result = $this->$db->getConnection()->exec('CREATE TABLE TEST');
and I know that $db is set and works properly, because I can run other commands such as
$this->$db->listTables(); or
$result = $this->$db->fetchAssoc("SHOW COLUMNS FROM " .$schema);
As I was reading through Zend documentation, it was mentioned that some database transactions that are not prepared should be used through the first example (e.g. exec("...") ), but apparently I have problems running those.
Any thoughts?
This should work ...
$db = Zend_Db_Table::getDefaultAdapter();
$db->query('CREATE TABLE wolf (tag VARCHAR(9))');

doctrine2 native query update statement

How to do a native sql query in Doctrine 2, executing an update statement?
The createNativeQuery method on EntityManager, requires a second parameter (ResultSetMapping) to be able to map the resultsets to Objects.
But when updating (or inserting, or set, or...) there is no resulset to map.
Passing null or just new ResultSetMapping(), gives an error.
Are only select queries supported for native sql?
Essentially ditto w/ faken,
this from the docs:
If you want to execute DELETE, UPDATE or INSERT statements the Native
SQL API cannot be used and will probably throw errors. Use
EntityManager#getConnection() to access the native database connection
and call the executeUpdate() method for these queries.
one note of use is the connection object can be retrieved from the EntityManager:
$conn = $entityManager->getConnection();
$rowsAffected = $conn->executeUpdate($sql, $params, $types);
Update statements are usually pretty simple, so you might as well use the normal Doctrine2 way (i.e. programmatically updating entities and calling EntityManager::flush() OR using DQL Updates).
Having said this, if you really want to use normal SQL, you could always do it like this:
Keep the db connection object you get when creating a connection with Doctrine2:
$connection = \Doctrine\DBAL\DriverManager::getConnection($dbConfig->toArray(),null,$evm);
Execute whatever SQL you want, using the available methods in the connection object, e.g.:
$connection->executeUpdate($sql, $params, $types);
$connection->exec($sql);
...

Categories