Skip to content

Commit

Permalink
Added new method to split_query used by execute method, complete with…
Browse files Browse the repository at this point in the history
… test that it splits properly when semicolons exist inside strings. ref pull ruckus#120 and issue ruckus#123 on github
  • Loading branch information
stilliard committed Apr 24, 2014
1 parent fe99fb6 commit 9144e55
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 4 deletions.
28 changes: 27 additions & 1 deletion lib/Ruckusing/Migration/Base.php
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,32 @@ public function create_table($table_name, $options = array())
return $this->_adapter->create_table($table_name, $options);
}

/**
* Split up multiple sql queries from a single query string
* @link http://stackoverflow.com/questions/4001797/how-to-break-queries-using-regex-in-php
* @param string $query The query to be split
* @return array Each query string found
*/
protected function split_query($query)
{
$open = false;
$buffer = null;
$parts = array();
for($i = 0, $l = strlen($query); $i < $l; $i++) {
if ($query[$i] == ';' && !$open) {
$parts[] = trim($buffer);
$buffer = null;
continue;
}
if ($query[$i] == "'") {
$open = ($open) ? false: true;
}
$buffer .= $query[$i];
}
if ($buffer) $parts[] = trim($buffer);
return $parts;
}

/**
* Execute a query
*
Expand All @@ -248,7 +274,7 @@ public function create_table($table_name, $options = array())
public function execute($query)
{
$result = null;
$queries = explode(';', $query);
$queries = $this->split_query($query);
foreach($queries as $query_s) {
$query_s = trim($query_s);
if (!empty($query_s)) {
Expand Down
20 changes: 17 additions & 3 deletions tests/unit/BaseMigrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,16 +101,30 @@ public function test_execute_multiple_queries()
) engine=innodb default charset=utf8 collate=utf8_unicode_ci;
");

// test first table
// test first table created ok
$col = $this->adapter->column_info("admin", "email");
$this->assertEquals("email", $col['field']);

// test second table
// test second table created ok
$col = $this->adapter->column_info("adminsession", "admin_id");
$this->assertEquals("admin_id", $col['field']);

// test multiple queries with a semicolon inside quotes
$base->execute("
DROP TABLE IF EXISTS `demo`;
CREATE TABLE `demo` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO demo(id, name) VALUES(1,'A;A');
INSERT INTO demo(id, name) VALUES(2,'b;b');
");
$rows = $this->adapter->select_all('SELECT * FROM demo');
$this->assertEquals(2, count($rows));

// cleanup
$base->execute("drop table `admin`; drop table `adminsession`;");
$base->execute("DROP TABLE `admin`; DROP TABLE `adminsession`; DROP TABLE `demo`;");

}
}

0 comments on commit 9144e55

Please sign in to comment.