Skip to content

Commit

Permalink
#38 - updated the ActiveRecordProviderSQLite class to handle creating…
Browse files Browse the repository at this point in the history
… missing foreign keys from the checkIndexes() method once they are found
  • Loading branch information
alphadevx committed May 1, 2018
1 parent f78f5f0 commit 2bd525b
Show file tree
Hide file tree
Showing 6 changed files with 72 additions and 17 deletions.
2 changes: 1 addition & 1 deletion Alpha/Controller/InstallController.php
Expand Up @@ -298,7 +298,7 @@ public function doGET($request)
ActiveRecord::commit();

self::$logger->info('Finished installation!');
self::$logger->action('Installed the application');
self::$logger->info('Installed the application');
self::$logger->debug('<<doGET');

return new Response(200, $body, array('Content-Type' => 'text/html'));
Expand Down
4 changes: 2 additions & 2 deletions Alpha/Model/ActiveRecord.php
Expand Up @@ -882,7 +882,7 @@ public function getVersion()
*
* @throws \Alpha\Exception\AlphaException
*/
public function makeTable()
public function makeTable($checkIndexes = true)
{
self::$logger->debug('>>makeTable()');

Expand All @@ -894,7 +894,7 @@ public function makeTable()

$provider = ServiceFactory::getInstance($config->get('db.provider.name'), 'Alpha\Model\ActiveRecordProviderInterface');
$provider->setRecord($this);
$provider->makeTable();
$provider->makeTable($checkIndexes);

if (method_exists($this, 'after_makeTable_callback')) {
$this->{'after_makeTable_callback'}();
Expand Down
6 changes: 4 additions & 2 deletions Alpha/Model/ActiveRecordProviderMySQL.php
Expand Up @@ -1233,7 +1233,7 @@ public function getVersion()
*
* @see Alpha\Model\ActiveRecordProviderInterface::makeTable()
*/
public function makeTable()
public function makeTable($checkIndexes = true)
{
self::$logger->debug('>>makeTable()');

Expand Down Expand Up @@ -1298,7 +1298,9 @@ public function makeTable()
}

// check the table indexes if any additional ones required
$this->checkIndexes();
if ($checkIndexes) {
$this->checkIndexes();
}

if ($this->record->getMaintainHistory()) {
$this->record->makeHistoryTable();
Expand Down
71 changes: 61 additions & 10 deletions Alpha/Model/ActiveRecordProviderSQLite.php
Expand Up @@ -913,7 +913,7 @@ public function save()
$stmt->execute();
} catch (Exception $e) {
if (self::getConnection()->lastErrorCode() == 19) {
throw new ValidationException('Unique key violation while trying to save object, SQLite error is ['.self::getLastDatabaseError().'], query ['.$this->record->getLastQuery().']');
throw new ValidationException('Unique key violation while trying to save object, exception ['.$e->getMessage().'], SQLite error is ['.self::getLastDatabaseError().'], query ['.$this->record->getLastQuery().']');
} else {
throw new FailedSaveException('Failed to save object, exception ['.$e->getMessage().'], DB error is ['.self::getLastDatabaseError().'], query ['.$this->record->getLastQuery().']');
}
Expand Down Expand Up @@ -1274,7 +1274,7 @@ public function getVersion()
*
* @see Alpha\Model\ActiveRecordProviderInterface::makeTable()
*/
public function makeTable()
public function makeTable($checkIndexes = true)
{
self::$logger->debug('>>makeTable()');

Expand Down Expand Up @@ -1358,7 +1358,9 @@ public function makeTable()
}

// check the table indexes if any additional ones required
$this->checkIndexes();
if ($checkIndexes) {
$this->checkIndexes();
}

if ($this->record->getMaintainHistory()) {
$this->record->makeHistoryTable();
Expand Down Expand Up @@ -2005,6 +2007,58 @@ private function checkIndexes()
}
}

// process foreign-key indexes
// get the class attributes
$reflection = new ReflectionClass(get_class($this->record));
$properties = $reflection->getProperties();
foreach ($properties as $propObj) {
$propName = $propObj->name;
$prop = $this->record->getPropObject($propName);
if ($prop instanceof Relation) {
if ($prop->getRelationType() == 'MANY-TO-ONE') {
$indexExists = false;
foreach ($indexNames as $index) {
if ($this->record->getTableName().'_'.$propName.'_fk_idx' == $index) {
$indexExists = true;
}
}
if (!$indexExists) {
$this->createForeignIndex($propName, $prop->getRelatedClass(), $prop->getRelatedClassField());
}
}
if ($prop->getRelationType() == 'MANY-TO-MANY') {
$lookup = $prop->getLookup();
if ($lookup != null) {
try {
$lookupIndexNames = $lookup->getIndexes();
// handle index check/creation on left side of Relation
$indexExists = false;
foreach ($lookupIndexNames as $index) {
if ($lookup->getTableName().'_leftID_fk_idx' == $index) {
$indexExists = true;
}
}
if (!$indexExists) {
$lookup->createForeignIndex('leftID', $prop->getRelatedClass('left'), 'ID');
}
// handle index check/creation on right side of Relation
$indexExists = false;
foreach ($lookupIndexNames as $index) {
if ($lookup->getTableName().'_rightID_fk_idx' == $index) {
$indexExists = true;
}
}
if (!$indexExists) {
$lookup->createForeignIndex('rightID', $prop->getRelatedClass('right'), 'ID');
}
} catch (AlphaException $e) {
self::$logger->error($e->getMessage());
}
}
}
}
}

self::$logger->debug('<<checkIndexes');
}

Expand All @@ -2028,8 +2082,6 @@ public function createForeignIndex($attributeName, $relatedClass, $relatedClassA
* 4. Drop [tablename]_temp.
*/
try {
ActiveRecord::begin($this->record);

// rename the table to [tablename]_temp
$query = 'ALTER TABLE '.$this->record->getTableName().' RENAME TO '.$this->record->getTableName().'_temp;';
$this->record->setLastQuery($query);
Expand All @@ -2042,7 +2094,9 @@ public function createForeignIndex($attributeName, $relatedClass, $relatedClassA
$tableName = $record->getTableName();
$this->foreignKeys[$attributeName] = array($tableName, $relatedClassAttribute);

$this->makeTable();
if (!$this->checkTableExists()) {
$this->makeTable(false);
}

self::$logger->info('Made a new copy of the table ['.$this->record->getTableName().']');

Expand All @@ -2057,11 +2111,7 @@ public function createForeignIndex($attributeName, $relatedClass, $relatedClassA
$this->record->dropTable($this->record->getTableName().'_temp');

self::$logger->info('Dropped the table ['.$this->record->getTableName().'_temp]');

ActiveRecord::commit($this->record);
} catch (Exception $e) {
ActiveRecord::rollback($this->record);

throw new FailedIndexCreateException('Failed to create the index ['.$attributeName.'] on ['.$this->record->getTableName().'], error is ['.$e->getMessage().'], query ['.$this->record->getLastQuery().']');
}

Expand Down Expand Up @@ -2320,6 +2370,7 @@ public static function createDatabase()

if (!self::checkDatabaseExists()) {
fopen($config->get('db.file.path'), 'x+');
chmod($config->get('db.file.path'), 0755);
}
}

Expand Down
2 changes: 1 addition & 1 deletion config/test.ini
Expand Up @@ -214,7 +214,7 @@ security.encrypt.http.fieldnames = false
security.http.header.x.frame.options = DENY

; The class name of the session provider to use
session.provider.name = "Alpha\Util\Http\Session\SessionProviderPHP"
session.provider.name = "Alpha\Util\Http\Session\SessionProviderArray"

; --------------
; Email Settings
Expand Down
4 changes: 3 additions & 1 deletion test/Alpha/Test/Controller/InstallControllerTest.php
Expand Up @@ -64,6 +64,7 @@ protected function setup()
$config->set('app.file.store.dir', $testInstallDir.'/store/');
$config->set('db.file.path', $testInstallDir.'/unittests.db');
$config->set('db.file.test.path', $testInstallDir.'/unittests.db');
ActiveRecord::disconnect();

if (!file_exists($testInstallDir)) {
mkdir($testInstallDir);
Expand All @@ -80,7 +81,7 @@ protected function setup()
$person->set('password', 'testpassword');

$sessionProvider = $config->get('session.provider.name');
$session = ServiceFactory::getInstance($sessionProvider, 'Alpha\Util\Http\Session\SessionProviderInterface');
$session = ServiceFactory::getInstance('Alpha\Util\Http\Session\SessionProviderArray', 'Alpha\Util\Http\Session\SessionProviderInterface');
$session->set('currentUser', $person);
}

Expand All @@ -90,6 +91,7 @@ protected function teardown()
$config->set('app.root', '');
$config->set('app.file.store.dir', '/tmp/');
$config->set('db.file.path', '/tmp/unittests.db');
ActiveRecord::disconnect();
}

/**
Expand Down

0 comments on commit 2bd525b

Please sign in to comment.