Browse Source

Set a default type for queries.

By not having a default query type, the sql() method would fatally error
if you had not called select() or a similar method before hand. This
change also impacts the SQLite driver as it does tricky things with
unions to simulate multi-inserts.

This also fixes strange errors when matching() callbacks trigger errors.

Refs #3697
mark_story 11 years ago
parent
commit
5fee0c60de

+ 3 - 1
src/Database/Dialect/SqliteDialectTrait.php

@@ -113,6 +113,7 @@ trait SqliteDialectTrait {
 
 		$newQuery = $query->connection()->newQuery();
 		$cols = $v->columns();
+		$replaceQuery = false;
 		foreach ($v->values() as $k => $val) {
 			$fillLength = count($cols) - count($val);
 			if ($fillLength > 0) {
@@ -124,6 +125,7 @@ trait SqliteDialectTrait {
 
 			$select = array_combine($cols, $val);
 			if ($k === 0) {
+				$replaceQuery = true;
 				$newQuery->select($select);
 				continue;
 			}
@@ -132,7 +134,7 @@ trait SqliteDialectTrait {
 			$newQuery->unionAll($q->select($select));
 		}
 
-		if ($newQuery->type()) {
+		if ($replaceQuery) {
 			$v->query($newQuery);
 		}
 

+ 1 - 1
src/Database/Query.php

@@ -47,7 +47,7 @@ class Query implements ExpressionInterface, IteratorAggregate {
  *
  * @var string
  */
-	protected $_type;
+	protected $_type = 'select';
 
 /**
  * List of SQL parts that will be used to build this query.

+ 12 - 0
tests/TestCase/Database/QueryTest.php

@@ -45,6 +45,18 @@ class QueryTest extends TestCase {
 	}
 
 /**
+ * Queries need a default type to prevent fatal errors
+ * when an uninitialized query has its sql() method called.
+ *
+ * @return void
+ */
+	public function testDefaultType() {
+		$query = new Query($this->connection);
+		$this->assertEquals('', $query->sql());
+		$this->assertEquals('select', $query->type());
+	}
+
+/**
  * Tests that it is possible to obtain expression results from a query
  *
  * @return void