Browse files

Possible use tables from other db in FROM or JOIN

If you want to join table from other database you need use
innerJoin() or leftJoin() functions. You cannot use "smart join builder",
because it is impossible to detect if it is other database or table
from primary database. See tests (28,29)
  • Loading branch information...
1 parent 7824ac6 commit 68b42a9afad603e77ec326b6a482d8bc3519911e @lichtner lichtner committed May 22, 2012
Showing with 46 additions and 0 deletions.
  1. +13 −0 FluentPDO.php
  2. +15 −0 tests/28-from-other-db.phpt
  3. +18 −0 tests/29-join-table-from-other-db.phpt
View
13 FluentPDO.php
@@ -96,6 +96,7 @@ class FluentQuery implements IteratorAggregate {
/** @var FluentPDO */
private $fpdo;
private $clauses = array(), $statements = array(), $parameters = array();
+ /** @var array of used tables (also include table from clause FROM) */
private $joins = array();
/** @var PDOStatement */
private $result;
@@ -108,6 +109,7 @@ function __construct(FluentPDO $fpdo, $from) {
$this->createSelectClauses();
$this->statements['FROM'] = $from;
$this->statements['SELECT'][] = "$from.*";
+ $this->joins[] = $from;
}
function getPDO() {
@@ -194,6 +196,9 @@ private function addJoinStatements($clause, $statement, $parameters = array()) {
$this->joins = array();
return $this->resetClause('JOIN');
}
+ if (array_search(substr($statement, 0, -1), $this->joins) !== FALSE) {
+ return;
+ }
# match "tables AS alias"
preg_match('~([a-z_][a-z0-9_\.:]*)(\s+AS)?(\s+([a-z_][a-z0-9_]*))?~i', $statement, $matches);
@@ -465,6 +470,14 @@ private function createUndefinedJoins($statement) {
$this->addJoinStatements('LEFT JOIN', $join);
}
}
+
+ # don't rewrite table from other databases
+ foreach ($this->joins as $join) {
+ if (strpos($join, '.') !== FALSE && strpos($statement, $join) === 0) {
+ return $statement;
+ }
+ }
+
# remove extra referenced tables (rewrite tab1.tab2:col => tab2.col)
$statement = preg_replace('~(?:\\b[a-z_][a-z0-9_.:]*[.:])?([a-z_][a-z0-9_]*)[.:]([a-z_*])~i', '\\1.\\2', $statement);
return $statement;
View
15 tests/28-from-other-db.phpt
@@ -0,0 +1,15 @@
+--TEST--
+FROM table from other database
+--FILE--
+<?php
+include_once dirname(__FILE__) . "/connect.inc.php";
+/* @var $fpdo FluentPDO */
+
+$query = $fpdo->from('db2.user')->order('db2.user.name')->getQuery();
+echo "$query\n";
+
+?>
+--EXPECTF--
+SELECT db2.user.*
+FROM db2.user
+ORDER BY db2.user.name
View
18 tests/29-join-table-from-other-db.phpt
@@ -0,0 +1,18 @@
+--TEST--
+FROM table from other database
+--FILE--
+<?php
+include_once dirname(__FILE__) . "/connect.inc.php";
+/* @var $fpdo FluentPDO */
+
+$query = $fpdo->from('user')
+ ->innerJoin('db2.types ON db2.types.id = user.type')
+ ->select('db2.types.*')
+ ->getQuery();
+echo "$query\n";
+
+?>
+--EXPECTF--
+SELECT user.*, db2.types.*
+FROM user
+ INNER JOIN db2.types ON db2.types.id = user.type

0 comments on commit 68b42a9

Please sign in to comment.