repo
stringlengths 5
75
| commit
stringlengths 40
40
| message
stringlengths 6
18.2k
| diff
stringlengths 60
262k
|
---|---|---|---|
sirprize/xdoctrine | c4fa4247fead2dca6f60f84a175ca111ae8a05c3 | remove require\s | diff --git a/lib/Xdoctrine/Common/Cache/ZendCache.php b/lib/Xdoctrine/Common/Cache/ZendCache.php
index 8c71657..440888d 100644
--- a/lib/Xdoctrine/Common/Cache/ZendCache.php
+++ b/lib/Xdoctrine/Common/Cache/ZendCache.php
@@ -1,93 +1,93 @@
<?php
/**
* Xdoctrine - Sirprize's Doctrine2 Extensions
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
*
* @package Xzend
* @copyright Copyright (c) 2009, Christian Hoegl, Switzerland (http://sitengine.org)
* @license http://sitengine.org/license/new-bsd New BSD License
*/
namespace Xdoctrine\Common\Cache;
-require_once 'Doctrine/Common/Cache/AbstractCache.php';
+#require_once 'Doctrine/Common/Cache/AbstractCache.php';
class ZendCache extends \Doctrine\Common\Cache\AbstractCache
{
/**
* @var \Zend_Cache_Core
*/
private $_zendCache;
/**
* Sets the \Zend_Cache_Core instance to use.
*
* @param \Zend_Cache_Core $zendCache
*/
public function setZendCache(\Zend_Cache_Core $zendCache)
{
$this->_zendCache = $zendCache;
}
/**
* Gets the \Zend_Cache_Core instance used by the cache.
*
* @return \Zend_Cache_Core
*/
public function getZendCache()
{
return $this->_zendCache;
}
/**
* {@inheritdoc}
*/
protected function _doFetch($id)
{
return $this->_zendCache->load($this->_prepareId($id));
}
/**
* {@inheritdoc}
*/
protected function _doContains($id)
{
return (bool) $this->_zendCache->test($this->_prepareId($id));
}
/**
* {@inheritdoc}
*/
protected function _doSave($id, $data, $lifeTime = false)
{
return $this->_zendCache->save($data, $this->_prepareId($id), array(), $lifeTime);
}
/**
* {@inheritdoc}
*/
protected function _doDelete($id)
{
return $this->_zendCache->remove($this->_prepareId($id));
}
protected function _prepareId($id)
{
return preg_replace('/[^a-zA-Z0-9_]/', '_', $id);
}
public function getIds()
{
return $this->_zendCache->getIds();
}
}
\ No newline at end of file
diff --git a/lib/Xdoctrine/DBAL/Logging/ZendSQLLogger.php b/lib/Xdoctrine/DBAL/Logging/ZendSQLLogger.php
index 295f0ea..ba97060 100644
--- a/lib/Xdoctrine/DBAL/Logging/ZendSQLLogger.php
+++ b/lib/Xdoctrine/DBAL/Logging/ZendSQLLogger.php
@@ -1,72 +1,72 @@
<?php
/**
* Xdoctrine - Sirprize's Doctrine2 Extensions
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
*
* @package Xzend
* @copyright Copyright (c) 2009, Christian Hoegl, Switzerland (http://sitengine.org)
* @license http://sitengine.org/license/new-bsd New BSD License
*/
namespace Xdoctrine\DBAL\Logging;
-require_once 'Doctrine/DBAL/Logging/SQLLogger.php';
+#require_once 'Doctrine/DBAL/Logging/SQLLogger.php';
class ZendSQLLogger implements \Doctrine\DBAL\Logging\SQLLogger
{
/**
* @var \Zend_Log
*/
private $_zendLog;
/**
* Sets the \Zend_Log instance to use.
*
* @param \Zend_Log $zendLog
*/
public function setZendLog(\Zend_Log $zendLog)
{
$this->_zendLog = $zendLog;
}
/**
* Gets the \Zend_Log instance used by the cache.
*
* @return \Zend_Log
*/
public function getZendLog()
{
return $this->_zendLog;
}
public function startQuery($sql, array $params = null, array $types = null)
{
$p = '';
foreach($params as $k => $v)
{
if(is_object($v))
{
continue;
}
$p .= (($p) ? ', ' : '').$k.' => '.$v;
}
$this->getZendLog()->debug($sql);
$this->getZendLog()->debug("PARAMS: $p");
}
public function stopQuery()
{}
}
\ No newline at end of file
diff --git a/lib/Xdoctrine/ORM/Event/Listener/Abstrakt.php b/lib/Xdoctrine/ORM/Event/Listener/Abstrakt.php
index 9bbec9b..36184f6 100644
--- a/lib/Xdoctrine/ORM/Event/Listener/Abstrakt.php
+++ b/lib/Xdoctrine/ORM/Event/Listener/Abstrakt.php
@@ -1,121 +1,121 @@
<?php
/**
* Xdoctrine - Sirprize's Doctrine2 Extensions
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
*
* @package Xzend
* @copyright Copyright (c) 2009, Christian Hoegl, Switzerland (http://sitengine.org)
* @license http://sitengine.org/license/new-bsd New BSD License
*/
namespace Xdoctrine\Orm\Event\Listener;
-require_once 'Xdoctrine/ORM/Event/Listener/Interfaze.php';
+#require_once 'Xdoctrine/ORM/Event/Listener/Interfaze.php';
abstract class Abstrakt implements \Xdoctrine\ORM\Event\Listener\Interfaze
{
protected $_queue = array();
protected $_entityClassName = null;
protected $_events = array();
public function __construct($entityClassName)
{
$this->_entityClassName = $entityClassName;
}
public function getEvents()
{
return $this->_events;
}
public function getQueue()
{
return $this->_queue;
}
public function isQueued($id)
{
return isset($this->_queue[$id]);
}
public function hasError($id)
{
return (isset($this->_queue[$id]) && $this->_queue[$id] == 0);
}
public function isFlushOk()
{
foreach($this->_queue as $item)
{
if($item == 0)
{
return false;
}
}
return true;
}
public function isFlushError()
{
foreach($this->_queue as $item)
{
if($item == 0)
{
return true;
}
}
return false;
}
public function countFlushOks()
{
$ok = 0;
foreach($this->_queue as $item)
{
if($item == 1)
{
$ok++;
}
}
return $ok;
}
public function countFlushErrors()
{
$errors = 0;
foreach($this->_queue as $item)
{
if($item == 0)
{
$errors++;
}
}
return $errors;
}
}
\ No newline at end of file
diff --git a/lib/Xdoctrine/ORM/Event/Listener/Persists.php b/lib/Xdoctrine/ORM/Event/Listener/Persists.php
index e406b4e..f152613 100644
--- a/lib/Xdoctrine/ORM/Event/Listener/Persists.php
+++ b/lib/Xdoctrine/ORM/Event/Listener/Persists.php
@@ -1,50 +1,50 @@
<?php
/**
* Xdoctrine - Sirprize's Doctrine2 Extensions
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
*
* @package Xzend
* @copyright Copyright (c) 2009, Christian Hoegl, Switzerland (http://sitengine.org)
* @license http://sitengine.org/license/new-bsd New BSD License
*/
namespace Xdoctrine\ORM\Event\Listener;
-require_once 'Xdoctrine/ORM/Event/Listener/Abstrakt.php';
+#require_once 'Xdoctrine/ORM/Event/Listener/Abstrakt.php';
class Persists extends \Xdoctrine\ORM\Event\Listener\Abstrakt
{
protected $_events = array(
\Doctrine\ORM\Events::prePersist,
\Doctrine\ORM\Events::postPersist
);
public function prePersist(\Doctrine\ORM\Event\LifecycleEventArgs $eventArgs)
{
if($eventArgs->getEntity() instanceof $this->_entityClassName)
{
$this->_queue[$eventArgs->getEntity()->getId()] = 0;
}
}
public function postPersist(\Doctrine\ORM\Event\LifecycleEventArgs $eventArgs)
{
if($eventArgs->getEntity() instanceof $this->_entityClassName)
{
$this->_queue[$eventArgs->getEntity()->getId()] = 1;
}
}
}
\ No newline at end of file
diff --git a/lib/Xdoctrine/ORM/Event/Listener/Removes.php b/lib/Xdoctrine/ORM/Event/Listener/Removes.php
index e5d69de..1c1a6e1 100644
--- a/lib/Xdoctrine/ORM/Event/Listener/Removes.php
+++ b/lib/Xdoctrine/ORM/Event/Listener/Removes.php
@@ -1,50 +1,50 @@
<?php
/**
* Xdoctrine - Sirprize's Doctrine2 Extensions
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
*
* @package Xzend
* @copyright Copyright (c) 2009, Christian Hoegl, Switzerland (http://sitengine.org)
* @license http://sitengine.org/license/new-bsd New BSD License
*/
namespace Xdoctrine\ORM\Event\Listener;
-require_once 'Xdoctrine/ORM/Event/Listener/Abstrakt.php';
+#require_once 'Xdoctrine/ORM/Event/Listener/Abstrakt.php';
class Removes extends \Xdoctrine\ORM\Event\Listener\Abstrakt
{
protected $_events = array(
\Doctrine\ORM\Events::preRemove,
\Doctrine\ORM\Events::postRemove
);
public function preRemove(\Doctrine\ORM\Event\LifecycleEventArgs $eventArgs)
{
if($eventArgs->getEntity() instanceof $this->_entityClassName)
{
$this->_queue[$eventArgs->getEntity()->getId()] = 0;
}
}
public function postRemove(\Doctrine\ORM\Event\LifecycleEventArgs $eventArgs)
{
if($eventArgs->getEntity() instanceof $this->_entityClassName)
{
$this->_queue[$eventArgs->getEntity()->getId()] = 1;
}
}
}
\ No newline at end of file
diff --git a/lib/Xdoctrine/ORM/Event/Listener/Updates.php b/lib/Xdoctrine/ORM/Event/Listener/Updates.php
index 2f11140..c845fcb 100644
--- a/lib/Xdoctrine/ORM/Event/Listener/Updates.php
+++ b/lib/Xdoctrine/ORM/Event/Listener/Updates.php
@@ -1,50 +1,50 @@
<?php
/**
* Xdoctrine - Sirprize's Doctrine2 Extensions
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
*
* @package Xzend
* @copyright Copyright (c) 2009, Christian Hoegl, Switzerland (http://sitengine.org)
* @license http://sitengine.org/license/new-bsd New BSD License
*/
namespace Xdoctrine\ORM\Event\Listener;
-require_once 'Xdoctrine/ORM/Event/Listener/Abstrakt.php';
+#require_once 'Xdoctrine/ORM/Event/Listener/Abstrakt.php';
class Updates extends \Xdoctrine\ORM\Event\Listener\Abstrakt
{
protected $_events = array(
\Doctrine\ORM\Events::preUpdate,
\Doctrine\ORM\Events::postUpdate
);
public function preUpdate(\Doctrine\ORM\Event\PreUpdateEventArgs $eventArgs)
{
if($eventArgs->getEntity() instanceof $this->_entityClassName)
{
$this->_queue[$eventArgs->getEntity()->getId()] = 0;
}
}
public function postUpdate(\Doctrine\ORM\Event\LifecycleEventArgs $eventArgs)
{
if($eventArgs->getEntity() instanceof $this->_entityClassName)
{
$this->_queue[$eventArgs->getEntity()->getId()] = 1;
}
}
}
\ No newline at end of file
|
sirprize/xdoctrine | 221430b10d581fa7dc157a14954454269218ef8b | rollout changes of doctrine upgrade to doctrine 2.0.0BETA4 | diff --git a/lib/Xdoctrine/DBAL/Logging/ZendSQLLogger.php b/lib/Xdoctrine/DBAL/Logging/ZendSQLLogger.php
index a8b9dde..295f0ea 100644
--- a/lib/Xdoctrine/DBAL/Logging/ZendSQLLogger.php
+++ b/lib/Xdoctrine/DBAL/Logging/ZendSQLLogger.php
@@ -1,67 +1,72 @@
<?php
/**
* Xdoctrine - Sirprize's Doctrine2 Extensions
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
*
* @package Xzend
* @copyright Copyright (c) 2009, Christian Hoegl, Switzerland (http://sitengine.org)
* @license http://sitengine.org/license/new-bsd New BSD License
*/
namespace Xdoctrine\DBAL\Logging;
require_once 'Doctrine/DBAL/Logging/SQLLogger.php';
class ZendSQLLogger implements \Doctrine\DBAL\Logging\SQLLogger
{
/**
* @var \Zend_Log
*/
private $_zendLog;
/**
* Sets the \Zend_Log instance to use.
*
* @param \Zend_Log $zendLog
*/
public function setZendLog(\Zend_Log $zendLog)
{
$this->_zendLog = $zendLog;
}
/**
* Gets the \Zend_Log instance used by the cache.
*
* @return \Zend_Log
*/
public function getZendLog()
{
return $this->_zendLog;
}
- function logSQL($sql, array $params = null)
+
+ public function startQuery($sql, array $params = null, array $types = null)
{
$p = '';
foreach($params as $k => $v)
{
if(is_object($v))
{
continue;
}
$p .= (($p) ? ', ' : '').$k.' => '.$v;
}
$this->getZendLog()->debug($sql);
$this->getZendLog()->debug("PARAMS: $p");
}
+
+
+ public function stopQuery()
+ {}
}
\ No newline at end of file
|
sirprize/xdoctrine | d16226a3ebda3d54de54ae28074e9631df7b36d1 | rolling forward | diff --git a/lib/Xdoctrine/ORM/Event/Listener/Abstrakt.php b/lib/Xdoctrine/ORM/Event/Listener/Abstrakt.php
index 2bec875..9bbec9b 100644
--- a/lib/Xdoctrine/ORM/Event/Listener/Abstrakt.php
+++ b/lib/Xdoctrine/ORM/Event/Listener/Abstrakt.php
@@ -1,154 +1,121 @@
<?php
/**
* Xdoctrine - Sirprize's Doctrine2 Extensions
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
*
* @package Xzend
* @copyright Copyright (c) 2009, Christian Hoegl, Switzerland (http://sitengine.org)
* @license http://sitengine.org/license/new-bsd New BSD License
*/
namespace Xdoctrine\Orm\Event\Listener;
-abstract class Abstrakt
+require_once 'Xdoctrine/ORM/Event/Listener/Interfaze.php';
+
+
+abstract class Abstrakt implements \Xdoctrine\ORM\Event\Listener\Interfaze
{
protected $_queue = array();
protected $_entityClassName = null;
protected $_events = array();
public function __construct($entityClassName)
{
$this->_entityClassName = $entityClassName;
}
- /*
- public function isRegistered(\Doctrine\Common\EventManager $eventManager)
- {
- return ($this->getRegisteredInstance($eventManager) !== null);
- }
-
-
- public function getRegisteredInstance(\Doctrine\Common\EventManager $eventManager)
- {
- foreach($this->_events as $event)
- {
- if($eventManager->hasListeners($event))
- {
- foreach($eventManager->getListeners($event) as $listener)
- {
- if($listener instanceof $this)
- {
- return $listener;
- }
- }
- }
- }
-
- return null;
- }
-
-
- public function register(\Doctrine\Common\EventManager $eventManager)
- {
- #if(!$this->isRegistered($eventManager))
- #{
- $eventManager->addEventListener($this->_events, $this);
- return $this;
- #}
- }
- */
public function getEvents()
{
return $this->_events;
}
public function getQueue()
{
return $this->_queue;
}
public function isQueued($id)
{
return isset($this->_queue[$id]);
}
public function hasError($id)
{
return (isset($this->_queue[$id]) && $this->_queue[$id] == 0);
}
public function isFlushOk()
{
foreach($this->_queue as $item)
{
if($item == 0)
{
return false;
}
}
return true;
}
public function isFlushError()
{
foreach($this->_queue as $item)
{
if($item == 0)
{
return true;
}
}
return false;
}
public function countFlushOks()
{
$ok = 0;
foreach($this->_queue as $item)
{
if($item == 1)
{
$ok++;
}
}
return $ok;
}
public function countFlushErrors()
{
$errors = 0;
foreach($this->_queue as $item)
{
if($item == 0)
{
$errors++;
}
}
return $errors;
}
}
\ No newline at end of file
diff --git a/lib/Xdoctrine/ORM/Event/Listener/Interfaze.php b/lib/Xdoctrine/ORM/Event/Listener/Interfaze.php
new file mode 100644
index 0000000..c09e745
--- /dev/null
+++ b/lib/Xdoctrine/ORM/Event/Listener/Interfaze.php
@@ -0,0 +1,24 @@
+<?php
+
+/**
+ * Xdoctrine - Sirprize's Doctrine2 Extensions
+ *
+ * LICENSE
+ *
+ * This source file is subject to the new BSD license that is bundled
+ * with this package in the file LICENSE.txt.
+ *
+ * @package Xzend
+ * @copyright Copyright (c) 2009, Christian Hoegl, Switzerland (http://sitengine.org)
+ * @license http://sitengine.org/license/new-bsd New BSD License
+ */
+
+namespace Xdoctrine\Orm\Event\Listener;
+
+
+interface Interfaze
+{
+
+ public function getEvents();
+
+}
\ No newline at end of file
|
sirprize/xdoctrine | c5361816db9deffa71563b9b85a5781e0c655d18 | initial import | diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..496ee2c
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+.DS_Store
\ No newline at end of file
diff --git a/lib/Xdoctrine/Common/Cache/ZendCache.php b/lib/Xdoctrine/Common/Cache/ZendCache.php
new file mode 100644
index 0000000..8c71657
--- /dev/null
+++ b/lib/Xdoctrine/Common/Cache/ZendCache.php
@@ -0,0 +1,93 @@
+<?php
+
+/**
+ * Xdoctrine - Sirprize's Doctrine2 Extensions
+ *
+ * LICENSE
+ *
+ * This source file is subject to the new BSD license that is bundled
+ * with this package in the file LICENSE.txt.
+ *
+ * @package Xzend
+ * @copyright Copyright (c) 2009, Christian Hoegl, Switzerland (http://sitengine.org)
+ * @license http://sitengine.org/license/new-bsd New BSD License
+ */
+
+
+namespace Xdoctrine\Common\Cache;
+
+
+require_once 'Doctrine/Common/Cache/AbstractCache.php';
+
+
+class ZendCache extends \Doctrine\Common\Cache\AbstractCache
+{
+ /**
+ * @var \Zend_Cache_Core
+ */
+ private $_zendCache;
+
+ /**
+ * Sets the \Zend_Cache_Core instance to use.
+ *
+ * @param \Zend_Cache_Core $zendCache
+ */
+ public function setZendCache(\Zend_Cache_Core $zendCache)
+ {
+ $this->_zendCache = $zendCache;
+ }
+
+ /**
+ * Gets the \Zend_Cache_Core instance used by the cache.
+ *
+ * @return \Zend_Cache_Core
+ */
+ public function getZendCache()
+ {
+ return $this->_zendCache;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ protected function _doFetch($id)
+ {
+ return $this->_zendCache->load($this->_prepareId($id));
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ protected function _doContains($id)
+ {
+ return (bool) $this->_zendCache->test($this->_prepareId($id));
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ protected function _doSave($id, $data, $lifeTime = false)
+ {
+ return $this->_zendCache->save($data, $this->_prepareId($id), array(), $lifeTime);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ protected function _doDelete($id)
+ {
+ return $this->_zendCache->remove($this->_prepareId($id));
+ }
+
+
+ protected function _prepareId($id)
+ {
+ return preg_replace('/[^a-zA-Z0-9_]/', '_', $id);
+ }
+
+
+ public function getIds()
+ {
+ return $this->_zendCache->getIds();
+ }
+}
\ No newline at end of file
diff --git a/lib/Xdoctrine/DBAL/Logging/ZendSQLLogger.php b/lib/Xdoctrine/DBAL/Logging/ZendSQLLogger.php
new file mode 100644
index 0000000..a8b9dde
--- /dev/null
+++ b/lib/Xdoctrine/DBAL/Logging/ZendSQLLogger.php
@@ -0,0 +1,67 @@
+<?php
+
+/**
+ * Xdoctrine - Sirprize's Doctrine2 Extensions
+ *
+ * LICENSE
+ *
+ * This source file is subject to the new BSD license that is bundled
+ * with this package in the file LICENSE.txt.
+ *
+ * @package Xzend
+ * @copyright Copyright (c) 2009, Christian Hoegl, Switzerland (http://sitengine.org)
+ * @license http://sitengine.org/license/new-bsd New BSD License
+ */
+
+
+namespace Xdoctrine\DBAL\Logging;
+
+
+require_once 'Doctrine/DBAL/Logging/SQLLogger.php';
+
+
+class ZendSQLLogger implements \Doctrine\DBAL\Logging\SQLLogger
+{
+ /**
+ * @var \Zend_Log
+ */
+ private $_zendLog;
+
+ /**
+ * Sets the \Zend_Log instance to use.
+ *
+ * @param \Zend_Log $zendLog
+ */
+ public function setZendLog(\Zend_Log $zendLog)
+ {
+ $this->_zendLog = $zendLog;
+ }
+
+ /**
+ * Gets the \Zend_Log instance used by the cache.
+ *
+ * @return \Zend_Log
+ */
+ public function getZendLog()
+ {
+ return $this->_zendLog;
+ }
+
+
+ function logSQL($sql, array $params = null)
+ {
+ $p = '';
+
+ foreach($params as $k => $v)
+ {
+ if(is_object($v))
+ {
+ continue;
+ }
+ $p .= (($p) ? ', ' : '').$k.' => '.$v;
+ }
+
+ $this->getZendLog()->debug($sql);
+ $this->getZendLog()->debug("PARAMS: $p");
+ }
+}
\ No newline at end of file
diff --git a/lib/Xdoctrine/ORM/Event/Listener/Abstrakt.php b/lib/Xdoctrine/ORM/Event/Listener/Abstrakt.php
new file mode 100644
index 0000000..2bec875
--- /dev/null
+++ b/lib/Xdoctrine/ORM/Event/Listener/Abstrakt.php
@@ -0,0 +1,154 @@
+<?php
+
+/**
+ * Xdoctrine - Sirprize's Doctrine2 Extensions
+ *
+ * LICENSE
+ *
+ * This source file is subject to the new BSD license that is bundled
+ * with this package in the file LICENSE.txt.
+ *
+ * @package Xzend
+ * @copyright Copyright (c) 2009, Christian Hoegl, Switzerland (http://sitengine.org)
+ * @license http://sitengine.org/license/new-bsd New BSD License
+ */
+
+namespace Xdoctrine\Orm\Event\Listener;
+
+
+abstract class Abstrakt
+{
+
+
+ protected $_queue = array();
+ protected $_entityClassName = null;
+ protected $_events = array();
+
+
+ public function __construct($entityClassName)
+ {
+ $this->_entityClassName = $entityClassName;
+ }
+
+ /*
+ public function isRegistered(\Doctrine\Common\EventManager $eventManager)
+ {
+ return ($this->getRegisteredInstance($eventManager) !== null);
+ }
+
+
+ public function getRegisteredInstance(\Doctrine\Common\EventManager $eventManager)
+ {
+ foreach($this->_events as $event)
+ {
+ if($eventManager->hasListeners($event))
+ {
+ foreach($eventManager->getListeners($event) as $listener)
+ {
+ if($listener instanceof $this)
+ {
+ return $listener;
+ }
+ }
+ }
+ }
+
+ return null;
+ }
+
+
+ public function register(\Doctrine\Common\EventManager $eventManager)
+ {
+ #if(!$this->isRegistered($eventManager))
+ #{
+ $eventManager->addEventListener($this->_events, $this);
+ return $this;
+ #}
+ }
+ */
+
+ public function getEvents()
+ {
+ return $this->_events;
+ }
+
+
+ public function getQueue()
+ {
+ return $this->_queue;
+ }
+
+
+ public function isQueued($id)
+ {
+ return isset($this->_queue[$id]);
+ }
+
+
+ public function hasError($id)
+ {
+ return (isset($this->_queue[$id]) && $this->_queue[$id] == 0);
+ }
+
+
+ public function isFlushOk()
+ {
+ foreach($this->_queue as $item)
+ {
+ if($item == 0)
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+
+ public function isFlushError()
+ {
+ foreach($this->_queue as $item)
+ {
+ if($item == 0)
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+
+ public function countFlushOks()
+ {
+ $ok = 0;
+
+ foreach($this->_queue as $item)
+ {
+ if($item == 1)
+ {
+ $ok++;
+ }
+ }
+
+ return $ok;
+ }
+
+
+ public function countFlushErrors()
+ {
+ $errors = 0;
+
+ foreach($this->_queue as $item)
+ {
+ if($item == 0)
+ {
+ $errors++;
+ }
+ }
+
+ return $errors;
+ }
+
+
+}
\ No newline at end of file
diff --git a/lib/Xdoctrine/ORM/Event/Listener/Persists.php b/lib/Xdoctrine/ORM/Event/Listener/Persists.php
new file mode 100644
index 0000000..e406b4e
--- /dev/null
+++ b/lib/Xdoctrine/ORM/Event/Listener/Persists.php
@@ -0,0 +1,50 @@
+<?php
+
+/**
+ * Xdoctrine - Sirprize's Doctrine2 Extensions
+ *
+ * LICENSE
+ *
+ * This source file is subject to the new BSD license that is bundled
+ * with this package in the file LICENSE.txt.
+ *
+ * @package Xzend
+ * @copyright Copyright (c) 2009, Christian Hoegl, Switzerland (http://sitengine.org)
+ * @license http://sitengine.org/license/new-bsd New BSD License
+ */
+
+
+namespace Xdoctrine\ORM\Event\Listener;
+
+
+require_once 'Xdoctrine/ORM/Event/Listener/Abstrakt.php';
+
+
+class Persists extends \Xdoctrine\ORM\Event\Listener\Abstrakt
+{
+
+
+ protected $_events = array(
+ \Doctrine\ORM\Events::prePersist,
+ \Doctrine\ORM\Events::postPersist
+ );
+
+
+ public function prePersist(\Doctrine\ORM\Event\LifecycleEventArgs $eventArgs)
+ {
+ if($eventArgs->getEntity() instanceof $this->_entityClassName)
+ {
+ $this->_queue[$eventArgs->getEntity()->getId()] = 0;
+ }
+ }
+
+
+ public function postPersist(\Doctrine\ORM\Event\LifecycleEventArgs $eventArgs)
+ {
+ if($eventArgs->getEntity() instanceof $this->_entityClassName)
+ {
+ $this->_queue[$eventArgs->getEntity()->getId()] = 1;
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/lib/Xdoctrine/ORM/Event/Listener/Removes.php b/lib/Xdoctrine/ORM/Event/Listener/Removes.php
new file mode 100644
index 0000000..e5d69de
--- /dev/null
+++ b/lib/Xdoctrine/ORM/Event/Listener/Removes.php
@@ -0,0 +1,50 @@
+<?php
+
+/**
+ * Xdoctrine - Sirprize's Doctrine2 Extensions
+ *
+ * LICENSE
+ *
+ * This source file is subject to the new BSD license that is bundled
+ * with this package in the file LICENSE.txt.
+ *
+ * @package Xzend
+ * @copyright Copyright (c) 2009, Christian Hoegl, Switzerland (http://sitengine.org)
+ * @license http://sitengine.org/license/new-bsd New BSD License
+ */
+
+
+namespace Xdoctrine\ORM\Event\Listener;
+
+
+require_once 'Xdoctrine/ORM/Event/Listener/Abstrakt.php';
+
+
+class Removes extends \Xdoctrine\ORM\Event\Listener\Abstrakt
+{
+
+
+ protected $_events = array(
+ \Doctrine\ORM\Events::preRemove,
+ \Doctrine\ORM\Events::postRemove
+ );
+
+
+ public function preRemove(\Doctrine\ORM\Event\LifecycleEventArgs $eventArgs)
+ {
+ if($eventArgs->getEntity() instanceof $this->_entityClassName)
+ {
+ $this->_queue[$eventArgs->getEntity()->getId()] = 0;
+ }
+ }
+
+
+ public function postRemove(\Doctrine\ORM\Event\LifecycleEventArgs $eventArgs)
+ {
+ if($eventArgs->getEntity() instanceof $this->_entityClassName)
+ {
+ $this->_queue[$eventArgs->getEntity()->getId()] = 1;
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/lib/Xdoctrine/ORM/Event/Listener/Updates.php b/lib/Xdoctrine/ORM/Event/Listener/Updates.php
new file mode 100644
index 0000000..2f11140
--- /dev/null
+++ b/lib/Xdoctrine/ORM/Event/Listener/Updates.php
@@ -0,0 +1,50 @@
+<?php
+
+/**
+ * Xdoctrine - Sirprize's Doctrine2 Extensions
+ *
+ * LICENSE
+ *
+ * This source file is subject to the new BSD license that is bundled
+ * with this package in the file LICENSE.txt.
+ *
+ * @package Xzend
+ * @copyright Copyright (c) 2009, Christian Hoegl, Switzerland (http://sitengine.org)
+ * @license http://sitengine.org/license/new-bsd New BSD License
+ */
+
+
+namespace Xdoctrine\ORM\Event\Listener;
+
+
+require_once 'Xdoctrine/ORM/Event/Listener/Abstrakt.php';
+
+
+class Updates extends \Xdoctrine\ORM\Event\Listener\Abstrakt
+{
+
+
+ protected $_events = array(
+ \Doctrine\ORM\Events::preUpdate,
+ \Doctrine\ORM\Events::postUpdate
+ );
+
+
+ public function preUpdate(\Doctrine\ORM\Event\PreUpdateEventArgs $eventArgs)
+ {
+ if($eventArgs->getEntity() instanceof $this->_entityClassName)
+ {
+ $this->_queue[$eventArgs->getEntity()->getId()] = 0;
+ }
+ }
+
+
+ public function postUpdate(\Doctrine\ORM\Event\LifecycleEventArgs $eventArgs)
+ {
+ if($eventArgs->getEntity() instanceof $this->_entityClassName)
+ {
+ $this->_queue[$eventArgs->getEntity()->getId()] = 1;
+ }
+ }
+
+}
\ No newline at end of file
|
elchingon/yii-dbmigrations | d13ea3341b6859e2ef4eefb5bf34dee396f2328b | Added a lot of information to the readme file. | diff --git a/README.textile b/README.textile
index 7d50ad0..b277989 100644
--- a/README.textile
+++ b/README.textile
@@ -1,222 +1,346 @@
h1. Yii DB Migrations
A database migrations engine for the "Yii framework":http://www.yiiframework.com. It comes in the form of an extension which can be dropped into any existing Yii framework application.
It relies on the database abstraction layer of the Yii framework to talk to the database engine.
It's largely inspired on the migrations functionality of the Ruby on Rails framework.
h2. Why bother in the first place?
You might wonder why you need database migrations in the first place. Sure, you could use plain SQL files to apply updates to the database, but they have a big disadvantage: they are database specific.
Imagine you initially create your database using SQLite and later on decide to change to MySQL. When you use plain SQL files, you will need to rewrite them using MySQL's flavor of SQL. Also, you will need to create some tool that knows what has been applied already to the database and what's not applied yet.
Meet database migrations. By defining a higher level interface to creating and maintaining the database schema, you can define it in a database agnostic way.
By using PHP functions to create tables, indexes, fields, ... you can write the schema once and apply it to any database backend supported. The added bonus is that the yii-dbmigrations extension keeps track of which migrations have been applied already and which ones still need to be applied.
h2. Current limitations
Be aware that the current version is still very alpha.
There are only two database engines supported:
* MySQL
* SQLite
h2. Installing the extension
h3. Putting the files in the right location
Installing the extension is quite easy. Once you downloaded the files from github, you need to put all the files in a folder called "yii-dbmigrations" and put it in the <code>protected/extensions</code> folder from your project.
h3. Configuring the database connection
You need to make sure you configure database access properly in the configuration file of your project. As the console applications in the Yii framework look at the <code>protected/config/console.php</code> file, you need to make sure you configure the <code>db</code> settings under the <code>components</code> key in the configuration array. For MySQL, the configuration will look as follows:
<pre>
'components' => array(
'db'=>array(
'class' => 'CDbConnection',
'connectionString'=>'mysql:host=localhost;dbname=my_db',
'charset' => 'UTF8',
'username'=>'root',
'password'=>'root',
),
),
</pre>
For SQLite, the configuration looks as follows:
<pre>
'components' => array(
'db'=>array(
'connectionString'=>'sqlite:'.dirname(__FILE__).'/../data/my_db.db',
),
),
</pre>
h3. Configuring the command map
To make the <code>yiic</code> tool know about the <code>migrate</code> command, you need to add a <code>commandMap</code> key to the application configuration in <code>protected/config/console.php</code>.
In there, you need to put the following configuration:
<pre>
'commandMap' => array(
'migrate' => array(
'class'=>'application.extensions.yii-dbmigrations.CDbMigrationCommand',
),
),
</pre>
h3. Testing your installation
To test if the installation was succesfull, you can run the yiic command and should see the following output:
<pre>
-Yii command runner (based on Yii v1.0.6)
+Yii command runner (based on Yii v1.0.10)
Usage: protected/yiic <command-name> [parameters...]
The following commands are available:
- migrate
- message
- shell
- webapp
To see individual command help, use the following:
protected/yiic help <command-name>
</pre>
It should mention that the <code>migrate</code> command is available.
h2. Creating migrations
h3. Naming conventions
You can create migrations by creating files in the <code>protected/migrations</code> folder or in the <code>migrations</code> folder inside your module. The file names for the migrations should follow a specific naming convention:
<pre>
m20090614213453_MigrationName.php
</pre>
The migration file names always start with the letter m followed by 14 digit timestamp and an underscore. After that, you can give a name to the migration so that you can easily identify the migration.
+You can also use the <code>protected/yiic migrate create <MigrationName></code> to create a new empty migration:
+
+<pre>
+$ protected/yiic migrate create TestMigration
+Migrations directory: protected/migrations/
+
+Created migration: m20091114210716_TestMigration.php
+</pre>
+
h3. Implementing the migration
In the migration file, you need to create a class that extends the parent class <code>CDbMigration</code>. The <code>CDbMigration</code> class needs to have the <code>up</code> and <code>down</code> methods as you can see in the following sample migration:
<pre>
class m20090611153243_CreateTables extends CDbMigration {
+ // Apply the migration
public function up() {
- $this->createTable(
- 'posts',
- array(
- array('id', 'primary_key'),
- array('title', 'string'),
- array('body', 'text'),
- )
- );
-
- $this->addIndex(
- 'posts', 'posts_title', array('title')
- );
+ // Create the posts table
+ $t = $this->newTable('posts');
+ $t->primary_key('id');
+ $t->string('title');
+ $t->text('body');
+ $t->index('posts_title', 'title');
+ $this->addTable($t);
}
+ // Remove the migration
public function down() {
+
+ // Remove the table
$this->removeTable('posts');
+
}
}
</pre>
h3. Supported functionality
In the migration class, you have the following functionality available:
* execute: execute a raw SQL statement that doesn't return any data.
* query: execute a raw SQL statement that returns data.
* createTable: create a new table
+* newTable: creates a new table definition
+* addTable: adds the table definition to the migration
* renameTable: rename a table
* removeTable: remove a table
* addColumn: add a column to a table
* renameColumn: rename a column in a table
* changeColumn: change the definition of a column in a table
* removeColumn: remove a column from a table
* addIndex: add an index to the database or table
* removeIndex: remove an index from the database or table
When specifying fields, we also support a type mapping so that you can use generic type definitions instead of database specific type definitions. The following types are supported:
* primary_key
* string
* text
* integer
* float
* decimal
* datetime
* timestamp
* time
* date
* binary
* boolean
* bool
You can also specify a database specific type when defining a field, but this will make your migrations less portable across database engines.
+h3. Short syntax to create tables
+
+There is also a short syntax to create tables which is a lot more concise than
+using the <code>createTable</code> syntax. To use this syntax, you need to perform 3 different steps:
+
+h4. Create a new table definition
+
+The first step is to create a new table definition in your migration:
+
+<pre>
+$t = $this->newTable('<tableName>');
+</pre>
+
+h4. Add the fields and indexes
+
+Now, you can add fields and indexes to your table definition. The name of the function indicates the type of field to add:
+
+<pre>
+$t->primary_key('id');
+$t->string('title');
+$t->text('body');
+</pre>
+
+Adding indexes is done by the <code>index</code> and <code>unique</code> functions:
+
+<pre>
+$t->index('title');
+$t->unique('title');
+</pre>
+
+h4. Creating the table
+
+To actually create the table, you need to add the definition to the migration using the <code>addTable</code> function:
+
+<pre>
+$this->addTable($t);
+</pre>
+
+It will now create the table and indexes.
+
h2. Applying migrations
Once you created the migrations, you can apply them to your database by running the <code>migrate</code> command:
<pre>
protected/yiic migrate
</pre>
You will see the following output:
<pre>
+Migrations directory: protected/migrations/
+
Creating initial schema_version table
-Applying migration: m20090611153243_CreateTables
+=== Applying: m20090611153243_CreateTables =====================================
>> Creating table: posts
>> Adding index posts_title to table: posts
-Marking migration as applied: m20090611153243_CreateTables
-Applying migration: m20090612162832_CreateTags
+=== Marked as applied: m20090611153243_CreateTables ============================
+
+=== Applying: m20090612162832_CreateTags =======================================
>> Creating table: tags
>> Creating table: post_tags
>> Adding index post_tags_post_tag to table: post_tags
-Marking migration as applied: m20090612162832_CreateTags
-Applying migration: m20090612163144_RenameTagsTable
+=== Marked as applied: m20090612162832_CreateTags ==============================
+
+=== Applying: m20090612163144_RenameTagsTable ==================================
>> Renaming table: post_tags to: post_tags_link_table
-Marking migration as applied: m20090612163144_RenameTagsTable
-Applying migration: m20090616153243_Test_CreateTables
- >> Creating table: test_pages
- >> Adding index test_pages_title to table: test_pages
-Marking migration as applied: m20090616153243_Test_CreateTables
+=== Marked as applied: m20090612163144_RenameTagsTable =========================
</pre>
It will apply all the migrations found in the <code>protected/migrations</code> directory provided they were not applied to the database yet.
It will also apply any migrations found in the <code>migrations</code> directory inside each module which is enabled in the application.
-If you run the <code>migrate</code> command again, it will show that the migrations were applied already:
+If you run the <code>migrate</code> command again, it will show nothing as the migrations were applied already:
<pre>
-Skipping applied migration: m20090611153243_CreateTables
-Skipping applied migration: m20090612162832_CreateTags
-Skipping applied migration: m20090612163144_RenameTagsTable
-Skipping applied migration: m20090616153243_Test_CreateTables
+Migrations directory: protected/migrations/
</pre>
Since the <code>migrate</code> command checks based on the ID of each migration, it can detect that a migration is already applied to the database and therefor doesn't need to be applied anymore.
+h2. protected/yiic migrate command reference
+
+The complete reference to the migrate command can be obtained by running the <code>protected/yiic help migrate</code> command. This outputs the following help:
+
+<pre>
+USAGE
+ migrate [create|version|up|down|list]
+
+DESCRIPTION
+ This command applies the database migrations which can be found in the
+ migrations directory in your project folder.
+
+PARAMETERS
+ * create: creates a new migration in the migrations directory.
+
+ * version: options, the ID of the migration to migrate the database to.
+
+ * up: optional, apply the first migration that is not applied to the database
+ yet.
+
+ * down: remove the last applied migration from the database.
+
+ * redo: redo the last migration (removes and installs it again)
+
+ * list: list all the migrations available in the application and show if they
+ are applied or not.
+
+EXAMPLES
+ * Apply all migrations that are not applied yet:
+ migrate
+
+ * Migrate up to version 20090612163144 if it's not applied yet:
+ migrate 20090612163144
+
+ * Migrate down to version 20090612163144 if it's applied already:
+ migrate 20090612163144
+
+ * Apply the first migration that is not applied to the database yet:
+ migrate up
+
+ * Remove the last applied migration:
+ migrate down
+
+ * Re-apply the last applied migration:
+ migrate redo
+
+ * List all the migrations found in the application and their status:
+ migrate list
+
+ * Create a new migration
+ migrate create
+
+ * Create a new name migration
+ migrate create MyMigrationName
+</pre>
+
+h2. Data types
+
+The yii-dbmigrations package supports the following data types:
+
+|*type*|*MySQL*|*SQLite*|
+|primary_key|<code>int(11) DEFAULT NULL auto_increment PRIMARY KEY</code>|<code>INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL</code>|
+|string|<code>varchar(255)</code>|<code>varchar(255)</code>|
+|text|<code>text</code>|<code>text</code>|
+|integer|<code>int(4)</code>|<code>integer</code>|
+|float|<code>float</code>|<code>float</code>|
+|decimal|<code>decimal</code>|<code>decimal</code>|
+|datetime|<code>datetime</code>|<code>datetime</code>|
+|timestamp|<code>datetime</code>|<code>datetime</code>|
+|time|<code>time</code>|<code>time</code>|
+|date|<code>date</code>|<code>date</code>|
+|binary|<code>blob</code>|<code>blob</code>|
+|boolean|<code>tinyint(1)</code>|<code>tinyint(1)</code>|
+|bool|<code>tinyint(1)</code>|<code>tinyint(1)</code>|
+
+
h2. Author information
This extension is created and maintained by Pieter Claerhout. You can contact the author on:
* Website: "http://www.yellowduck.be":http://www.yellowduck.be
* Twitter: "http://twitter.com/pieterclaerhout":http://twitter.com/pieterclaerhout
* Github: "http://github.com/pieterclaerhout/yii-dbmigrations/tree/master":http://github.com/pieterclaerhout/yii-dbmigrations/tree/master
|
elchingon/yii-dbmigrations | 96189e33cb50d4d78a06f2dfc03f9b3e3b7f98ad | Rewrote the sample migrations to use the new syntax to create tables. | diff --git a/samples/m20090611153243_CreateTables.php b/samples/m20090611153243_CreateTables.php
index 708af1a..1e6c0d4 100644
--- a/samples/m20090611153243_CreateTables.php
+++ b/samples/m20090611153243_CreateTables.php
@@ -1,26 +1,26 @@
<?php
class m20090611153243_CreateTables extends CDbMigration {
+ // Apply the migration
public function up() {
- $this->createTable(
- 'posts',
- array(
- array('id', 'primary_key'),
- array('title', 'string'),
- array('body', 'text'),
- )
- );
-
- $this->addIndex(
- 'posts', 'posts_title', array('title')
- );
+ // Create the posts table
+ $t = $this->newTable('posts');
+ $t->primary_key('id');
+ $t->string('title');
+ $t->text('body');
+ $t->index('posts_title', 'title');
+ $this->addTable($t);
}
+ // Remove the migration
public function down() {
+
+ // Remove the table
$this->removeTable('posts');
+
}
}
\ No newline at end of file
diff --git a/samples/m20090612162832_CreateTags.php b/samples/m20090612162832_CreateTags.php
index 2a27cc8..3b8e9b1 100644
--- a/samples/m20090612162832_CreateTags.php
+++ b/samples/m20090612162832_CreateTags.php
@@ -1,35 +1,33 @@
<?php
class m20090612162832_CreateTags extends CDbMigration {
+ // Apply the migration
public function up() {
- $this->createTable(
- 'tags',
- array(
- array('id', 'primary_key'),
- array('name', 'string'),
- )
- );
+ // Create the tags table
+ $t = $this->newTable('tags');
+ $t->primary_key();
+ $t->string('name');
+ $this->addTable($t);
- $this->createTable(
- 'post_tags',
- array(
- array('id', 'primary_key'),
- array('post_id', 'int'),
- array('tag_id', 'int'),
- )
- );
-
- $this->addIndex(
- 'post_tags', 'post_tags_post_tag', array('post_id', 'tag_id'), true
- );
+ // Create the post_tags table
+ $t = $this->newTable('post_tags');
+ $t->primary_key();
+ $t->integer('post_id');
+ $t->integer('tag_id');
+ $t->index('post_tags_post_tag', array('post_id', 'tag_id'), true);
+ $this->addTable($t);
}
+ // Remove the migration
public function down() {
+
+ // Remove the tables
$this->removeTable('post_tags');
$this->removeTable('tags');
+
}
}
\ No newline at end of file
diff --git a/samples/m20090612163144_RenameTagsTable.php b/samples/m20090612163144_RenameTagsTable.php
index 69a2bc2..0b1b50f 100644
--- a/samples/m20090612163144_RenameTagsTable.php
+++ b/samples/m20090612163144_RenameTagsTable.php
@@ -1,17 +1,21 @@
<?php
class m20090612163144_RenameTagsTable extends CDbMigration {
+ // Apply the migration
public function up() {
- $this->renameTable(
- 'post_tags', 'post_tags_link_table'
- );
+
+ // Rename a table
+ $this->renameTable('post_tags', 'post_tags_link_table');
+
}
+ // Remove the migration
public function down() {
- $this->renameTable(
- 'post_tags_link_table', 'post_tags'
- );
+
+ // Undo the table rename
+ $this->renameTable('post_tags_link_table', 'post_tags');
+
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | 9e981328934de0979e5967b4ce18826cbaab8183 | Added the CDbMigrationTable class and made it available in CDbMigration. | diff --git a/CDbMigration.php b/CDbMigration.php
index d16e64c..2d202c5 100644
--- a/CDbMigration.php
+++ b/CDbMigration.php
@@ -1,269 +1,301 @@
<?php
/**
* CDbMigration class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* @package extensions.yii-dbmigrations
*/
class CDbMigrationException extends Exception {}
/**
* This class abstracts a database migration. The main functions that you will
* need to implement for creating a migration are the up and down methods.
*
* The up method will be applied when the migration gets installed into the
* system, the down method when the migration gets removed from the system.
*
* @package extensions.yii-dbmigrations
*/
abstract class CDbMigration {
/**
* The CDbMigrationAdapater that is used to perform the actual migrations
* on the database.
*/
public $adapter;
/**
* Class constructor for the CDbMigration class.
*
* @param $adapter The CDbMigrationAdapater that is used to perform the
* actual migrations on the database.
*/
public function __construct(CDbMigrationAdapter $adapter) {
$this->adapter = $adapter;
}
/**
* This method will execute the given class method inside a database
* transaction. It will raise an exception if the class method doesn't
* exist.
*
* For the transaction handling, we rely on the Yii DB functionality. If
* the database doesn't support transactions, the SQL statements will be
* executed one after another without using transactions.
*
* If the command succeeds, the transaction will get committed, if not, a
* rollback of the transaction will happen.
*
* @param $command The name of the class method to execute.
*/
public function performTransactional($command) {
// Check if the class method exists
if (!method_exists($this, $command)) {
throw new CDbMigrationException(
'Invalid migration command: ' . $command
);
}
// Run the command inside a transaction
$transaction = $this->adapter->db->beginTransaction();
try {
$this->$command();
$transaction->commit();
} catch (Exception $e) {
$transaction->rollback();
throw new CDbMigrationException($e->getMessage());
}
}
/**
* The up class method contains all the statements that will be executed
* when the migration is applied to the database.
*/
public function up() {
}
/**
* The up class method contains all the statements that will be executed
* when the migration is removed the database.
*/
public function down() {
}
/**
* This function returns the ID of the migration.
*
* Given the following migration class name:
*
* <code>m20090611153243_CreateTables</code>
*
* The id for this migration will be:
*
* <code>20090611153243</code>
*
* @returns The ID of the migration.
*/
public function getId() {
$id = explode('_', get_class($this));
return substr($id[0], 1);
}
/**
* This function returns the name of the migration.
*
* Given the following migration class name:
*
* <code>m20090611153243_CreateTables</code>
*
* The name for this migration will be:
*
* <code>CreateTables</code>
*
* @returns The name of the migration.
*/
public function getName() {
$name = explode('_', get_class($this));
return join('_', array_slice($name, 1, sizeof($name) - 1));
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that doesn't return any data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The number of affected rows.
*/
protected function execute($query, $params=array()) {
return $this->adapter->execute($query, $params);
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that returns data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The rows returned from the database.
*/
protected function query($query, $params=array()) {
return $this->adapter->query($query, $params);
}
/**
* The createTable function allows you to create a new table in the
* database.
*
* @param $name The name of the table to create.
- * @param $column The column definition for the database table
+ * @param $columns The column definition for the database table
* @param $options The extra options to pass to the database creation.
*/
protected function createTable($name, $columns=array(), $options=null) {
echo(' >> Creating table: ' . $name . PHP_EOL);
return $this->adapter->createTable($name, $columns, $options);
}
+ /**
+ * Create a new table
+ *
+ * @param $name The name of the table to create.
+ * @param $options The extra options to pass to the database creation.
+ */
+ protected function newTable($name, $options=null) {
+ return new CDbMigrationTable($name, $options);
+ }
+
+ /**
+ * Add a table
+ *
+ * @param $table The CDbTable definition
+ * @param $options The extra options to pass to the database creation.
+ */
+ protected function addTable(CDbMigrationTable $table) {
+
+ // Add the table
+ if (sizeof($table->columns) > 0) {
+ $this->createTable($table->name, $table->columns, $table->options);
+ }
+
+ // Add the indexes
+ if (sizeof($table->indexes) > 0) {
+ foreach ($table->indexes as $index) {
+ $this->addIndex($table->name, $index[0], $index[1], $index[2]);
+ }
+ }
+
+ }
+
/**
* Rename a table.
*
* @param $name The name of the table to rename.
* @param $new_name The new name for the table.
*/
protected function renameTable($name, $new_name) {
echo(' >> Renaming table: ' . $name . ' to: ' . $new_name . PHP_EOL);
return $this->adapter->renameTable($name, $new_name);
}
/**
* Remove a table from the database.
*
* @param $name The name of the table to remove.
*/
protected function removeTable($name) {
echo(' >> Removing table: ' . $name . PHP_EOL);
return $this->adapter->removeTable($name);
}
/**
* Add a database column to an existing table.
*
* @param $table The table to add the column in.
* @param $column The name of the column to add.
* @param $type The data type for the new column.
* @param $options The extra options to pass to the column.
*/
protected function addColumn($table, $column, $type, $options=null) {
echo(' >> Adding column ' . $column . ' to table: ' . $table . PHP_EOL);
return $this->adapter->addColumn($table, $column, $type, $options);
}
/**
* Rename a database column in an existing table.
*
* @param $table The table to rename the column from.
* @param $name The current name of the column.
* @param $new_name The new name of the column.
*/
protected function renameColumn($table, $name, $new_name) {
echo(
' >> Renaming column ' . $name . ' to: ' . $new_name
. ' in table: ' . $table . PHP_EOL
);
return $this->adapter->renameColumn($table, $name, $new_name);
}
/**
* Change a database column in an existing table.
*
* @param $table The name of the table to change the column from.
* @param $column The name of the column to change.
* @param $type The new data type for the column.
* @param $options The extra options to pass to the column.
*/
protected function changeColumn($table, $column, $type, $options=null) {
echo(
' >> Changing column ' . $column . ' to: ' . $type
. ' in table: ' . $table . PHP_EOL
);
return $this->adapter->changeColumn($table, $column, $type, $options);
}
/**
* Remove a table column from the database.
*
* @param $table The name of the table to remove the column from.
* @param $column The name of the table column to remove.
*/
protected function removeColumn($table, $column) {
echo(
' >> Removing column ' . $column . ' from table: ' . $table . PHP_EOL
);
return $this->adapter->removeColumn($table, $column);
}
/**
* Add an index to the database or a specific table.
*
* @param $table The name of the table to add the index to.
* @param $name The name of the index to create.
* @param $columns The name of the fields to include in the index.
* @param $unique If set to true, a unique index will be created.
*/
public function addIndex($table, $name, $columns, $unique=false) {
echo(' >> Adding index ' . $name . ' to table: ' . $table . PHP_EOL);
return $this->adapter->addIndex($table, $name, $columns, $unique);
}
/**
* Remove a table index from the database.
*
* @param $table The name of the table to remove the index from.
* @param $column The name of the table index to remove.
*/
protected function removeIndex($table, $name) {
echo(' >> Removing index ' . $name . ' from table: ' . $table . PHP_EOL);
return $this->adapter->removeIndex($table, $name);
}
}
\ No newline at end of file
diff --git a/CDbMigrationTable.php b/CDbMigrationTable.php
new file mode 100644
index 0000000..b71cf17
--- /dev/null
+++ b/CDbMigrationTable.php
@@ -0,0 +1,215 @@
+<?php
+
+/**
+ * CDbTable class file.
+ *
+ * @author Pieter Claerhout <[email protected]>
+ * @link http://github.com/pieterclaerhout/yii-dbmigrations/
+ * @copyright Copyright © 2009 Pieter Claerhout
+ */
+
+/**
+ * This class abstracts a database class. You can use it to easily create
+ * tables and fields.
+ *
+ * @package extensions.yii-dbmigrations
+ */
+class CDbMigrationTable {
+
+ /**
+ * The name of the table.
+ */
+ public $name;
+
+ /**
+ * The options for the table.
+ */
+ public $options;
+
+ /**
+ * The list of columns for the table.
+ */
+ public $columns = array();
+
+ /**
+ * The list of indexes for the table.
+ */
+ public $indexes = array();
+
+ /**
+ * Constructor
+ *
+ * @param $name The name of the table to create.
+ * @param $options The extra options to pass to the database creation.
+ */
+ public function __construct($name, $options=null) {
+ $this->name = $name;
+ $this->options = $options;
+ }
+
+ /**
+ * Add a primary key to the table.
+ *
+ * @param $name The name of the primary key column.
+ * @param $options The extra options to pass to the column.
+ */
+ public function primary_key($name='id', $options=null) {
+ $this->addField($name, 'primary_key', $options);
+ }
+
+ /**
+ * Add a string field to the table.
+ *
+ * @param $name The name of the primary key column.
+ * @param $options The extra options to pass to the column.
+ */
+ public function string($name, $options=null) {
+ $this->addField($name, 'string', $options);
+ }
+
+ /**
+ * Add a text field to the table.
+ *
+ * @param $name The name of the primary key column.
+ * @param $options The extra options to pass to the column.
+ */
+ public function text($name, $options=null) {
+ $this->addField($name, 'text', $options);
+ }
+
+ /**
+ * Add an integer field to the table.
+ *
+ * @param $name The name of the primary key column.
+ * @param $options The extra options to pass to the column.
+ */
+ public function integer($name, $options=null) {
+ $this->addField($name, 'integer', $options);
+ }
+
+ /**
+ * Add a float field to the table.
+ *
+ * @param $name The name of the primary key column.
+ * @param $options The extra options to pass to the column.
+ */
+ public function float($name, $options=null) {
+ $this->addField($name, 'float', $options);
+ }
+
+ /**
+ * Add a decimal field to the table.
+ *
+ * @param $name The name of the primary key column.
+ * @param $options The extra options to pass to the column.
+ */
+ public function decimal($name, $options=null) {
+ $this->addField($name, 'decimal', $options);
+ }
+
+ /**
+ * Add a datetime field to the table.
+ *
+ * @param $name The name of the primary key column.
+ * @param $options The extra options to pass to the column.
+ */
+ public function datetime($name, $options=null) {
+ $this->addField($name, 'datetime', $options);
+ }
+
+ /**
+ * Add a timestamp field to the table.
+ *
+ * @param $name The name of the primary key column.
+ * @param $options The extra options to pass to the column.
+ */
+ public function timestamp($name, $options=null) {
+ $this->addField($name, 'timestamp', $options);
+ }
+
+ /**
+ * Add a time field to the table.
+ *
+ * @param $name The name of the primary key column.
+ * @param $options The extra options to pass to the column.
+ */
+ public function time($name, $options=null) {
+ $this->addField($name, 'time', $options);
+ }
+
+ /**
+ * Add a date field to the table.
+ *
+ * @param $name The name of the primary key column.
+ * @param $options The extra options to pass to the column.
+ */
+ public function date($name, $options=null) {
+ $this->addField($name, 'date', $options);
+ }
+
+ /**
+ * Add a binary field to the table.
+ *
+ * @param $name The name of the primary key column.
+ * @param $options The extra options to pass to the column.
+ */
+ public function binary($name, $options=null) {
+ $this->addField($name, 'binary', $options);
+ }
+
+ /**
+ * Add a boolean field to the table.
+ *
+ * @param $name The name of the primary key column.
+ * @param $options The extra options to pass to the column.
+ */
+ public function boolean($name, $options=null) {
+ $this->addField($name, 'boolean', $options);
+ }
+
+ /**
+ * Add a boolean field to the table.
+ *
+ * @param $name The name of the primary key column.
+ * @param $options The extra options to pass to the column.
+ */
+ public function bool($name, $options=null) {
+ $this->addField($name, 'bool', $options);
+ }
+
+ /**
+ * Add a non-unique index to the table.
+ *
+ * @param $name The name of the index.
+ * @param $columns The column(s) to add to the index
+ * @param $unique Whether a unique or non unique index should be created.
+ */
+ public function index($name, $columns, $unique=false) {
+ if (!is_array($columns)) {
+ $columns = array($columns);
+ }
+ $this->indexes[] = array($name, $columns, $unique);
+ }
+
+ /**
+ * Add a unique index to the table.
+ *
+ * @param $name The name of the index.
+ * @param $columns The column(s) to add to the index
+ */
+ public function unique($name, $columns) {
+ $this->index($name, $columns, true);
+ }
+
+ /**
+ * Helper function to add a field to the column definition.
+ *
+ * @param $name The name of the field to add.
+ * @param $type The type of the field to add.
+ * @param $options The extra options to pass to the column.
+ */
+ protected function addField($name, $type, $options=null) {
+ $this->columns[] = array($name, $type, $options);
+ }
+
+}
\ No newline at end of file
|
elchingon/yii-dbmigrations | c60057baa5f263e0ec2463da39ac6f1690fbecb9 | Replaced the deprecated split function with the explode function to make sure it works fine with PHP 5.3 (reported by junqed). | diff --git a/CDbMigration.php b/CDbMigration.php
index f93eafd..d16e64c 100644
--- a/CDbMigration.php
+++ b/CDbMigration.php
@@ -1,269 +1,269 @@
<?php
/**
* CDbMigration class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* @package extensions.yii-dbmigrations
*/
class CDbMigrationException extends Exception {}
/**
* This class abstracts a database migration. The main functions that you will
* need to implement for creating a migration are the up and down methods.
*
* The up method will be applied when the migration gets installed into the
* system, the down method when the migration gets removed from the system.
*
* @package extensions.yii-dbmigrations
*/
abstract class CDbMigration {
/**
* The CDbMigrationAdapater that is used to perform the actual migrations
* on the database.
*/
public $adapter;
/**
* Class constructor for the CDbMigration class.
*
* @param $adapter The CDbMigrationAdapater that is used to perform the
* actual migrations on the database.
*/
public function __construct(CDbMigrationAdapter $adapter) {
$this->adapter = $adapter;
}
/**
* This method will execute the given class method inside a database
* transaction. It will raise an exception if the class method doesn't
* exist.
*
* For the transaction handling, we rely on the Yii DB functionality. If
* the database doesn't support transactions, the SQL statements will be
* executed one after another without using transactions.
*
* If the command succeeds, the transaction will get committed, if not, a
* rollback of the transaction will happen.
*
* @param $command The name of the class method to execute.
*/
public function performTransactional($command) {
// Check if the class method exists
if (!method_exists($this, $command)) {
throw new CDbMigrationException(
'Invalid migration command: ' . $command
);
}
// Run the command inside a transaction
$transaction = $this->adapter->db->beginTransaction();
try {
$this->$command();
$transaction->commit();
} catch (Exception $e) {
$transaction->rollback();
throw new CDbMigrationException($e->getMessage());
}
}
/**
* The up class method contains all the statements that will be executed
* when the migration is applied to the database.
*/
public function up() {
}
/**
* The up class method contains all the statements that will be executed
* when the migration is removed the database.
*/
public function down() {
}
/**
* This function returns the ID of the migration.
*
* Given the following migration class name:
*
* <code>m20090611153243_CreateTables</code>
*
* The id for this migration will be:
*
* <code>20090611153243</code>
*
* @returns The ID of the migration.
*/
public function getId() {
- $id = split('_', get_class($this));
+ $id = explode('_', get_class($this));
return substr($id[0], 1);
}
/**
* This function returns the name of the migration.
*
* Given the following migration class name:
*
* <code>m20090611153243_CreateTables</code>
*
* The name for this migration will be:
*
* <code>CreateTables</code>
*
* @returns The name of the migration.
*/
public function getName() {
- $name = split('_', get_class($this));
+ $name = explode('_', get_class($this));
return join('_', array_slice($name, 1, sizeof($name) - 1));
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that doesn't return any data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The number of affected rows.
*/
protected function execute($query, $params=array()) {
return $this->adapter->execute($query, $params);
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that returns data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The rows returned from the database.
*/
protected function query($query, $params=array()) {
return $this->adapter->query($query, $params);
}
/**
* The createTable function allows you to create a new table in the
* database.
*
* @param $name The name of the table to create.
* @param $column The column definition for the database table
* @param $options The extra options to pass to the database creation.
*/
protected function createTable($name, $columns=array(), $options=null) {
echo(' >> Creating table: ' . $name . PHP_EOL);
return $this->adapter->createTable($name, $columns, $options);
}
/**
* Rename a table.
*
* @param $name The name of the table to rename.
* @param $new_name The new name for the table.
*/
protected function renameTable($name, $new_name) {
echo(' >> Renaming table: ' . $name . ' to: ' . $new_name . PHP_EOL);
return $this->adapter->renameTable($name, $new_name);
}
/**
* Remove a table from the database.
*
* @param $name The name of the table to remove.
*/
protected function removeTable($name) {
echo(' >> Removing table: ' . $name . PHP_EOL);
return $this->adapter->removeTable($name);
}
/**
* Add a database column to an existing table.
*
* @param $table The table to add the column in.
* @param $column The name of the column to add.
* @param $type The data type for the new column.
* @param $options The extra options to pass to the column.
*/
protected function addColumn($table, $column, $type, $options=null) {
echo(' >> Adding column ' . $column . ' to table: ' . $table . PHP_EOL);
return $this->adapter->addColumn($table, $column, $type, $options);
}
/**
* Rename a database column in an existing table.
*
* @param $table The table to rename the column from.
* @param $name The current name of the column.
* @param $new_name The new name of the column.
*/
protected function renameColumn($table, $name, $new_name) {
echo(
' >> Renaming column ' . $name . ' to: ' . $new_name
. ' in table: ' . $table . PHP_EOL
);
return $this->adapter->renameColumn($table, $name, $new_name);
}
/**
* Change a database column in an existing table.
*
* @param $table The name of the table to change the column from.
* @param $column The name of the column to change.
* @param $type The new data type for the column.
* @param $options The extra options to pass to the column.
*/
protected function changeColumn($table, $column, $type, $options=null) {
echo(
' >> Changing column ' . $column . ' to: ' . $type
. ' in table: ' . $table . PHP_EOL
);
return $this->adapter->changeColumn($table, $column, $type, $options);
}
/**
* Remove a table column from the database.
*
* @param $table The name of the table to remove the column from.
* @param $column The name of the table column to remove.
*/
protected function removeColumn($table, $column) {
echo(
' >> Removing column ' . $column . ' from table: ' . $table . PHP_EOL
);
return $this->adapter->removeColumn($table, $column);
}
/**
* Add an index to the database or a specific table.
*
* @param $table The name of the table to add the index to.
* @param $name The name of the index to create.
* @param $columns The name of the fields to include in the index.
* @param $unique If set to true, a unique index will be created.
*/
public function addIndex($table, $name, $columns, $unique=false) {
echo(' >> Adding index ' . $name . ' to table: ' . $table . PHP_EOL);
return $this->adapter->addIndex($table, $name, $columns, $unique);
}
/**
* Remove a table index from the database.
*
* @param $table The name of the table to remove the index from.
* @param $column The name of the table index to remove.
*/
protected function removeIndex($table, $name) {
echo(' >> Removing index ' . $name . ' from table: ' . $table . PHP_EOL);
return $this->adapter->removeIndex($table, $name);
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | 6c1c9a5c56202aea33639792665744aa4c39fc0f | Fixed a bug that was found when using Yii Framework version 1.0.10. | diff --git a/CDbMigrationEngine.php b/CDbMigrationEngine.php
index 0be45d4..2781edc 100644
--- a/CDbMigrationEngine.php
+++ b/CDbMigrationEngine.php
@@ -1,496 +1,494 @@
<?php
/**
* CDbMigrationEngine class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the adapters we are going to use for the migrations.
*/
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* A database migration engine exception
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngineException extends Exception {}
/**
* The CDbMigrationEngine class is the actual engine that can do all the
* migrations related functionality.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngine {
/**
* The migration adapter to use
*/
private $adapter;
/**
* The name of the table that contains the schema information.
*/
const SCHEMA_TABLE = 'schema_version';
/**
* The field in the schema_version table that contains the id of the
* installed migrations.
*/
const SCHEMA_FIELD = 'id';
/**
* The extension used for the migration files.
*/
const SCHEMA_EXT = 'php';
/**
* The directory in which the migrations can be found.
*/
const MIGRATIONS_DIR = 'migrations';
/**
* The command line arguments passed to the system.
*/
private $args;
/**
* The full path to the migrations
*/
private $migrationsDir;
/**
* Run the database migration engine, passing on the command-line
* arguments.
*
* @param $args The command line parameters.
*/
public function run($args) {
// Catch errors
try {
// Remember the arguments
$this->args = $args;
// Initialize the engine
$this->init();
// Check if we need to create a migration
if (isset($args[0]) && !empty($args[0])) {
$this->applyMigrations($args[0]);
} else {
$this->applyMigrations();
}
} catch (Exception $e) {
echo('ERROR: ' . $e->getMessage() . PHP_EOL);
}
}
/**
* Initialize the database migration engine. Several things happen during
* this initialization:
* - Constructs the full path to the migrations
* - The system checks if a database connection was configured.
* - The system checks if the database driver supports migrations.
* - If the schema_version table doesn't exist yet, it gets created.
*/
protected function init() {
// Construct the path to the migrations dir
$this->migrationsDir = Yii::app()->basePath;
if (!empty($module)) {
$this->migrationsDir .= '/modules/' . trim($module, '/');
}
$this->migrationsDir .= '/' . self::MIGRATIONS_DIR;
// Show the migrations directory
$dir = substr($this->migrationsDir, strlen(dirname(Yii::app()->basePath)) + 1) . '/';
echo('Migrations directory: ' . $dir . PHP_EOL . PHP_EOL);
// Check if a database connection was configured
try {
Yii::app()->db;
} catch (Exception $e) {
throw new CDbMigrationEngineException(
'Database configuration is missing in your configuration file.'
);
}
// Load the migration adapter
switch (Yii::app()->db->driverName) {
case 'mysql':
$this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
break;
case 'sqlite':
$this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
break;
default:
throw new CDbMigrationEngineException(
'Database of type ' . Yii::app()->db->driverName
. ' does not support migrations (yet).'
);
}
// Check if the schema version table exists
if (Yii::app()->db->schema->getTable('schema_version') == null) {
// Create the table
echo('Creating initial schema_version table' . PHP_EOL);
// Use the adapter to create the table
$this->adapter->createTable(
self::SCHEMA_TABLE,
array(
array(self::SCHEMA_FIELD, 'string'),
)
);
// Create an index on the column
$this->adapter->addIndex(
self::SCHEMA_TABLE,
'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
array(self::SCHEMA_FIELD),
true
);
}
}
/**
* Get the list of migrations that are applied to the database. This
* basically reads out the schema_version table from the database.
*
* @returns An array with the IDs of the already applied database
* migrations as found in the database.
*/
protected function getAppliedMigrations() {
// Get the field and table name
$field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
$table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
// Construct the SQL statement
$sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
// Get the list
- return Yii::app()->db->createCommand($sql)->queryColumn(
- self::SCHEMA_FIELD
- );
-
+ return Yii::app()->db->createCommand($sql)->queryColumn();
+
}
/**
* Get the list of possible migrations from the file system. This will read
* the contents of the migrations directory and the migrations directory
* inside each installed and enabled module.
*
* @returns An array with the IDs of the possible database migrations as
* found in the database.
*/
protected function getPossibleMigrations() {
// Get the migrations for the default application
$migrations = $this->getPossibleMigrationsForModule();
/*
// Get the migrations for each installed and enabled module
foreach (Yii::app()->modules as $module => $moduleData) {
$migrations = array_merge(
$migrations, $this->getPossibleMigrationsForModule($module)
);
}
*/
// Sort them based on the file path (which is the key in the array)
ksort($migrations);
// Returh the list of migrations
return $migrations;
}
/**
* A helper function to get the list of migrations for a specific module.
* If no module is specified, it will return the list of modules from the
* "protected/migrations" directory.
*
* @param $module The name of the module to get the migrations for.
*/
protected function getPossibleMigrationsForModule($module=null) {
// Start with an empty list
$migrations = array();
// Check if the migrations directory actually exists
if (is_dir($this->migrationsDir)) {
// Construct the list of migrations
$migrationFiles = CFileHelper::findFiles(
$this->migrationsDir,
array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
);
foreach ($migrationFiles as $migration) {
// Check if it's valid
if (substr(basename($migration), 0, 1) != 'm') {
continue;
}
// Include the file
include_once($migration);
// Get the class name
$className = basename($migration, '.' . self::SCHEMA_EXT);
// Check if the class exists
if (!class_exists($className) || strlen($className) < 16) {
continue;
}
// Check if the class is a valid migration
$migrationReflection = new ReflectionClass($className);
$baseReflection = new ReflectionClass('CDbMigration');
if (!$migrationReflection->isSubclassOf($baseReflection)) {
continue;
}
// Add them to the list
$id = substr($className, 1, 14);
$migrations[$id] = array(
'file' => $migration,
'class' => $className,
);
}
}
// Return the list
return $migrations;
}
/**
* Apply the migrations to the database. This will apply any migration that
* has not been applied to the database yet. It does this in a
* chronological order based on the IDs of the migrations.
*
* @param $version The version to migrate to. If you specify the special
* cases "up" or "down", it will go one migration "up" or
* "down". If it's a number, if will migrate "up" or "down"
* to that specific version.
*/
protected function applyMigrations($version='') {
// Get the list of applied and possible migrations
$applied = $this->getAppliedMigrations();
$possible = $this->getPossibleMigrations();
// Check what which action need to happen
if ($version == 'list') {
// List the status of all migrations
foreach ($possible as $id => $specs) {
$status = in_array($id, $applied) ? 'Applied: ' : 'Not Applied: ';
$name = substr(basename($specs['file'], '.php'), 1);
$name = str_replace('_', ' ', $name);
echo("${status} ${name}" . PHP_EOL);
}
} elseif ($version == 'create') {
// Get the name from the migration
$name = 'UntitledMigration';
if (isset($this->args[1]) && !empty($this->args[1])) {
$name = trim($this->args[1]);
}
$name = strftime('m%Y%m%d%H%M%S_' . $name);
// Read the template file
$data = file_get_contents(
dirname(__FILE__) . '/templates/migration.php'
);
$data = str_replace('${name}', $name, $data);
// Save the file
if (!is_dir($this->migrationsDir)) {
mkdir($this->migrationsDir);
}
file_put_contents(
$this->migrationsDir . '/' . $name . '.php', $data
);
echo('Created migration: ' . $dir . $name . '.php' . PHP_EOL);
} elseif ($version == 'down') {
// Get the last migration
$migration = array_pop($applied);
// Apply the migration
if ($migration) {
$this->applyMigration(
$possible[$migration]['class'],
$possible[$migration]['file'],
'down'
);
}
} elseif ($version == 'redo') {
// Redo the last migration
$this->applyMigrations('down');
$this->applyMigrations('up');
} elseif ($version == 'up') {
// Check if there are still versions to apply
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
// Exit the loop
break;
}
}
} elseif (!empty($version)) {
// Check if it's a valid version number
if (!isset($possible[$version])) {
throw new CDbMigrationEngineException(
'Invalid migration: ' . $version
);
}
// Check if we need to go up or down
if (in_array($version, $applied)) {
// Reverse loop over the possible migrations
foreach (array_reverse($possible, true) as $id => $specs) {
// If we reached the correct version, exit the loop
if ($id == $version) {
break;
}
// Check if it's applied or not
if (in_array($id, $applied)) {
// Remove the migration
$this->applyMigration(
$specs['class'], $specs['file'], 'down'
);
}
}
} else {
// Loop over all possible migrations
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
// If we applied the requested migration, exit the loop
if ($id == $version) {
break;
}
}
}
}
} else {
// Loop over all possible migrations
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
}
}
}
}
/**
* Apply a specific migration based on the migration name.
*
* @param $class The class name of the migration to apply.
* @param $file The file in which you can find the migration.
* @param $direction The direction in which the migration needs to be
* applied. Needs to be "up" or "down".
*/
protected function applyMigration($class, $file, $direction='up') {
// Include the migration file
require_once($file);
// Create the migration
$migration = new $class($this->adapter);
// Apply the migration
$msg = ($direction == 'up') ? 'Applying' : 'Removing';
$msg = str_pad('=== ' . $msg . ': ' . $class . ' ', 80, '=') . PHP_EOL;
echo($msg);
// Perform the migration function transactional
$migration->performTransactional($direction);
// Commit the migration
if ($direction == 'up') {
$cmd = Yii::app()->db->commandBuilder->createInsertCommand(
self::SCHEMA_TABLE,
array(self::SCHEMA_FIELD => $migration->getId())
)->execute();
$msg = 'applied';
} else {
$sql = 'DELETE FROM '
. $this->adapter->db->quoteTableName(self::SCHEMA_TABLE)
. ' WHERE '
. $this->adapter->db->quoteColumnName(self::SCHEMA_FIELD)
. ' = '
. $this->adapter->db->quoteValue($migration->getId());
$this->adapter->execute($sql);
$msg = 'removed';
}
$msg = str_pad('=== Marked as ' . $msg . ': ' . $class . ' ', 80, '=') . PHP_EOL . PHP_EOL;
echo($msg);
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | 7fe045d5f853e057bea3b9ab7c2cc99e18fa6ad0 | Change wording because it is possible to migrate down. Also clarify which file to put the command map into. | diff --git a/README.textile b/README.textile
index ae84c3c..7d50ad0 100644
--- a/README.textile
+++ b/README.textile
@@ -1,224 +1,222 @@
h1. Yii DB Migrations
A database migrations engine for the "Yii framework":http://www.yiiframework.com. It comes in the form of an extension which can be dropped into any existing Yii framework application.
It relies on the database abstraction layer of the Yii framework to talk to the database engine.
It's largely inspired on the migrations functionality of the Ruby on Rails framework.
h2. Why bother in the first place?
You might wonder why you need database migrations in the first place. Sure, you could use plain SQL files to apply updates to the database, but they have a big disadvantage: they are database specific.
Imagine you initially create your database using SQLite and later on decide to change to MySQL. When you use plain SQL files, you will need to rewrite them using MySQL's flavor of SQL. Also, you will need to create some tool that knows what has been applied already to the database and what's not applied yet.
Meet database migrations. By defining a higher level interface to creating and maintaining the database schema, you can define it in a database agnostic way.
By using PHP functions to create tables, indexes, fields, ... you can write the schema once and apply it to any database backend supported. The added bonus is that the yii-dbmigrations extension keeps track of which migrations have been applied already and which ones still need to be applied.
h2. Current limitations
Be aware that the current version is still very alpha.
There are only two database engines supported:
* MySQL
* SQLite
-In the current version, it's only possible to migrate up, it cannot (yet) remove already installed migrations.
-
h2. Installing the extension
h3. Putting the files in the right location
Installing the extension is quite easy. Once you downloaded the files from github, you need to put all the files in a folder called "yii-dbmigrations" and put it in the <code>protected/extensions</code> folder from your project.
h3. Configuring the database connection
You need to make sure you configure database access properly in the configuration file of your project. As the console applications in the Yii framework look at the <code>protected/config/console.php</code> file, you need to make sure you configure the <code>db</code> settings under the <code>components</code> key in the configuration array. For MySQL, the configuration will look as follows:
<pre>
'components' => array(
'db'=>array(
'class' => 'CDbConnection',
'connectionString'=>'mysql:host=localhost;dbname=my_db',
'charset' => 'UTF8',
'username'=>'root',
'password'=>'root',
),
),
</pre>
For SQLite, the configuration looks as follows:
<pre>
'components' => array(
'db'=>array(
'connectionString'=>'sqlite:'.dirname(__FILE__).'/../data/my_db.db',
),
),
</pre>
h3. Configuring the command map
-To make the <code>yiic</code> tool know about the <code>migrate</code> command, you need to add a <code>commandMap</code> key to the application configuration.
+To make the <code>yiic</code> tool know about the <code>migrate</code> command, you need to add a <code>commandMap</code> key to the application configuration in <code>protected/config/console.php</code>.
In there, you need to put the following configuration:
<pre>
'commandMap' => array(
'migrate' => array(
'class'=>'application.extensions.yii-dbmigrations.CDbMigrationCommand',
),
),
</pre>
h3. Testing your installation
To test if the installation was succesfull, you can run the yiic command and should see the following output:
<pre>
Yii command runner (based on Yii v1.0.6)
Usage: protected/yiic <command-name> [parameters...]
The following commands are available:
- migrate
- message
- shell
- webapp
To see individual command help, use the following:
protected/yiic help <command-name>
</pre>
It should mention that the <code>migrate</code> command is available.
h2. Creating migrations
h3. Naming conventions
You can create migrations by creating files in the <code>protected/migrations</code> folder or in the <code>migrations</code> folder inside your module. The file names for the migrations should follow a specific naming convention:
<pre>
m20090614213453_MigrationName.php
</pre>
The migration file names always start with the letter m followed by 14 digit timestamp and an underscore. After that, you can give a name to the migration so that you can easily identify the migration.
h3. Implementing the migration
In the migration file, you need to create a class that extends the parent class <code>CDbMigration</code>. The <code>CDbMigration</code> class needs to have the <code>up</code> and <code>down</code> methods as you can see in the following sample migration:
<pre>
class m20090611153243_CreateTables extends CDbMigration {
public function up() {
$this->createTable(
'posts',
array(
array('id', 'primary_key'),
array('title', 'string'),
array('body', 'text'),
)
);
$this->addIndex(
'posts', 'posts_title', array('title')
);
}
public function down() {
$this->removeTable('posts');
}
}
</pre>
h3. Supported functionality
In the migration class, you have the following functionality available:
* execute: execute a raw SQL statement that doesn't return any data.
* query: execute a raw SQL statement that returns data.
* createTable: create a new table
* renameTable: rename a table
* removeTable: remove a table
* addColumn: add a column to a table
* renameColumn: rename a column in a table
* changeColumn: change the definition of a column in a table
* removeColumn: remove a column from a table
* addIndex: add an index to the database or table
* removeIndex: remove an index from the database or table
When specifying fields, we also support a type mapping so that you can use generic type definitions instead of database specific type definitions. The following types are supported:
* primary_key
* string
* text
* integer
* float
* decimal
* datetime
* timestamp
* time
* date
* binary
* boolean
* bool
You can also specify a database specific type when defining a field, but this will make your migrations less portable across database engines.
h2. Applying migrations
Once you created the migrations, you can apply them to your database by running the <code>migrate</code> command:
<pre>
protected/yiic migrate
</pre>
You will see the following output:
<pre>
Creating initial schema_version table
Applying migration: m20090611153243_CreateTables
>> Creating table: posts
>> Adding index posts_title to table: posts
Marking migration as applied: m20090611153243_CreateTables
Applying migration: m20090612162832_CreateTags
>> Creating table: tags
>> Creating table: post_tags
>> Adding index post_tags_post_tag to table: post_tags
Marking migration as applied: m20090612162832_CreateTags
Applying migration: m20090612163144_RenameTagsTable
>> Renaming table: post_tags to: post_tags_link_table
Marking migration as applied: m20090612163144_RenameTagsTable
Applying migration: m20090616153243_Test_CreateTables
>> Creating table: test_pages
>> Adding index test_pages_title to table: test_pages
Marking migration as applied: m20090616153243_Test_CreateTables
</pre>
It will apply all the migrations found in the <code>protected/migrations</code> directory provided they were not applied to the database yet.
It will also apply any migrations found in the <code>migrations</code> directory inside each module which is enabled in the application.
If you run the <code>migrate</code> command again, it will show that the migrations were applied already:
<pre>
Skipping applied migration: m20090611153243_CreateTables
Skipping applied migration: m20090612162832_CreateTags
Skipping applied migration: m20090612163144_RenameTagsTable
Skipping applied migration: m20090616153243_Test_CreateTables
</pre>
Since the <code>migrate</code> command checks based on the ID of each migration, it can detect that a migration is already applied to the database and therefor doesn't need to be applied anymore.
h2. Author information
This extension is created and maintained by Pieter Claerhout. You can contact the author on:
* Website: "http://www.yellowduck.be":http://www.yellowduck.be
* Twitter: "http://twitter.com/pieterclaerhout":http://twitter.com/pieterclaerhout
* Github: "http://github.com/pieterclaerhout/yii-dbmigrations/tree/master":http://github.com/pieterclaerhout/yii-dbmigrations/tree/master
|
elchingon/yii-dbmigrations | 7ba69a970c97f81dfd5c490f3dc452cc2dc4b1d2 | When performing a redo on a migration, the migrations directory is now only shown once. | diff --git a/CDbMigrationEngine.php b/CDbMigrationEngine.php
index b05098a..0be45d4 100644
--- a/CDbMigrationEngine.php
+++ b/CDbMigrationEngine.php
@@ -1,496 +1,496 @@
<?php
/**
* CDbMigrationEngine class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the adapters we are going to use for the migrations.
*/
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* A database migration engine exception
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngineException extends Exception {}
/**
* The CDbMigrationEngine class is the actual engine that can do all the
* migrations related functionality.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngine {
/**
* The migration adapter to use
*/
private $adapter;
/**
* The name of the table that contains the schema information.
*/
const SCHEMA_TABLE = 'schema_version';
/**
* The field in the schema_version table that contains the id of the
* installed migrations.
*/
const SCHEMA_FIELD = 'id';
/**
* The extension used for the migration files.
*/
const SCHEMA_EXT = 'php';
/**
* The directory in which the migrations can be found.
*/
const MIGRATIONS_DIR = 'migrations';
/**
* The command line arguments passed to the system.
*/
private $args;
/**
* The full path to the migrations
*/
private $migrationsDir;
/**
* Run the database migration engine, passing on the command-line
* arguments.
*
* @param $args The command line parameters.
*/
public function run($args) {
// Catch errors
try {
// Remember the arguments
$this->args = $args;
// Initialize the engine
$this->init();
// Check if we need to create a migration
if (isset($args[0]) && !empty($args[0])) {
$this->applyMigrations($args[0]);
} else {
$this->applyMigrations();
}
} catch (Exception $e) {
echo('ERROR: ' . $e->getMessage() . PHP_EOL);
}
}
/**
* Initialize the database migration engine. Several things happen during
* this initialization:
* - Constructs the full path to the migrations
* - The system checks if a database connection was configured.
* - The system checks if the database driver supports migrations.
* - If the schema_version table doesn't exist yet, it gets created.
*/
protected function init() {
// Construct the path to the migrations dir
$this->migrationsDir = Yii::app()->basePath;
if (!empty($module)) {
$this->migrationsDir .= '/modules/' . trim($module, '/');
}
$this->migrationsDir .= '/' . self::MIGRATIONS_DIR;
+ // Show the migrations directory
+ $dir = substr($this->migrationsDir, strlen(dirname(Yii::app()->basePath)) + 1) . '/';
+ echo('Migrations directory: ' . $dir . PHP_EOL . PHP_EOL);
+
// Check if a database connection was configured
try {
Yii::app()->db;
} catch (Exception $e) {
throw new CDbMigrationEngineException(
'Database configuration is missing in your configuration file.'
);
}
// Load the migration adapter
switch (Yii::app()->db->driverName) {
case 'mysql':
$this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
break;
case 'sqlite':
$this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
break;
default:
throw new CDbMigrationEngineException(
'Database of type ' . Yii::app()->db->driverName
. ' does not support migrations (yet).'
);
}
// Check if the schema version table exists
if (Yii::app()->db->schema->getTable('schema_version') == null) {
// Create the table
echo('Creating initial schema_version table' . PHP_EOL);
// Use the adapter to create the table
$this->adapter->createTable(
self::SCHEMA_TABLE,
array(
array(self::SCHEMA_FIELD, 'string'),
)
);
// Create an index on the column
$this->adapter->addIndex(
self::SCHEMA_TABLE,
'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
array(self::SCHEMA_FIELD),
true
);
}
}
/**
* Get the list of migrations that are applied to the database. This
* basically reads out the schema_version table from the database.
*
* @returns An array with the IDs of the already applied database
* migrations as found in the database.
*/
protected function getAppliedMigrations() {
// Get the field and table name
$field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
$table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
// Construct the SQL statement
$sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
// Get the list
return Yii::app()->db->createCommand($sql)->queryColumn(
self::SCHEMA_FIELD
);
}
/**
* Get the list of possible migrations from the file system. This will read
* the contents of the migrations directory and the migrations directory
* inside each installed and enabled module.
*
* @returns An array with the IDs of the possible database migrations as
* found in the database.
*/
protected function getPossibleMigrations() {
// Get the migrations for the default application
$migrations = $this->getPossibleMigrationsForModule();
/*
// Get the migrations for each installed and enabled module
foreach (Yii::app()->modules as $module => $moduleData) {
$migrations = array_merge(
$migrations, $this->getPossibleMigrationsForModule($module)
);
}
*/
// Sort them based on the file path (which is the key in the array)
ksort($migrations);
// Returh the list of migrations
return $migrations;
}
/**
* A helper function to get the list of migrations for a specific module.
* If no module is specified, it will return the list of modules from the
* "protected/migrations" directory.
*
* @param $module The name of the module to get the migrations for.
*/
protected function getPossibleMigrationsForModule($module=null) {
// Start with an empty list
$migrations = array();
// Check if the migrations directory actually exists
if (is_dir($this->migrationsDir)) {
// Construct the list of migrations
$migrationFiles = CFileHelper::findFiles(
$this->migrationsDir,
array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
);
foreach ($migrationFiles as $migration) {
// Check if it's valid
if (substr(basename($migration), 0, 1) != 'm') {
continue;
}
// Include the file
include_once($migration);
// Get the class name
$className = basename($migration, '.' . self::SCHEMA_EXT);
// Check if the class exists
if (!class_exists($className) || strlen($className) < 16) {
continue;
}
// Check if the class is a valid migration
$migrationReflection = new ReflectionClass($className);
$baseReflection = new ReflectionClass('CDbMigration');
if (!$migrationReflection->isSubclassOf($baseReflection)) {
continue;
}
// Add them to the list
$id = substr($className, 1, 14);
$migrations[$id] = array(
'file' => $migration,
'class' => $className,
);
}
}
// Return the list
return $migrations;
}
/**
* Apply the migrations to the database. This will apply any migration that
* has not been applied to the database yet. It does this in a
* chronological order based on the IDs of the migrations.
*
* @param $version The version to migrate to. If you specify the special
* cases "up" or "down", it will go one migration "up" or
* "down". If it's a number, if will migrate "up" or "down"
* to that specific version.
*/
protected function applyMigrations($version='') {
// Get the list of applied and possible migrations
$applied = $this->getAppliedMigrations();
$possible = $this->getPossibleMigrations();
- // Show the migrations directory
- $dir = substr($this->migrationsDir, strlen(dirname(Yii::app()->basePath)) + 1) . '/';
- echo('Migrations directory: ' . $dir . PHP_EOL . PHP_EOL);
-
// Check what which action need to happen
if ($version == 'list') {
// List the status of all migrations
foreach ($possible as $id => $specs) {
$status = in_array($id, $applied) ? 'Applied: ' : 'Not Applied: ';
$name = substr(basename($specs['file'], '.php'), 1);
$name = str_replace('_', ' ', $name);
echo("${status} ${name}" . PHP_EOL);
}
} elseif ($version == 'create') {
// Get the name from the migration
$name = 'UntitledMigration';
if (isset($this->args[1]) && !empty($this->args[1])) {
$name = trim($this->args[1]);
}
$name = strftime('m%Y%m%d%H%M%S_' . $name);
// Read the template file
$data = file_get_contents(
dirname(__FILE__) . '/templates/migration.php'
);
$data = str_replace('${name}', $name, $data);
// Save the file
if (!is_dir($this->migrationsDir)) {
mkdir($this->migrationsDir);
}
file_put_contents(
$this->migrationsDir . '/' . $name . '.php', $data
);
echo('Created migration: ' . $dir . $name . '.php' . PHP_EOL);
} elseif ($version == 'down') {
// Get the last migration
$migration = array_pop($applied);
// Apply the migration
if ($migration) {
$this->applyMigration(
$possible[$migration]['class'],
$possible[$migration]['file'],
'down'
);
}
} elseif ($version == 'redo') {
// Redo the last migration
$this->applyMigrations('down');
$this->applyMigrations('up');
} elseif ($version == 'up') {
// Check if there are still versions to apply
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
// Exit the loop
break;
}
}
} elseif (!empty($version)) {
// Check if it's a valid version number
if (!isset($possible[$version])) {
throw new CDbMigrationEngineException(
'Invalid migration: ' . $version
);
}
// Check if we need to go up or down
if (in_array($version, $applied)) {
// Reverse loop over the possible migrations
foreach (array_reverse($possible, true) as $id => $specs) {
// If we reached the correct version, exit the loop
if ($id == $version) {
break;
}
// Check if it's applied or not
if (in_array($id, $applied)) {
// Remove the migration
$this->applyMigration(
$specs['class'], $specs['file'], 'down'
);
}
}
} else {
// Loop over all possible migrations
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
// If we applied the requested migration, exit the loop
if ($id == $version) {
break;
}
}
}
}
} else {
// Loop over all possible migrations
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
}
}
}
}
/**
* Apply a specific migration based on the migration name.
*
* @param $class The class name of the migration to apply.
* @param $file The file in which you can find the migration.
* @param $direction The direction in which the migration needs to be
* applied. Needs to be "up" or "down".
*/
protected function applyMigration($class, $file, $direction='up') {
// Include the migration file
require_once($file);
// Create the migration
$migration = new $class($this->adapter);
// Apply the migration
$msg = ($direction == 'up') ? 'Applying' : 'Removing';
$msg = str_pad('=== ' . $msg . ': ' . $class . ' ', 80, '=') . PHP_EOL;
echo($msg);
// Perform the migration function transactional
$migration->performTransactional($direction);
// Commit the migration
if ($direction == 'up') {
$cmd = Yii::app()->db->commandBuilder->createInsertCommand(
self::SCHEMA_TABLE,
array(self::SCHEMA_FIELD => $migration->getId())
)->execute();
$msg = 'applied';
} else {
$sql = 'DELETE FROM '
. $this->adapter->db->quoteTableName(self::SCHEMA_TABLE)
. ' WHERE '
. $this->adapter->db->quoteColumnName(self::SCHEMA_FIELD)
. ' = '
. $this->adapter->db->quoteValue($migration->getId());
$this->adapter->execute($sql);
$msg = 'removed';
}
$msg = str_pad('=== Marked as ' . $msg . ': ' . $class . ' ', 80, '=') . PHP_EOL . PHP_EOL;
echo($msg);
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | 0d51e48873271c5eba96d159e16306fb97eafd2c | Fixed the message emitted when changing a table column | diff --git a/CDbMigration.php b/CDbMigration.php
index 52e85aa..f93eafd 100644
--- a/CDbMigration.php
+++ b/CDbMigration.php
@@ -1,269 +1,269 @@
<?php
/**
* CDbMigration class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* @package extensions.yii-dbmigrations
*/
class CDbMigrationException extends Exception {}
/**
* This class abstracts a database migration. The main functions that you will
* need to implement for creating a migration are the up and down methods.
*
* The up method will be applied when the migration gets installed into the
* system, the down method when the migration gets removed from the system.
*
* @package extensions.yii-dbmigrations
*/
abstract class CDbMigration {
/**
* The CDbMigrationAdapater that is used to perform the actual migrations
* on the database.
*/
public $adapter;
/**
* Class constructor for the CDbMigration class.
*
* @param $adapter The CDbMigrationAdapater that is used to perform the
* actual migrations on the database.
*/
public function __construct(CDbMigrationAdapter $adapter) {
$this->adapter = $adapter;
}
/**
* This method will execute the given class method inside a database
* transaction. It will raise an exception if the class method doesn't
* exist.
*
* For the transaction handling, we rely on the Yii DB functionality. If
* the database doesn't support transactions, the SQL statements will be
* executed one after another without using transactions.
*
* If the command succeeds, the transaction will get committed, if not, a
* rollback of the transaction will happen.
*
* @param $command The name of the class method to execute.
*/
public function performTransactional($command) {
// Check if the class method exists
if (!method_exists($this, $command)) {
throw new CDbMigrationException(
'Invalid migration command: ' . $command
);
}
// Run the command inside a transaction
$transaction = $this->adapter->db->beginTransaction();
try {
$this->$command();
$transaction->commit();
} catch (Exception $e) {
$transaction->rollback();
throw new CDbMigrationException($e->getMessage());
}
}
/**
* The up class method contains all the statements that will be executed
* when the migration is applied to the database.
*/
public function up() {
}
/**
* The up class method contains all the statements that will be executed
* when the migration is removed the database.
*/
public function down() {
}
/**
* This function returns the ID of the migration.
*
* Given the following migration class name:
*
* <code>m20090611153243_CreateTables</code>
*
* The id for this migration will be:
*
* <code>20090611153243</code>
*
* @returns The ID of the migration.
*/
public function getId() {
$id = split('_', get_class($this));
return substr($id[0], 1);
}
/**
* This function returns the name of the migration.
*
* Given the following migration class name:
*
* <code>m20090611153243_CreateTables</code>
*
* The name for this migration will be:
*
* <code>CreateTables</code>
*
* @returns The name of the migration.
*/
public function getName() {
$name = split('_', get_class($this));
return join('_', array_slice($name, 1, sizeof($name) - 1));
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that doesn't return any data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The number of affected rows.
*/
protected function execute($query, $params=array()) {
return $this->adapter->execute($query, $params);
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that returns data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The rows returned from the database.
*/
protected function query($query, $params=array()) {
return $this->adapter->query($query, $params);
}
/**
* The createTable function allows you to create a new table in the
* database.
*
* @param $name The name of the table to create.
* @param $column The column definition for the database table
* @param $options The extra options to pass to the database creation.
*/
protected function createTable($name, $columns=array(), $options=null) {
echo(' >> Creating table: ' . $name . PHP_EOL);
return $this->adapter->createTable($name, $columns, $options);
}
/**
* Rename a table.
*
* @param $name The name of the table to rename.
* @param $new_name The new name for the table.
*/
protected function renameTable($name, $new_name) {
echo(' >> Renaming table: ' . $name . ' to: ' . $new_name . PHP_EOL);
return $this->adapter->renameTable($name, $new_name);
}
/**
* Remove a table from the database.
*
* @param $name The name of the table to remove.
*/
protected function removeTable($name) {
echo(' >> Removing table: ' . $name . PHP_EOL);
return $this->adapter->removeTable($name);
}
/**
* Add a database column to an existing table.
*
* @param $table The table to add the column in.
* @param $column The name of the column to add.
* @param $type The data type for the new column.
* @param $options The extra options to pass to the column.
*/
protected function addColumn($table, $column, $type, $options=null) {
echo(' >> Adding column ' . $column . ' to table: ' . $table . PHP_EOL);
return $this->adapter->addColumn($table, $column, $type, $options);
}
/**
* Rename a database column in an existing table.
*
* @param $table The table to rename the column from.
* @param $name The current name of the column.
* @param $new_name The new name of the column.
*/
protected function renameColumn($table, $name, $new_name) {
echo(
' >> Renaming column ' . $name . ' to: ' . $new_name
. ' in table: ' . $table . PHP_EOL
);
return $this->adapter->renameColumn($table, $name, $new_name);
}
/**
* Change a database column in an existing table.
*
* @param $table The name of the table to change the column from.
* @param $column The name of the column to change.
* @param $type The new data type for the column.
* @param $options The extra options to pass to the column.
*/
protected function changeColumn($table, $column, $type, $options=null) {
echo(
- ' >> Chaning column ' . $name . ' to: ' . $type
+ ' >> Changing column ' . $column . ' to: ' . $type
. ' in table: ' . $table . PHP_EOL
);
return $this->adapter->changeColumn($table, $column, $type, $options);
}
/**
* Remove a table column from the database.
*
* @param $table The name of the table to remove the column from.
* @param $column The name of the table column to remove.
*/
protected function removeColumn($table, $column) {
echo(
' >> Removing column ' . $column . ' from table: ' . $table . PHP_EOL
);
return $this->adapter->removeColumn($table, $column);
}
/**
* Add an index to the database or a specific table.
*
* @param $table The name of the table to add the index to.
* @param $name The name of the index to create.
* @param $columns The name of the fields to include in the index.
* @param $unique If set to true, a unique index will be created.
*/
public function addIndex($table, $name, $columns, $unique=false) {
echo(' >> Adding index ' . $name . ' to table: ' . $table . PHP_EOL);
return $this->adapter->addIndex($table, $name, $columns, $unique);
}
/**
* Remove a table index from the database.
*
* @param $table The name of the table to remove the index from.
* @param $column The name of the table index to remove.
*/
protected function removeIndex($table, $name) {
echo(' >> Removing index ' . $name . ' from table: ' . $table . PHP_EOL);
return $this->adapter->removeIndex($table, $name);
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | e4951da0902efb971206eb2ffc08737c82efadbb | The migration engine now show the directory in which the migrations are created. | diff --git a/CDbMigrationEngine.php b/CDbMigrationEngine.php
index f420eb9..b05098a 100644
--- a/CDbMigrationEngine.php
+++ b/CDbMigrationEngine.php
@@ -1,492 +1,496 @@
<?php
/**
* CDbMigrationEngine class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the adapters we are going to use for the migrations.
*/
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* A database migration engine exception
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngineException extends Exception {}
/**
* The CDbMigrationEngine class is the actual engine that can do all the
* migrations related functionality.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngine {
/**
* The migration adapter to use
*/
private $adapter;
/**
* The name of the table that contains the schema information.
*/
const SCHEMA_TABLE = 'schema_version';
/**
* The field in the schema_version table that contains the id of the
* installed migrations.
*/
const SCHEMA_FIELD = 'id';
/**
* The extension used for the migration files.
*/
const SCHEMA_EXT = 'php';
/**
* The directory in which the migrations can be found.
*/
const MIGRATIONS_DIR = 'migrations';
/**
* The command line arguments passed to the system.
*/
private $args;
/**
* The full path to the migrations
*/
private $migrationsDir;
/**
* Run the database migration engine, passing on the command-line
* arguments.
*
* @param $args The command line parameters.
*/
public function run($args) {
// Catch errors
try {
// Remember the arguments
$this->args = $args;
// Initialize the engine
$this->init();
// Check if we need to create a migration
if (isset($args[0]) && !empty($args[0])) {
$this->applyMigrations($args[0]);
} else {
$this->applyMigrations();
}
} catch (Exception $e) {
echo('ERROR: ' . $e->getMessage() . PHP_EOL);
}
}
/**
* Initialize the database migration engine. Several things happen during
* this initialization:
* - Constructs the full path to the migrations
* - The system checks if a database connection was configured.
* - The system checks if the database driver supports migrations.
* - If the schema_version table doesn't exist yet, it gets created.
*/
protected function init() {
// Construct the path to the migrations dir
$this->migrationsDir = Yii::app()->basePath;
if (!empty($module)) {
$this->migrationsDir .= '/modules/' . trim($module, '/');
}
$this->migrationsDir .= '/' . self::MIGRATIONS_DIR;
// Check if a database connection was configured
try {
Yii::app()->db;
} catch (Exception $e) {
throw new CDbMigrationEngineException(
'Database configuration is missing in your configuration file.'
);
}
// Load the migration adapter
switch (Yii::app()->db->driverName) {
case 'mysql':
$this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
break;
case 'sqlite':
$this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
break;
default:
throw new CDbMigrationEngineException(
'Database of type ' . Yii::app()->db->driverName
. ' does not support migrations (yet).'
);
}
// Check if the schema version table exists
if (Yii::app()->db->schema->getTable('schema_version') == null) {
// Create the table
echo('Creating initial schema_version table' . PHP_EOL);
// Use the adapter to create the table
$this->adapter->createTable(
self::SCHEMA_TABLE,
array(
array(self::SCHEMA_FIELD, 'string'),
)
);
// Create an index on the column
$this->adapter->addIndex(
self::SCHEMA_TABLE,
'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
array(self::SCHEMA_FIELD),
true
);
}
}
/**
* Get the list of migrations that are applied to the database. This
* basically reads out the schema_version table from the database.
*
* @returns An array with the IDs of the already applied database
* migrations as found in the database.
*/
protected function getAppliedMigrations() {
// Get the field and table name
$field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
$table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
// Construct the SQL statement
$sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
// Get the list
return Yii::app()->db->createCommand($sql)->queryColumn(
self::SCHEMA_FIELD
);
}
/**
* Get the list of possible migrations from the file system. This will read
* the contents of the migrations directory and the migrations directory
* inside each installed and enabled module.
*
* @returns An array with the IDs of the possible database migrations as
* found in the database.
*/
protected function getPossibleMigrations() {
// Get the migrations for the default application
$migrations = $this->getPossibleMigrationsForModule();
/*
// Get the migrations for each installed and enabled module
foreach (Yii::app()->modules as $module => $moduleData) {
$migrations = array_merge(
$migrations, $this->getPossibleMigrationsForModule($module)
);
}
*/
// Sort them based on the file path (which is the key in the array)
ksort($migrations);
// Returh the list of migrations
return $migrations;
}
/**
* A helper function to get the list of migrations for a specific module.
* If no module is specified, it will return the list of modules from the
* "protected/migrations" directory.
*
* @param $module The name of the module to get the migrations for.
*/
protected function getPossibleMigrationsForModule($module=null) {
// Start with an empty list
$migrations = array();
// Check if the migrations directory actually exists
if (is_dir($this->migrationsDir)) {
// Construct the list of migrations
$migrationFiles = CFileHelper::findFiles(
$this->migrationsDir,
array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
);
foreach ($migrationFiles as $migration) {
// Check if it's valid
if (substr(basename($migration), 0, 1) != 'm') {
continue;
}
// Include the file
include_once($migration);
// Get the class name
$className = basename($migration, '.' . self::SCHEMA_EXT);
// Check if the class exists
if (!class_exists($className) || strlen($className) < 16) {
continue;
}
// Check if the class is a valid migration
$migrationReflection = new ReflectionClass($className);
$baseReflection = new ReflectionClass('CDbMigration');
if (!$migrationReflection->isSubclassOf($baseReflection)) {
continue;
}
// Add them to the list
$id = substr($className, 1, 14);
$migrations[$id] = array(
'file' => $migration,
'class' => $className,
);
}
}
// Return the list
return $migrations;
}
/**
* Apply the migrations to the database. This will apply any migration that
* has not been applied to the database yet. It does this in a
* chronological order based on the IDs of the migrations.
*
* @param $version The version to migrate to. If you specify the special
* cases "up" or "down", it will go one migration "up" or
* "down". If it's a number, if will migrate "up" or "down"
* to that specific version.
*/
protected function applyMigrations($version='') {
// Get the list of applied and possible migrations
$applied = $this->getAppliedMigrations();
$possible = $this->getPossibleMigrations();
+ // Show the migrations directory
+ $dir = substr($this->migrationsDir, strlen(dirname(Yii::app()->basePath)) + 1) . '/';
+ echo('Migrations directory: ' . $dir . PHP_EOL . PHP_EOL);
+
// Check what which action need to happen
if ($version == 'list') {
// List the status of all migrations
foreach ($possible as $id => $specs) {
$status = in_array($id, $applied) ? 'Applied: ' : 'Not Applied: ';
$name = substr(basename($specs['file'], '.php'), 1);
$name = str_replace('_', ' ', $name);
echo("${status} ${name}" . PHP_EOL);
}
} elseif ($version == 'create') {
// Get the name from the migration
$name = 'UntitledMigration';
if (isset($this->args[1]) && !empty($this->args[1])) {
$name = trim($this->args[1]);
}
$name = strftime('m%Y%m%d%H%M%S_' . $name);
// Read the template file
$data = file_get_contents(
dirname(__FILE__) . '/templates/migration.php'
);
$data = str_replace('${name}', $name, $data);
// Save the file
if (!is_dir($this->migrationsDir)) {
mkdir($this->migrationsDir);
}
file_put_contents(
$this->migrationsDir . '/' . $name . '.php', $data
);
- echo('Created migration: ' . $name . '.php' . PHP_EOL);
+ echo('Created migration: ' . $dir . $name . '.php' . PHP_EOL);
} elseif ($version == 'down') {
// Get the last migration
$migration = array_pop($applied);
// Apply the migration
if ($migration) {
$this->applyMigration(
$possible[$migration]['class'],
$possible[$migration]['file'],
'down'
);
}
} elseif ($version == 'redo') {
// Redo the last migration
$this->applyMigrations('down');
$this->applyMigrations('up');
} elseif ($version == 'up') {
// Check if there are still versions to apply
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
// Exit the loop
break;
}
}
} elseif (!empty($version)) {
// Check if it's a valid version number
if (!isset($possible[$version])) {
throw new CDbMigrationEngineException(
'Invalid migration: ' . $version
);
}
// Check if we need to go up or down
if (in_array($version, $applied)) {
// Reverse loop over the possible migrations
foreach (array_reverse($possible, true) as $id => $specs) {
// If we reached the correct version, exit the loop
if ($id == $version) {
break;
}
// Check if it's applied or not
if (in_array($id, $applied)) {
// Remove the migration
$this->applyMigration(
$specs['class'], $specs['file'], 'down'
);
}
}
} else {
// Loop over all possible migrations
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
// If we applied the requested migration, exit the loop
if ($id == $version) {
break;
}
}
}
}
} else {
// Loop over all possible migrations
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
}
}
}
}
/**
* Apply a specific migration based on the migration name.
*
* @param $class The class name of the migration to apply.
* @param $file The file in which you can find the migration.
* @param $direction The direction in which the migration needs to be
* applied. Needs to be "up" or "down".
*/
protected function applyMigration($class, $file, $direction='up') {
// Include the migration file
require_once($file);
// Create the migration
$migration = new $class($this->adapter);
// Apply the migration
$msg = ($direction == 'up') ? 'Applying' : 'Removing';
$msg = str_pad('=== ' . $msg . ': ' . $class . ' ', 80, '=') . PHP_EOL;
echo($msg);
// Perform the migration function transactional
$migration->performTransactional($direction);
// Commit the migration
if ($direction == 'up') {
$cmd = Yii::app()->db->commandBuilder->createInsertCommand(
self::SCHEMA_TABLE,
array(self::SCHEMA_FIELD => $migration->getId())
)->execute();
$msg = 'applied';
} else {
$sql = 'DELETE FROM '
. $this->adapter->db->quoteTableName(self::SCHEMA_TABLE)
. ' WHERE '
. $this->adapter->db->quoteColumnName(self::SCHEMA_FIELD)
. ' = '
. $this->adapter->db->quoteValue($migration->getId());
$this->adapter->execute($sql);
$msg = 'removed';
}
$msg = str_pad('=== Marked as ' . $msg . ': ' . $class . ' ', 80, '=') . PHP_EOL . PHP_EOL;
echo($msg);
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | b9f13a4c5362edefcb8f2bed1fbc1a1c37bea508 | When running migrations, a constant called YII_MIGRATING is now defined. | diff --git a/CDbMigrationCommand.php b/CDbMigrationCommand.php
index acf2905..ff209ac 100644
--- a/CDbMigrationCommand.php
+++ b/CDbMigrationCommand.php
@@ -1,98 +1,110 @@
<?php
/**
* CDbMigrationCommand class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the different extension components.
*/
Yii::import('application.extensions.yii-dbmigrations.*');
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* This class creates the migrate console command so that you can use it with
* the yiic tool inside your project.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationCommand extends CConsoleCommand {
/**
* Return the help for the migrate command.
*/
public function getHelp() {
return <<<EOD
USAGE
migrate [create|version|up|down|list]
DESCRIPTION
This command applies the database migrations which can be found in the
migrations directory in your project folder.
PARAMETERS
* create: creates a new migration in the migrations directory.
* version: options, the ID of the migration to migrate the database to.
* up: optional, apply the first migration that is not applied to the database
yet.
* down: remove the last applied migration from the database.
* redo: redo the last migration (removes and installs it again)
* list: list all the migrations available in the application and show if they
are applied or not.
EXAMPLES
* Apply all migrations that are not applied yet:
migrate
* Migrate up to version 20090612163144 if it's not applied yet:
migrate 20090612163144
* Migrate down to version 20090612163144 if it's applied already:
migrate 20090612163144
* Apply the first migration that is not applied to the database yet:
migrate up
* Remove the last applied migration:
migrate down
* Re-apply the last applied migration:
migrate redo
* List all the migrations found in the application and their status:
migrate list
* Create a new migration
migrate create
* Create a new name migration
migrate create MyMigrationName
EOD;
}
/**
* Runs the actual command passing along the command line parameters.
*
* @param $args The command line parameters
*/
public function run($args) {
+
+ // Catch errors
try {
+
+ // Set a constant so that we know we are running migrations
+ define('YII_MIGRATING', true);
+
+ // Create the engine and run it
$engine = new CDbMigrationEngine();
$engine->run($args);
+
} catch (Exception $e) {
+
+ // Something went wrong, show the error message
echo('FATAL ERROR: ' . $e->getMessage());
+
}
+
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | a5a90e1a7c64582f49fbb0540de260fd667e1e68 | The output from the migrations is now a little more compact. | diff --git a/CDbMigrationEngine.php b/CDbMigrationEngine.php
index ee38e10..f420eb9 100644
--- a/CDbMigrationEngine.php
+++ b/CDbMigrationEngine.php
@@ -1,498 +1,492 @@
<?php
/**
* CDbMigrationEngine class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the adapters we are going to use for the migrations.
*/
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* A database migration engine exception
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngineException extends Exception {}
/**
* The CDbMigrationEngine class is the actual engine that can do all the
* migrations related functionality.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngine {
/**
* The migration adapter to use
*/
private $adapter;
/**
* The name of the table that contains the schema information.
*/
const SCHEMA_TABLE = 'schema_version';
/**
* The field in the schema_version table that contains the id of the
* installed migrations.
*/
const SCHEMA_FIELD = 'id';
/**
* The extension used for the migration files.
*/
const SCHEMA_EXT = 'php';
/**
* The directory in which the migrations can be found.
*/
const MIGRATIONS_DIR = 'migrations';
/**
* The command line arguments passed to the system.
*/
private $args;
/**
* The full path to the migrations
*/
private $migrationsDir;
/**
* Run the database migration engine, passing on the command-line
* arguments.
*
* @param $args The command line parameters.
*/
public function run($args) {
// Catch errors
try {
// Remember the arguments
$this->args = $args;
// Initialize the engine
$this->init();
// Check if we need to create a migration
if (isset($args[0]) && !empty($args[0])) {
$this->applyMigrations($args[0]);
} else {
$this->applyMigrations();
}
} catch (Exception $e) {
echo('ERROR: ' . $e->getMessage() . PHP_EOL);
}
}
/**
* Initialize the database migration engine. Several things happen during
* this initialization:
* - Constructs the full path to the migrations
* - The system checks if a database connection was configured.
* - The system checks if the database driver supports migrations.
* - If the schema_version table doesn't exist yet, it gets created.
*/
protected function init() {
// Construct the path to the migrations dir
$this->migrationsDir = Yii::app()->basePath;
if (!empty($module)) {
$this->migrationsDir .= '/modules/' . trim($module, '/');
}
$this->migrationsDir .= '/' . self::MIGRATIONS_DIR;
// Check if a database connection was configured
try {
Yii::app()->db;
} catch (Exception $e) {
throw new CDbMigrationEngineException(
'Database configuration is missing in your configuration file.'
);
}
// Load the migration adapter
switch (Yii::app()->db->driverName) {
case 'mysql':
$this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
break;
case 'sqlite':
$this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
break;
default:
throw new CDbMigrationEngineException(
'Database of type ' . Yii::app()->db->driverName
. ' does not support migrations (yet).'
);
}
// Check if the schema version table exists
if (Yii::app()->db->schema->getTable('schema_version') == null) {
// Create the table
echo('Creating initial schema_version table' . PHP_EOL);
// Use the adapter to create the table
$this->adapter->createTable(
self::SCHEMA_TABLE,
array(
array(self::SCHEMA_FIELD, 'string'),
)
);
// Create an index on the column
$this->adapter->addIndex(
self::SCHEMA_TABLE,
'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
array(self::SCHEMA_FIELD),
true
);
}
}
/**
* Get the list of migrations that are applied to the database. This
* basically reads out the schema_version table from the database.
*
* @returns An array with the IDs of the already applied database
* migrations as found in the database.
*/
protected function getAppliedMigrations() {
// Get the field and table name
$field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
$table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
// Construct the SQL statement
$sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
// Get the list
return Yii::app()->db->createCommand($sql)->queryColumn(
self::SCHEMA_FIELD
);
}
/**
* Get the list of possible migrations from the file system. This will read
* the contents of the migrations directory and the migrations directory
* inside each installed and enabled module.
*
* @returns An array with the IDs of the possible database migrations as
* found in the database.
*/
protected function getPossibleMigrations() {
// Get the migrations for the default application
$migrations = $this->getPossibleMigrationsForModule();
/*
// Get the migrations for each installed and enabled module
foreach (Yii::app()->modules as $module => $moduleData) {
$migrations = array_merge(
$migrations, $this->getPossibleMigrationsForModule($module)
);
}
*/
// Sort them based on the file path (which is the key in the array)
ksort($migrations);
// Returh the list of migrations
return $migrations;
}
/**
* A helper function to get the list of migrations for a specific module.
* If no module is specified, it will return the list of modules from the
* "protected/migrations" directory.
*
* @param $module The name of the module to get the migrations for.
*/
protected function getPossibleMigrationsForModule($module=null) {
// Start with an empty list
$migrations = array();
// Check if the migrations directory actually exists
if (is_dir($this->migrationsDir)) {
// Construct the list of migrations
$migrationFiles = CFileHelper::findFiles(
$this->migrationsDir,
array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
);
foreach ($migrationFiles as $migration) {
// Check if it's valid
if (substr(basename($migration), 0, 1) != 'm') {
continue;
}
// Include the file
include_once($migration);
// Get the class name
$className = basename($migration, '.' . self::SCHEMA_EXT);
// Check if the class exists
if (!class_exists($className) || strlen($className) < 16) {
continue;
}
// Check if the class is a valid migration
$migrationReflection = new ReflectionClass($className);
$baseReflection = new ReflectionClass('CDbMigration');
if (!$migrationReflection->isSubclassOf($baseReflection)) {
continue;
}
// Add them to the list
$id = substr($className, 1, 14);
$migrations[$id] = array(
'file' => $migration,
'class' => $className,
);
}
}
// Return the list
return $migrations;
}
/**
* Apply the migrations to the database. This will apply any migration that
* has not been applied to the database yet. It does this in a
* chronological order based on the IDs of the migrations.
*
* @param $version The version to migrate to. If you specify the special
* cases "up" or "down", it will go one migration "up" or
* "down". If it's a number, if will migrate "up" or "down"
* to that specific version.
*/
protected function applyMigrations($version='') {
// Get the list of applied and possible migrations
$applied = $this->getAppliedMigrations();
$possible = $this->getPossibleMigrations();
// Check what which action need to happen
if ($version == 'list') {
// List the status of all migrations
foreach ($possible as $id => $specs) {
$status = in_array($id, $applied) ? 'Applied: ' : 'Not Applied: ';
$name = substr(basename($specs['file'], '.php'), 1);
$name = str_replace('_', ' ', $name);
echo("${status} ${name}" . PHP_EOL);
}
} elseif ($version == 'create') {
// Get the name from the migration
$name = 'UntitledMigration';
if (isset($this->args[1]) && !empty($this->args[1])) {
$name = trim($this->args[1]);
}
$name = strftime('m%Y%m%d%H%M%S_' . $name);
// Read the template file
$data = file_get_contents(
dirname(__FILE__) . '/templates/migration.php'
);
$data = str_replace('${name}', $name, $data);
// Save the file
if (!is_dir($this->migrationsDir)) {
mkdir($this->migrationsDir);
}
file_put_contents(
$this->migrationsDir . '/' . $name . '.php', $data
);
echo('Created migration: ' . $name . '.php' . PHP_EOL);
} elseif ($version == 'down') {
// Get the last migration
$migration = array_pop($applied);
// Apply the migration
if ($migration) {
$this->applyMigration(
$possible[$migration]['class'],
$possible[$migration]['file'],
'down'
);
}
} elseif ($version == 'redo') {
// Redo the last migration
$this->applyMigrations('down');
$this->applyMigrations('up');
} elseif ($version == 'up') {
// Check if there are still versions to apply
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
// Exit the loop
break;
}
}
} elseif (!empty($version)) {
// Check if it's a valid version number
if (!isset($possible[$version])) {
throw new CDbMigrationEngineException(
'Invalid migration: ' . $version
);
}
// Check if we need to go up or down
if (in_array($version, $applied)) {
// Reverse loop over the possible migrations
foreach (array_reverse($possible, true) as $id => $specs) {
// If we reached the correct version, exit the loop
if ($id == $version) {
break;
}
// Check if it's applied or not
if (in_array($id, $applied)) {
// Remove the migration
$this->applyMigration(
$specs['class'], $specs['file'], 'down'
);
}
}
} else {
// Loop over all possible migrations
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
// If we applied the requested migration, exit the loop
if ($id == $version) {
break;
}
}
}
}
} else {
// Loop over all possible migrations
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
}
}
}
}
/**
* Apply a specific migration based on the migration name.
*
* @param $class The class name of the migration to apply.
* @param $file The file in which you can find the migration.
* @param $direction The direction in which the migration needs to be
* applied. Needs to be "up" or "down".
*/
protected function applyMigration($class, $file, $direction='up') {
// Include the migration file
require_once($file);
// Create the migration
$migration = new $class($this->adapter);
// Apply the migration
- if ($direction == 'up') {
- echo('=== Applying migration: ' . $class . ' =========' . PHP_EOL);
- } else {
- echo('=== Removing migration: ' . $class . ' =========' . PHP_EOL);
- }
- echo(PHP_EOL);
+ $msg = ($direction == 'up') ? 'Applying' : 'Removing';
+ $msg = str_pad('=== ' . $msg . ': ' . $class . ' ', 80, '=') . PHP_EOL;
+ echo($msg);
// Perform the migration function transactional
$migration->performTransactional($direction);
// Commit the migration
- echo(PHP_EOL);
if ($direction == 'up') {
- echo(
- ' Marking migration as applied: ' . $class . PHP_EOL . PHP_EOL
- );
$cmd = Yii::app()->db->commandBuilder->createInsertCommand(
self::SCHEMA_TABLE,
array(self::SCHEMA_FIELD => $migration->getId())
)->execute();
+ $msg = 'applied';
} else {
- echo(
- ' Marking migration as removed: ' . $class . PHP_EOL . PHP_EOL
- );
$sql = 'DELETE FROM '
. $this->adapter->db->quoteTableName(self::SCHEMA_TABLE)
. ' WHERE '
. $this->adapter->db->quoteColumnName(self::SCHEMA_FIELD)
. ' = '
. $this->adapter->db->quoteValue($migration->getId());
$this->adapter->execute($sql);
+ $msg = 'removed';
}
+ $msg = str_pad('=== Marked as ' . $msg . ': ' . $class . ' ', 80, '=') . PHP_EOL . PHP_EOL;
+ echo($msg);
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | 5ee9f5c9d109b180840b25f899d7f929c5a4e2cb | Added the redo command so that the last migration can be re-applied easily. | diff --git a/CDbMigrationCommand.php b/CDbMigrationCommand.php
index 9d9d965..acf2905 100644
--- a/CDbMigrationCommand.php
+++ b/CDbMigrationCommand.php
@@ -1,93 +1,98 @@
<?php
/**
* CDbMigrationCommand class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the different extension components.
*/
Yii::import('application.extensions.yii-dbmigrations.*');
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* This class creates the migrate console command so that you can use it with
* the yiic tool inside your project.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationCommand extends CConsoleCommand {
/**
* Return the help for the migrate command.
*/
public function getHelp() {
return <<<EOD
USAGE
migrate [create|version|up|down|list]
DESCRIPTION
This command applies the database migrations which can be found in the
migrations directory in your project folder.
PARAMETERS
* create: creates a new migration in the migrations directory.
* version: options, the ID of the migration to migrate the database to.
* up: optional, apply the first migration that is not applied to the database
yet.
* down: remove the last applied migration from the database.
+
+ * redo: redo the last migration (removes and installs it again)
* list: list all the migrations available in the application and show if they
are applied or not.
EXAMPLES
* Apply all migrations that are not applied yet:
migrate
* Migrate up to version 20090612163144 if it's not applied yet:
migrate 20090612163144
* Migrate down to version 20090612163144 if it's applied already:
migrate 20090612163144
* Apply the first migration that is not applied to the database yet:
migrate up
* Remove the last applied migration:
migrate down
-
+
+ * Re-apply the last applied migration:
+ migrate redo
+
* List all the migrations found in the application and their status:
migrate list
* Create a new migration
migrate create
* Create a new name migration
migrate create MyMigrationName
EOD;
}
/**
* Runs the actual command passing along the command line parameters.
*
* @param $args The command line parameters
*/
public function run($args) {
try {
$engine = new CDbMigrationEngine();
$engine->run($args);
} catch (Exception $e) {
echo('FATAL ERROR: ' . $e->getMessage());
}
}
}
\ No newline at end of file
diff --git a/CDbMigrationEngine.php b/CDbMigrationEngine.php
index 4c04d1a..ee38e10 100644
--- a/CDbMigrationEngine.php
+++ b/CDbMigrationEngine.php
@@ -1,492 +1,498 @@
<?php
/**
* CDbMigrationEngine class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the adapters we are going to use for the migrations.
*/
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* A database migration engine exception
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngineException extends Exception {}
/**
* The CDbMigrationEngine class is the actual engine that can do all the
* migrations related functionality.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngine {
/**
* The migration adapter to use
*/
private $adapter;
/**
* The name of the table that contains the schema information.
*/
const SCHEMA_TABLE = 'schema_version';
/**
* The field in the schema_version table that contains the id of the
* installed migrations.
*/
const SCHEMA_FIELD = 'id';
/**
* The extension used for the migration files.
*/
const SCHEMA_EXT = 'php';
/**
* The directory in which the migrations can be found.
*/
const MIGRATIONS_DIR = 'migrations';
/**
* The command line arguments passed to the system.
*/
private $args;
/**
* The full path to the migrations
*/
private $migrationsDir;
/**
* Run the database migration engine, passing on the command-line
* arguments.
*
* @param $args The command line parameters.
*/
public function run($args) {
// Catch errors
try {
// Remember the arguments
$this->args = $args;
// Initialize the engine
$this->init();
// Check if we need to create a migration
if (isset($args[0]) && !empty($args[0])) {
$this->applyMigrations($args[0]);
} else {
$this->applyMigrations();
}
} catch (Exception $e) {
echo('ERROR: ' . $e->getMessage() . PHP_EOL);
}
}
/**
* Initialize the database migration engine. Several things happen during
* this initialization:
* - Constructs the full path to the migrations
* - The system checks if a database connection was configured.
* - The system checks if the database driver supports migrations.
* - If the schema_version table doesn't exist yet, it gets created.
*/
protected function init() {
// Construct the path to the migrations dir
$this->migrationsDir = Yii::app()->basePath;
if (!empty($module)) {
$this->migrationsDir .= '/modules/' . trim($module, '/');
}
$this->migrationsDir .= '/' . self::MIGRATIONS_DIR;
// Check if a database connection was configured
try {
Yii::app()->db;
} catch (Exception $e) {
throw new CDbMigrationEngineException(
'Database configuration is missing in your configuration file.'
);
}
// Load the migration adapter
switch (Yii::app()->db->driverName) {
case 'mysql':
$this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
break;
case 'sqlite':
$this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
break;
default:
throw new CDbMigrationEngineException(
'Database of type ' . Yii::app()->db->driverName
. ' does not support migrations (yet).'
);
}
// Check if the schema version table exists
if (Yii::app()->db->schema->getTable('schema_version') == null) {
// Create the table
echo('Creating initial schema_version table' . PHP_EOL);
// Use the adapter to create the table
$this->adapter->createTable(
self::SCHEMA_TABLE,
array(
array(self::SCHEMA_FIELD, 'string'),
)
);
// Create an index on the column
$this->adapter->addIndex(
self::SCHEMA_TABLE,
'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
array(self::SCHEMA_FIELD),
true
);
}
}
/**
* Get the list of migrations that are applied to the database. This
* basically reads out the schema_version table from the database.
*
* @returns An array with the IDs of the already applied database
* migrations as found in the database.
*/
protected function getAppliedMigrations() {
// Get the field and table name
$field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
$table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
// Construct the SQL statement
$sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
// Get the list
return Yii::app()->db->createCommand($sql)->queryColumn(
self::SCHEMA_FIELD
);
}
/**
* Get the list of possible migrations from the file system. This will read
* the contents of the migrations directory and the migrations directory
* inside each installed and enabled module.
*
* @returns An array with the IDs of the possible database migrations as
* found in the database.
*/
protected function getPossibleMigrations() {
// Get the migrations for the default application
$migrations = $this->getPossibleMigrationsForModule();
/*
// Get the migrations for each installed and enabled module
foreach (Yii::app()->modules as $module => $moduleData) {
$migrations = array_merge(
$migrations, $this->getPossibleMigrationsForModule($module)
);
}
*/
// Sort them based on the file path (which is the key in the array)
ksort($migrations);
// Returh the list of migrations
return $migrations;
}
/**
* A helper function to get the list of migrations for a specific module.
* If no module is specified, it will return the list of modules from the
* "protected/migrations" directory.
*
* @param $module The name of the module to get the migrations for.
*/
protected function getPossibleMigrationsForModule($module=null) {
// Start with an empty list
$migrations = array();
// Check if the migrations directory actually exists
if (is_dir($this->migrationsDir)) {
// Construct the list of migrations
$migrationFiles = CFileHelper::findFiles(
$this->migrationsDir,
array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
);
foreach ($migrationFiles as $migration) {
// Check if it's valid
if (substr(basename($migration), 0, 1) != 'm') {
continue;
}
// Include the file
- include($migration);
+ include_once($migration);
// Get the class name
$className = basename($migration, '.' . self::SCHEMA_EXT);
// Check if the class exists
if (!class_exists($className) || strlen($className) < 16) {
continue;
}
// Check if the class is a valid migration
$migrationReflection = new ReflectionClass($className);
$baseReflection = new ReflectionClass('CDbMigration');
if (!$migrationReflection->isSubclassOf($baseReflection)) {
continue;
}
// Add them to the list
$id = substr($className, 1, 14);
$migrations[$id] = array(
'file' => $migration,
'class' => $className,
);
}
}
// Return the list
return $migrations;
}
/**
* Apply the migrations to the database. This will apply any migration that
* has not been applied to the database yet. It does this in a
* chronological order based on the IDs of the migrations.
*
* @param $version The version to migrate to. If you specify the special
* cases "up" or "down", it will go one migration "up" or
* "down". If it's a number, if will migrate "up" or "down"
* to that specific version.
*/
protected function applyMigrations($version='') {
// Get the list of applied and possible migrations
$applied = $this->getAppliedMigrations();
$possible = $this->getPossibleMigrations();
// Check what which action need to happen
if ($version == 'list') {
// List the status of all migrations
foreach ($possible as $id => $specs) {
$status = in_array($id, $applied) ? 'Applied: ' : 'Not Applied: ';
$name = substr(basename($specs['file'], '.php'), 1);
$name = str_replace('_', ' ', $name);
echo("${status} ${name}" . PHP_EOL);
}
} elseif ($version == 'create') {
// Get the name from the migration
$name = 'UntitledMigration';
if (isset($this->args[1]) && !empty($this->args[1])) {
$name = trim($this->args[1]);
}
$name = strftime('m%Y%m%d%H%M%S_' . $name);
// Read the template file
$data = file_get_contents(
dirname(__FILE__) . '/templates/migration.php'
);
$data = str_replace('${name}', $name, $data);
// Save the file
if (!is_dir($this->migrationsDir)) {
mkdir($this->migrationsDir);
}
file_put_contents(
$this->migrationsDir . '/' . $name . '.php', $data
);
echo('Created migration: ' . $name . '.php' . PHP_EOL);
} elseif ($version == 'down') {
// Get the last migration
$migration = array_pop($applied);
// Apply the migration
if ($migration) {
$this->applyMigration(
$possible[$migration]['class'],
$possible[$migration]['file'],
'down'
);
}
+
+ } elseif ($version == 'redo') {
+
+ // Redo the last migration
+ $this->applyMigrations('down');
+ $this->applyMigrations('up');
} elseif ($version == 'up') {
// Check if there are still versions to apply
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
// Exit the loop
break;
}
}
} elseif (!empty($version)) {
// Check if it's a valid version number
if (!isset($possible[$version])) {
throw new CDbMigrationEngineException(
'Invalid migration: ' . $version
);
}
// Check if we need to go up or down
if (in_array($version, $applied)) {
// Reverse loop over the possible migrations
foreach (array_reverse($possible, true) as $id => $specs) {
// If we reached the correct version, exit the loop
if ($id == $version) {
break;
}
// Check if it's applied or not
if (in_array($id, $applied)) {
// Remove the migration
$this->applyMigration(
$specs['class'], $specs['file'], 'down'
);
}
}
} else {
// Loop over all possible migrations
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
// If we applied the requested migration, exit the loop
if ($id == $version) {
break;
}
}
}
}
} else {
// Loop over all possible migrations
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
}
}
}
}
/**
* Apply a specific migration based on the migration name.
*
* @param $class The class name of the migration to apply.
* @param $file The file in which you can find the migration.
* @param $direction The direction in which the migration needs to be
* applied. Needs to be "up" or "down".
*/
protected function applyMigration($class, $file, $direction='up') {
// Include the migration file
require_once($file);
// Create the migration
$migration = new $class($this->adapter);
// Apply the migration
if ($direction == 'up') {
echo('=== Applying migration: ' . $class . ' =========' . PHP_EOL);
} else {
echo('=== Removing migration: ' . $class . ' =========' . PHP_EOL);
}
echo(PHP_EOL);
// Perform the migration function transactional
$migration->performTransactional($direction);
// Commit the migration
echo(PHP_EOL);
if ($direction == 'up') {
echo(
' Marking migration as applied: ' . $class . PHP_EOL . PHP_EOL
);
$cmd = Yii::app()->db->commandBuilder->createInsertCommand(
self::SCHEMA_TABLE,
array(self::SCHEMA_FIELD => $migration->getId())
)->execute();
} else {
echo(
' Marking migration as removed: ' . $class . PHP_EOL . PHP_EOL
);
$sql = 'DELETE FROM '
. $this->adapter->db->quoteTableName(self::SCHEMA_TABLE)
. ' WHERE '
. $this->adapter->db->quoteColumnName(self::SCHEMA_FIELD)
. ' = '
. $this->adapter->db->quoteValue($migration->getId());
$this->adapter->execute($sql);
}
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | 540bb1bd969a63bb18e3735dc1bc2a73e9348e43 | Removed the code that closes and re-opens the database connection as this doesn't refresh the database metadata anyway. | diff --git a/CDbMigrationEngine.php b/CDbMigrationEngine.php
index 58beab3..4c04d1a 100644
--- a/CDbMigrationEngine.php
+++ b/CDbMigrationEngine.php
@@ -1,496 +1,492 @@
<?php
/**
* CDbMigrationEngine class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the adapters we are going to use for the migrations.
*/
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* A database migration engine exception
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngineException extends Exception {}
/**
* The CDbMigrationEngine class is the actual engine that can do all the
* migrations related functionality.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngine {
/**
* The migration adapter to use
*/
private $adapter;
/**
* The name of the table that contains the schema information.
*/
const SCHEMA_TABLE = 'schema_version';
/**
* The field in the schema_version table that contains the id of the
* installed migrations.
*/
const SCHEMA_FIELD = 'id';
/**
* The extension used for the migration files.
*/
const SCHEMA_EXT = 'php';
/**
* The directory in which the migrations can be found.
*/
const MIGRATIONS_DIR = 'migrations';
/**
* The command line arguments passed to the system.
*/
private $args;
/**
* The full path to the migrations
*/
private $migrationsDir;
/**
* Run the database migration engine, passing on the command-line
* arguments.
*
* @param $args The command line parameters.
*/
public function run($args) {
// Catch errors
try {
// Remember the arguments
$this->args = $args;
// Initialize the engine
$this->init();
// Check if we need to create a migration
if (isset($args[0]) && !empty($args[0])) {
$this->applyMigrations($args[0]);
} else {
$this->applyMigrations();
}
} catch (Exception $e) {
echo('ERROR: ' . $e->getMessage() . PHP_EOL);
}
}
/**
* Initialize the database migration engine. Several things happen during
* this initialization:
* - Constructs the full path to the migrations
* - The system checks if a database connection was configured.
* - The system checks if the database driver supports migrations.
* - If the schema_version table doesn't exist yet, it gets created.
*/
protected function init() {
// Construct the path to the migrations dir
$this->migrationsDir = Yii::app()->basePath;
if (!empty($module)) {
$this->migrationsDir .= '/modules/' . trim($module, '/');
}
$this->migrationsDir .= '/' . self::MIGRATIONS_DIR;
// Check if a database connection was configured
try {
Yii::app()->db;
} catch (Exception $e) {
throw new CDbMigrationEngineException(
'Database configuration is missing in your configuration file.'
);
}
// Load the migration adapter
switch (Yii::app()->db->driverName) {
case 'mysql':
$this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
break;
case 'sqlite':
$this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
break;
default:
throw new CDbMigrationEngineException(
'Database of type ' . Yii::app()->db->driverName
. ' does not support migrations (yet).'
);
}
// Check if the schema version table exists
if (Yii::app()->db->schema->getTable('schema_version') == null) {
// Create the table
echo('Creating initial schema_version table' . PHP_EOL);
// Use the adapter to create the table
$this->adapter->createTable(
self::SCHEMA_TABLE,
array(
array(self::SCHEMA_FIELD, 'string'),
)
);
// Create an index on the column
$this->adapter->addIndex(
self::SCHEMA_TABLE,
'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
array(self::SCHEMA_FIELD),
true
);
}
}
/**
* Get the list of migrations that are applied to the database. This
* basically reads out the schema_version table from the database.
*
* @returns An array with the IDs of the already applied database
* migrations as found in the database.
*/
protected function getAppliedMigrations() {
// Get the field and table name
$field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
$table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
// Construct the SQL statement
$sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
// Get the list
return Yii::app()->db->createCommand($sql)->queryColumn(
self::SCHEMA_FIELD
);
}
/**
* Get the list of possible migrations from the file system. This will read
* the contents of the migrations directory and the migrations directory
* inside each installed and enabled module.
*
* @returns An array with the IDs of the possible database migrations as
* found in the database.
*/
protected function getPossibleMigrations() {
// Get the migrations for the default application
$migrations = $this->getPossibleMigrationsForModule();
/*
// Get the migrations for each installed and enabled module
foreach (Yii::app()->modules as $module => $moduleData) {
$migrations = array_merge(
$migrations, $this->getPossibleMigrationsForModule($module)
);
}
*/
// Sort them based on the file path (which is the key in the array)
ksort($migrations);
// Returh the list of migrations
return $migrations;
}
/**
* A helper function to get the list of migrations for a specific module.
* If no module is specified, it will return the list of modules from the
* "protected/migrations" directory.
*
* @param $module The name of the module to get the migrations for.
*/
protected function getPossibleMigrationsForModule($module=null) {
// Start with an empty list
$migrations = array();
// Check if the migrations directory actually exists
if (is_dir($this->migrationsDir)) {
// Construct the list of migrations
$migrationFiles = CFileHelper::findFiles(
$this->migrationsDir,
array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
);
foreach ($migrationFiles as $migration) {
// Check if it's valid
if (substr(basename($migration), 0, 1) != 'm') {
continue;
}
// Include the file
include($migration);
// Get the class name
$className = basename($migration, '.' . self::SCHEMA_EXT);
// Check if the class exists
if (!class_exists($className) || strlen($className) < 16) {
continue;
}
// Check if the class is a valid migration
$migrationReflection = new ReflectionClass($className);
$baseReflection = new ReflectionClass('CDbMigration');
if (!$migrationReflection->isSubclassOf($baseReflection)) {
continue;
}
// Add them to the list
$id = substr($className, 1, 14);
$migrations[$id] = array(
'file' => $migration,
'class' => $className,
);
}
}
// Return the list
return $migrations;
}
/**
* Apply the migrations to the database. This will apply any migration that
* has not been applied to the database yet. It does this in a
* chronological order based on the IDs of the migrations.
*
* @param $version The version to migrate to. If you specify the special
* cases "up" or "down", it will go one migration "up" or
* "down". If it's a number, if will migrate "up" or "down"
* to that specific version.
*/
protected function applyMigrations($version='') {
// Get the list of applied and possible migrations
$applied = $this->getAppliedMigrations();
$possible = $this->getPossibleMigrations();
// Check what which action need to happen
if ($version == 'list') {
// List the status of all migrations
foreach ($possible as $id => $specs) {
$status = in_array($id, $applied) ? 'Applied: ' : 'Not Applied: ';
$name = substr(basename($specs['file'], '.php'), 1);
$name = str_replace('_', ' ', $name);
echo("${status} ${name}" . PHP_EOL);
}
} elseif ($version == 'create') {
// Get the name from the migration
$name = 'UntitledMigration';
if (isset($this->args[1]) && !empty($this->args[1])) {
$name = trim($this->args[1]);
}
$name = strftime('m%Y%m%d%H%M%S_' . $name);
// Read the template file
$data = file_get_contents(
dirname(__FILE__) . '/templates/migration.php'
);
$data = str_replace('${name}', $name, $data);
// Save the file
if (!is_dir($this->migrationsDir)) {
mkdir($this->migrationsDir);
}
file_put_contents(
$this->migrationsDir . '/' . $name . '.php', $data
);
echo('Created migration: ' . $name . '.php' . PHP_EOL);
} elseif ($version == 'down') {
// Get the last migration
$migration = array_pop($applied);
// Apply the migration
if ($migration) {
$this->applyMigration(
$possible[$migration]['class'],
$possible[$migration]['file'],
'down'
);
}
} elseif ($version == 'up') {
// Check if there are still versions to apply
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
// Exit the loop
break;
}
}
} elseif (!empty($version)) {
// Check if it's a valid version number
if (!isset($possible[$version])) {
throw new CDbMigrationEngineException(
'Invalid migration: ' . $version
);
}
// Check if we need to go up or down
if (in_array($version, $applied)) {
// Reverse loop over the possible migrations
foreach (array_reverse($possible, true) as $id => $specs) {
// If we reached the correct version, exit the loop
if ($id == $version) {
break;
}
// Check if it's applied or not
if (in_array($id, $applied)) {
// Remove the migration
$this->applyMigration(
$specs['class'], $specs['file'], 'down'
);
}
}
} else {
// Loop over all possible migrations
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
// If we applied the requested migration, exit the loop
if ($id == $version) {
break;
}
}
}
}
} else {
// Loop over all possible migrations
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
}
}
}
}
/**
* Apply a specific migration based on the migration name.
*
* @param $class The class name of the migration to apply.
* @param $file The file in which you can find the migration.
* @param $direction The direction in which the migration needs to be
* applied. Needs to be "up" or "down".
*/
protected function applyMigration($class, $file, $direction='up') {
- // Close and open the database connection
- Yii::app()->db->active = false;
- Yii::app()->db->active = true;
-
// Include the migration file
require_once($file);
// Create the migration
$migration = new $class($this->adapter);
// Apply the migration
if ($direction == 'up') {
echo('=== Applying migration: ' . $class . ' =========' . PHP_EOL);
} else {
echo('=== Removing migration: ' . $class . ' =========' . PHP_EOL);
}
echo(PHP_EOL);
// Perform the migration function transactional
$migration->performTransactional($direction);
// Commit the migration
echo(PHP_EOL);
if ($direction == 'up') {
echo(
' Marking migration as applied: ' . $class . PHP_EOL . PHP_EOL
);
$cmd = Yii::app()->db->commandBuilder->createInsertCommand(
self::SCHEMA_TABLE,
array(self::SCHEMA_FIELD => $migration->getId())
)->execute();
} else {
echo(
' Marking migration as removed: ' . $class . PHP_EOL . PHP_EOL
);
$sql = 'DELETE FROM '
. $this->adapter->db->quoteTableName(self::SCHEMA_TABLE)
. ' WHERE '
. $this->adapter->db->quoteColumnName(self::SCHEMA_FIELD)
. ' = '
. $this->adapter->db->quoteValue($migration->getId());
$this->adapter->execute($sql);
}
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | c4d3cad39fac2b220b7b79f6b4b7a62c5ed13c95 | Added support for passing on parameters in the execute method of a migration. | diff --git a/CDbMigrationAdapter.php b/CDbMigrationAdapter.php
index caf076e..da22130 100644
--- a/CDbMigrationAdapter.php
+++ b/CDbMigrationAdapter.php
@@ -1,221 +1,229 @@
<?php
/**
* CDbMigrationAdapter class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* @package extensions.yii-dbmigrations
*/
abstract class CDbMigrationAdapter {
/**
* The database connection
*/
public $db;
/**
* Class Constructor
*/
public function __construct(CDbConnection $db) {
$this->db = $db;
}
/**
* Convert a type to a native database type
*/
protected function convertToNativeType($theType) {
if (isset($this->nativeDatabaseTypes[$theType])) {
return $this->nativeDatabaseTypes[$theType];
} else {
return $theType;
}
}
/**
* Convert the field information to native types
*/
protected function convertFields($fields) {
$result = array();
foreach ($fields as $field) {
if (is_array($field)) {
if (isset($field[0])) {
$field[0] = $this->db->quoteColumnName($field[0]);
}
if (isset($field[1])) {
$field[1] = $this->convertToNativeType($field[1]);
}
$result[] = join(' ', $field);
} else {
$result[] = $this->db->quoteColumnName($field);
}
}
return join(', ', $result);
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that doesn't return any data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The number of affected rows.
*/
public function execute($query, $params=array()) {
- return $this->db->createCommand($query)->execute();
+ $cmd = $this->db->createCommand($query);
+ foreach ($params as $key => $param) {
+ $cmd->bindValue($key, $param);
+ }
+ return $cmd->execute();
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that returns data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The rows returned from the database.
*/
public function query($query, $params=array()) {
- return $this->db->createCommand($query)->queryAll();
+ $cmd = $this->db->createCommand($query);
+ foreach ($params as $key => $param) {
+ $cmd->bindParam($key, $param);
+ }
+ return $cmd->queryAll();
}
/**
* Retrieve the type information from a database column.
*
* @returns The current data type of the column.
*/
public function columnInfo($table, $name) {
}
/**
* The createTable function allows you to create a new table in the
* database.
*
* @param $name The name of the table to create.
* @param $column The column definition for the database table
* @param $options The extra options to pass to the database creation.
*/
public function createTable($name, $columns=array(), $options=null) {
$sql = 'CREATE TABLE ' . $this->db->quoteTableName($name) . ' ('
. $this->convertFields($columns)
. ') ' . $options;
return $this->execute($sql);
}
/**
* Rename a table.
*
* @param $name The name of the table to rename.
* @param $new_name The new name for the table.
*/
public function renameTable($name, $new_name) {
$sql = 'RENAME TABLE ' . $this->db->quoteTableName($name) . ' TO '
. $this->db->quoteTableName($new_name);
return $this->execute($sql);
}
/**
* Remove a table from the database.
*
* @param $name The name of the table to remove.
*/
public function removeTable($name) {
$sql = 'DROP TABLE ' . $this->db->quoteTableName($name);
return $this->execute($sql);
}
/**
* Add a database column to an existing table.
*
* @param $table The table to add the column in.
* @param $column The name of the column to add.
* @param $type The data type for the new column.
* @param $options The extra options to pass to the column.
*/
public function addColumn($table, $column, $type, $options=null) {
$type = $this->convertToNativeType($type);
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD '
. $this->db->quoteColumnName($column) . ' ' . $type . ' '
. $options;
return $this->execute($sql);
}
/**
* Rename a database column in an existing table.
*
* @param $table The table to rename the column from.
* @param $name The current name of the column.
* @param $new_name The new name of the column.
*/
public function renameColumn($table, $name, $new_name) {
$type = $this->columnInfo($table, $name);
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
. $this->db->quoteColumnName($name) . ' '
. $this->db->quoteColumnName($new_name) . ' ' . $type;
return $this->execute($sql);
}
/**
* Change a database column in an existing table.
*
* @param $table The name of the table to change the column from.
* @param $column The name of the column to change.
* @param $type The new data type for the column.
* @param $options The extra options to pass to the column.
*/
public function changeColumn($table, $column, $type, $options=null) {
$type = $this->convertToNativeType($type);
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
. $this->db->quoteColumnName($column) . ' '
. $this->db->quoteColumnName($column) . ' ' . $type . ' '
. $options;
return $this->execute($sql);
}
/**
* Remove a table column from the database.
*
* @param $table The name of the table to remove the column from.
* @param $column The name of the table column to remove.
*/
public function removeColumn($table, $column) {
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' DROP '
. $this->db->quoteColumnName($column);
return $this->execute($sql);
}
/**
* Add an index to the database or a specific table.
*
* @param $table The name of the table to add the index to.
* @param $name The name of the index to create.
* @param $columns The name of the fields to include in the index.
* @param $unique If set to true, a unique index will be created.
*/
public function addIndex($table, $name, $columns, $unique=false) {
$sql = 'CREATE ';
$sql .= ($unique) ? 'UNIQUE ' : '';
$sql .= 'INDEX ' . $this->db->quoteColumnName($name) . ' ON '
. $this->db->quoteTableName($table) . ' ('
. $this->convertFields($columns)
. ')';
return $this->execute($sql);
}
/**
* Remove a table index from the database.
*
* @param $table The name of the table to remove the index from.
* @param $column The name of the table index to remove.
*/
public function removeIndex($table, $name) {
$sql = 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON '
. $this->db->quoteTableName($table);
return $this->execute($sql);
}
}
|
elchingon/yii-dbmigrations | 6a282d52a60131001f3005d76e520c130daefddf | Cleaned out the output of the list command. | diff --git a/CDbMigrationEngine.php b/CDbMigrationEngine.php
index 7ad42cd..58beab3 100644
--- a/CDbMigrationEngine.php
+++ b/CDbMigrationEngine.php
@@ -1,493 +1,496 @@
<?php
/**
* CDbMigrationEngine class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the adapters we are going to use for the migrations.
*/
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* A database migration engine exception
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngineException extends Exception {}
/**
* The CDbMigrationEngine class is the actual engine that can do all the
* migrations related functionality.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngine {
/**
* The migration adapter to use
*/
private $adapter;
/**
* The name of the table that contains the schema information.
*/
const SCHEMA_TABLE = 'schema_version';
/**
* The field in the schema_version table that contains the id of the
* installed migrations.
*/
const SCHEMA_FIELD = 'id';
/**
* The extension used for the migration files.
*/
const SCHEMA_EXT = 'php';
/**
* The directory in which the migrations can be found.
*/
const MIGRATIONS_DIR = 'migrations';
/**
* The command line arguments passed to the system.
*/
private $args;
/**
* The full path to the migrations
*/
private $migrationsDir;
/**
* Run the database migration engine, passing on the command-line
* arguments.
*
* @param $args The command line parameters.
*/
public function run($args) {
// Catch errors
try {
// Remember the arguments
$this->args = $args;
// Initialize the engine
$this->init();
// Check if we need to create a migration
if (isset($args[0]) && !empty($args[0])) {
$this->applyMigrations($args[0]);
} else {
$this->applyMigrations();
}
} catch (Exception $e) {
echo('ERROR: ' . $e->getMessage() . PHP_EOL);
}
}
/**
* Initialize the database migration engine. Several things happen during
* this initialization:
* - Constructs the full path to the migrations
* - The system checks if a database connection was configured.
* - The system checks if the database driver supports migrations.
* - If the schema_version table doesn't exist yet, it gets created.
*/
protected function init() {
// Construct the path to the migrations dir
$this->migrationsDir = Yii::app()->basePath;
if (!empty($module)) {
$this->migrationsDir .= '/modules/' . trim($module, '/');
}
$this->migrationsDir .= '/' . self::MIGRATIONS_DIR;
// Check if a database connection was configured
try {
Yii::app()->db;
} catch (Exception $e) {
throw new CDbMigrationEngineException(
'Database configuration is missing in your configuration file.'
);
}
// Load the migration adapter
switch (Yii::app()->db->driverName) {
case 'mysql':
$this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
break;
case 'sqlite':
$this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
break;
default:
throw new CDbMigrationEngineException(
'Database of type ' . Yii::app()->db->driverName
. ' does not support migrations (yet).'
);
}
// Check if the schema version table exists
if (Yii::app()->db->schema->getTable('schema_version') == null) {
// Create the table
echo('Creating initial schema_version table' . PHP_EOL);
// Use the adapter to create the table
$this->adapter->createTable(
self::SCHEMA_TABLE,
array(
array(self::SCHEMA_FIELD, 'string'),
)
);
// Create an index on the column
$this->adapter->addIndex(
self::SCHEMA_TABLE,
'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
array(self::SCHEMA_FIELD),
true
);
}
}
/**
* Get the list of migrations that are applied to the database. This
* basically reads out the schema_version table from the database.
*
* @returns An array with the IDs of the already applied database
* migrations as found in the database.
*/
protected function getAppliedMigrations() {
// Get the field and table name
$field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
$table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
// Construct the SQL statement
$sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
// Get the list
return Yii::app()->db->createCommand($sql)->queryColumn(
self::SCHEMA_FIELD
);
}
/**
* Get the list of possible migrations from the file system. This will read
* the contents of the migrations directory and the migrations directory
* inside each installed and enabled module.
*
* @returns An array with the IDs of the possible database migrations as
* found in the database.
*/
protected function getPossibleMigrations() {
// Get the migrations for the default application
$migrations = $this->getPossibleMigrationsForModule();
/*
// Get the migrations for each installed and enabled module
foreach (Yii::app()->modules as $module => $moduleData) {
$migrations = array_merge(
$migrations, $this->getPossibleMigrationsForModule($module)
);
}
*/
// Sort them based on the file path (which is the key in the array)
ksort($migrations);
// Returh the list of migrations
return $migrations;
}
/**
* A helper function to get the list of migrations for a specific module.
* If no module is specified, it will return the list of modules from the
* "protected/migrations" directory.
*
* @param $module The name of the module to get the migrations for.
*/
protected function getPossibleMigrationsForModule($module=null) {
// Start with an empty list
$migrations = array();
// Check if the migrations directory actually exists
if (is_dir($this->migrationsDir)) {
// Construct the list of migrations
$migrationFiles = CFileHelper::findFiles(
$this->migrationsDir,
array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
);
foreach ($migrationFiles as $migration) {
// Check if it's valid
if (substr(basename($migration), 0, 1) != 'm') {
continue;
}
// Include the file
include($migration);
// Get the class name
$className = basename($migration, '.' . self::SCHEMA_EXT);
// Check if the class exists
if (!class_exists($className) || strlen($className) < 16) {
continue;
}
// Check if the class is a valid migration
$migrationReflection = new ReflectionClass($className);
$baseReflection = new ReflectionClass('CDbMigration');
if (!$migrationReflection->isSubclassOf($baseReflection)) {
continue;
}
// Add them to the list
$id = substr($className, 1, 14);
$migrations[$id] = array(
'file' => $migration,
'class' => $className,
);
}
}
// Return the list
return $migrations;
}
/**
* Apply the migrations to the database. This will apply any migration that
* has not been applied to the database yet. It does this in a
* chronological order based on the IDs of the migrations.
*
* @param $version The version to migrate to. If you specify the special
* cases "up" or "down", it will go one migration "up" or
* "down". If it's a number, if will migrate "up" or "down"
* to that specific version.
*/
protected function applyMigrations($version='') {
// Get the list of applied and possible migrations
$applied = $this->getAppliedMigrations();
$possible = $this->getPossibleMigrations();
// Check what which action need to happen
if ($version == 'list') {
// List the status of all migrations
foreach ($possible as $id => $specs) {
- if (in_array($id, $applied)) {
- echo('Applied: ' . $specs['class'] . PHP_EOL);
- } else {
- echo('Not Applied: ' . $specs['class'] . PHP_EOL);
- }
+ $status = in_array($id, $applied) ? 'Applied: ' : 'Not Applied: ';
+ $name = substr(basename($specs['file'], '.php'), 1);
+ $name = str_replace('_', ' ', $name);
+ echo("${status} ${name}" . PHP_EOL);
}
} elseif ($version == 'create') {
// Get the name from the migration
$name = 'UntitledMigration';
if (isset($this->args[1]) && !empty($this->args[1])) {
$name = trim($this->args[1]);
}
$name = strftime('m%Y%m%d%H%M%S_' . $name);
// Read the template file
$data = file_get_contents(
dirname(__FILE__) . '/templates/migration.php'
);
$data = str_replace('${name}', $name, $data);
// Save the file
if (!is_dir($this->migrationsDir)) {
mkdir($this->migrationsDir);
}
file_put_contents(
$this->migrationsDir . '/' . $name . '.php', $data
);
echo('Created migration: ' . $name . '.php' . PHP_EOL);
} elseif ($version == 'down') {
// Get the last migration
$migration = array_pop($applied);
// Apply the migration
if ($migration) {
$this->applyMigration(
$possible[$migration]['class'],
$possible[$migration]['file'],
'down'
);
}
} elseif ($version == 'up') {
// Check if there are still versions to apply
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
// Exit the loop
break;
}
}
} elseif (!empty($version)) {
// Check if it's a valid version number
if (!isset($possible[$version])) {
throw new CDbMigrationEngineException(
'Invalid migration: ' . $version
);
}
// Check if we need to go up or down
if (in_array($version, $applied)) {
// Reverse loop over the possible migrations
foreach (array_reverse($possible, true) as $id => $specs) {
// If we reached the correct version, exit the loop
if ($id == $version) {
break;
}
// Check if it's applied or not
if (in_array($id, $applied)) {
// Remove the migration
$this->applyMigration(
$specs['class'], $specs['file'], 'down'
);
}
}
} else {
// Loop over all possible migrations
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
// If we applied the requested migration, exit the loop
if ($id == $version) {
break;
}
}
}
}
} else {
// Loop over all possible migrations
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
}
}
}
}
/**
* Apply a specific migration based on the migration name.
*
* @param $class The class name of the migration to apply.
* @param $file The file in which you can find the migration.
* @param $direction The direction in which the migration needs to be
* applied. Needs to be "up" or "down".
*/
protected function applyMigration($class, $file, $direction='up') {
+ // Close and open the database connection
+ Yii::app()->db->active = false;
+ Yii::app()->db->active = true;
+
// Include the migration file
require_once($file);
// Create the migration
$migration = new $class($this->adapter);
// Apply the migration
if ($direction == 'up') {
echo('=== Applying migration: ' . $class . ' =========' . PHP_EOL);
} else {
echo('=== Removing migration: ' . $class . ' =========' . PHP_EOL);
}
echo(PHP_EOL);
// Perform the migration function transactional
$migration->performTransactional($direction);
// Commit the migration
echo(PHP_EOL);
if ($direction == 'up') {
echo(
' Marking migration as applied: ' . $class . PHP_EOL . PHP_EOL
);
$cmd = Yii::app()->db->commandBuilder->createInsertCommand(
self::SCHEMA_TABLE,
array(self::SCHEMA_FIELD => $migration->getId())
)->execute();
} else {
echo(
' Marking migration as removed: ' . $class . PHP_EOL . PHP_EOL
);
$sql = 'DELETE FROM '
. $this->adapter->db->quoteTableName(self::SCHEMA_TABLE)
. ' WHERE '
. $this->adapter->db->quoteColumnName(self::SCHEMA_FIELD)
. ' = '
. $this->adapter->db->quoteValue($migration->getId());
$this->adapter->execute($sql);
}
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | 60d31574e5235046cfc56a3489f9fda9981450ea | Beautified the output from the migrate command. | diff --git a/CDbMigrationEngine.php b/CDbMigrationEngine.php
index f4e9f13..7ad42cd 100644
--- a/CDbMigrationEngine.php
+++ b/CDbMigrationEngine.php
@@ -1,491 +1,493 @@
<?php
/**
* CDbMigrationEngine class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the adapters we are going to use for the migrations.
*/
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* A database migration engine exception
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngineException extends Exception {}
/**
* The CDbMigrationEngine class is the actual engine that can do all the
* migrations related functionality.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngine {
/**
* The migration adapter to use
*/
private $adapter;
/**
* The name of the table that contains the schema information.
*/
const SCHEMA_TABLE = 'schema_version';
/**
* The field in the schema_version table that contains the id of the
* installed migrations.
*/
const SCHEMA_FIELD = 'id';
/**
* The extension used for the migration files.
*/
const SCHEMA_EXT = 'php';
/**
* The directory in which the migrations can be found.
*/
const MIGRATIONS_DIR = 'migrations';
/**
* The command line arguments passed to the system.
*/
private $args;
/**
* The full path to the migrations
*/
private $migrationsDir;
/**
* Run the database migration engine, passing on the command-line
* arguments.
*
* @param $args The command line parameters.
*/
public function run($args) {
// Catch errors
try {
// Remember the arguments
$this->args = $args;
// Initialize the engine
$this->init();
// Check if we need to create a migration
if (isset($args[0]) && !empty($args[0])) {
$this->applyMigrations($args[0]);
} else {
$this->applyMigrations();
}
} catch (Exception $e) {
echo('ERROR: ' . $e->getMessage() . PHP_EOL);
}
}
/**
* Initialize the database migration engine. Several things happen during
* this initialization:
* - Constructs the full path to the migrations
* - The system checks if a database connection was configured.
* - The system checks if the database driver supports migrations.
* - If the schema_version table doesn't exist yet, it gets created.
*/
protected function init() {
// Construct the path to the migrations dir
$this->migrationsDir = Yii::app()->basePath;
if (!empty($module)) {
$this->migrationsDir .= '/modules/' . trim($module, '/');
}
$this->migrationsDir .= '/' . self::MIGRATIONS_DIR;
// Check if a database connection was configured
try {
Yii::app()->db;
} catch (Exception $e) {
throw new CDbMigrationEngineException(
'Database configuration is missing in your configuration file.'
);
}
// Load the migration adapter
switch (Yii::app()->db->driverName) {
case 'mysql':
$this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
break;
case 'sqlite':
$this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
break;
default:
throw new CDbMigrationEngineException(
'Database of type ' . Yii::app()->db->driverName
. ' does not support migrations (yet).'
);
}
// Check if the schema version table exists
if (Yii::app()->db->schema->getTable('schema_version') == null) {
// Create the table
echo('Creating initial schema_version table' . PHP_EOL);
// Use the adapter to create the table
$this->adapter->createTable(
self::SCHEMA_TABLE,
array(
array(self::SCHEMA_FIELD, 'string'),
)
);
// Create an index on the column
$this->adapter->addIndex(
self::SCHEMA_TABLE,
'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
array(self::SCHEMA_FIELD),
true
);
}
}
/**
* Get the list of migrations that are applied to the database. This
* basically reads out the schema_version table from the database.
*
* @returns An array with the IDs of the already applied database
* migrations as found in the database.
*/
protected function getAppliedMigrations() {
// Get the field and table name
$field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
$table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
// Construct the SQL statement
$sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
// Get the list
return Yii::app()->db->createCommand($sql)->queryColumn(
self::SCHEMA_FIELD
);
}
/**
* Get the list of possible migrations from the file system. This will read
* the contents of the migrations directory and the migrations directory
* inside each installed and enabled module.
*
* @returns An array with the IDs of the possible database migrations as
* found in the database.
*/
protected function getPossibleMigrations() {
// Get the migrations for the default application
$migrations = $this->getPossibleMigrationsForModule();
/*
// Get the migrations for each installed and enabled module
foreach (Yii::app()->modules as $module => $moduleData) {
$migrations = array_merge(
$migrations, $this->getPossibleMigrationsForModule($module)
);
}
*/
// Sort them based on the file path (which is the key in the array)
ksort($migrations);
// Returh the list of migrations
return $migrations;
}
/**
* A helper function to get the list of migrations for a specific module.
* If no module is specified, it will return the list of modules from the
* "protected/migrations" directory.
*
* @param $module The name of the module to get the migrations for.
*/
protected function getPossibleMigrationsForModule($module=null) {
// Start with an empty list
$migrations = array();
// Check if the migrations directory actually exists
if (is_dir($this->migrationsDir)) {
// Construct the list of migrations
$migrationFiles = CFileHelper::findFiles(
$this->migrationsDir,
array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
);
foreach ($migrationFiles as $migration) {
// Check if it's valid
if (substr(basename($migration), 0, 1) != 'm') {
continue;
}
// Include the file
include($migration);
// Get the class name
$className = basename($migration, '.' . self::SCHEMA_EXT);
// Check if the class exists
if (!class_exists($className) || strlen($className) < 16) {
continue;
}
// Check if the class is a valid migration
$migrationReflection = new ReflectionClass($className);
$baseReflection = new ReflectionClass('CDbMigration');
if (!$migrationReflection->isSubclassOf($baseReflection)) {
continue;
}
// Add them to the list
$id = substr($className, 1, 14);
$migrations[$id] = array(
'file' => $migration,
'class' => $className,
);
}
}
// Return the list
return $migrations;
}
/**
* Apply the migrations to the database. This will apply any migration that
* has not been applied to the database yet. It does this in a
* chronological order based on the IDs of the migrations.
*
* @param $version The version to migrate to. If you specify the special
* cases "up" or "down", it will go one migration "up" or
* "down". If it's a number, if will migrate "up" or "down"
* to that specific version.
*/
protected function applyMigrations($version='') {
// Get the list of applied and possible migrations
$applied = $this->getAppliedMigrations();
$possible = $this->getPossibleMigrations();
// Check what which action need to happen
if ($version == 'list') {
// List the status of all migrations
foreach ($possible as $id => $specs) {
if (in_array($id, $applied)) {
echo('Applied: ' . $specs['class'] . PHP_EOL);
} else {
echo('Not Applied: ' . $specs['class'] . PHP_EOL);
}
}
} elseif ($version == 'create') {
// Get the name from the migration
$name = 'UntitledMigration';
if (isset($this->args[1]) && !empty($this->args[1])) {
$name = trim($this->args[1]);
}
$name = strftime('m%Y%m%d%H%M%S_' . $name);
// Read the template file
$data = file_get_contents(
dirname(__FILE__) . '/templates/migration.php'
);
$data = str_replace('${name}', $name, $data);
// Save the file
if (!is_dir($this->migrationsDir)) {
mkdir($this->migrationsDir);
}
file_put_contents(
$this->migrationsDir . '/' . $name . '.php', $data
);
echo('Created migration: ' . $name . '.php' . PHP_EOL);
} elseif ($version == 'down') {
// Get the last migration
$migration = array_pop($applied);
// Apply the migration
if ($migration) {
$this->applyMigration(
$possible[$migration]['class'],
$possible[$migration]['file'],
'down'
);
}
} elseif ($version == 'up') {
// Check if there are still versions to apply
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
// Exit the loop
break;
}
}
} elseif (!empty($version)) {
// Check if it's a valid version number
if (!isset($possible[$version])) {
throw new CDbMigrationEngineException(
'Invalid migration: ' . $version
);
}
// Check if we need to go up or down
if (in_array($version, $applied)) {
// Reverse loop over the possible migrations
foreach (array_reverse($possible, true) as $id => $specs) {
// If we reached the correct version, exit the loop
if ($id == $version) {
break;
}
// Check if it's applied or not
if (in_array($id, $applied)) {
// Remove the migration
$this->applyMigration(
$specs['class'], $specs['file'], 'down'
);
}
}
} else {
// Loop over all possible migrations
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
// If we applied the requested migration, exit the loop
if ($id == $version) {
break;
}
}
}
}
} else {
// Loop over all possible migrations
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
}
}
}
}
/**
* Apply a specific migration based on the migration name.
*
* @param $class The class name of the migration to apply.
* @param $file The file in which you can find the migration.
* @param $direction The direction in which the migration needs to be
* applied. Needs to be "up" or "down".
*/
protected function applyMigration($class, $file, $direction='up') {
// Include the migration file
require_once($file);
// Create the migration
$migration = new $class($this->adapter);
// Apply the migration
if ($direction == 'up') {
- echo('Applying migration: ' . $class . PHP_EOL);
+ echo('=== Applying migration: ' . $class . ' =========' . PHP_EOL);
} else {
- echo('Removing migration: ' . $class . PHP_EOL);
+ echo('=== Removing migration: ' . $class . ' =========' . PHP_EOL);
}
+ echo(PHP_EOL);
// Perform the migration function transactional
$migration->performTransactional($direction);
// Commit the migration
+ echo(PHP_EOL);
if ($direction == 'up') {
echo(
- 'Marking migration as applied: ' . $class . PHP_EOL
+ ' Marking migration as applied: ' . $class . PHP_EOL . PHP_EOL
);
$cmd = Yii::app()->db->commandBuilder->createInsertCommand(
self::SCHEMA_TABLE,
array(self::SCHEMA_FIELD => $migration->getId())
)->execute();
} else {
echo(
- 'Marking migration as removed: ' . $class . PHP_EOL
+ ' Marking migration as removed: ' . $class . PHP_EOL . PHP_EOL
);
$sql = 'DELETE FROM '
. $this->adapter->db->quoteTableName(self::SCHEMA_TABLE)
. ' WHERE '
. $this->adapter->db->quoteColumnName(self::SCHEMA_FIELD)
. ' = '
. $this->adapter->db->quoteValue($migration->getId());
$this->adapter->execute($sql);
}
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | 50e5b540ac1639666c38eeadbb305099120ece2b | Added the migrate create command. | diff --git a/CDbMigrationCommand.php b/CDbMigrationCommand.php
index 75b6696..9d9d965 100644
--- a/CDbMigrationCommand.php
+++ b/CDbMigrationCommand.php
@@ -1,85 +1,93 @@
<?php
/**
* CDbMigrationCommand class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the different extension components.
*/
Yii::import('application.extensions.yii-dbmigrations.*');
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* This class creates the migrate console command so that you can use it with
* the yiic tool inside your project.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationCommand extends CConsoleCommand {
/**
* Return the help for the migrate command.
*/
public function getHelp() {
return <<<EOD
USAGE
- migrate [version|up|down|list]
+ migrate [create|version|up|down|list]
DESCRIPTION
This command applies the database migrations which can be found in the
migrations directory in your project folder.
PARAMETERS
+ * create: creates a new migration in the migrations directory.
+
* version: options, the ID of the migration to migrate the database to.
* up: optional, apply the first migration that is not applied to the database
yet.
* down: remove the last applied migration from the database.
* list: list all the migrations available in the application and show if they
are applied or not.
EXAMPLES
* Apply all migrations that are not applied yet:
migrate
* Migrate up to version 20090612163144 if it's not applied yet:
migrate 20090612163144
* Migrate down to version 20090612163144 if it's applied already:
migrate 20090612163144
* Apply the first migration that is not applied to the database yet:
migrate up
* Remove the last applied migration:
migrate down
* List all the migrations found in the application and their status:
migrate list
+
+ * Create a new migration
+ migrate create
+
+ * Create a new name migration
+ migrate create MyMigrationName
EOD;
}
/**
* Runs the actual command passing along the command line parameters.
*
* @param $args The command line parameters
*/
public function run($args) {
try {
$engine = new CDbMigrationEngine();
$engine->run($args);
} catch (Exception $e) {
echo('FATAL ERROR: ' . $e->getMessage());
}
}
}
\ No newline at end of file
diff --git a/CDbMigrationEngine.php b/CDbMigrationEngine.php
index c21df82..f4e9f13 100644
--- a/CDbMigrationEngine.php
+++ b/CDbMigrationEngine.php
@@ -1,453 +1,491 @@
<?php
/**
* CDbMigrationEngine class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the adapters we are going to use for the migrations.
*/
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* A database migration engine exception
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngineException extends Exception {}
/**
* The CDbMigrationEngine class is the actual engine that can do all the
* migrations related functionality.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngine {
/**
* The migration adapter to use
*/
private $adapter;
/**
* The name of the table that contains the schema information.
*/
const SCHEMA_TABLE = 'schema_version';
/**
* The field in the schema_version table that contains the id of the
* installed migrations.
*/
const SCHEMA_FIELD = 'id';
/**
* The extension used for the migration files.
*/
const SCHEMA_EXT = 'php';
/**
* The directory in which the migrations can be found.
*/
const MIGRATIONS_DIR = 'migrations';
+ /**
+ * The command line arguments passed to the system.
+ */
+ private $args;
+
+ /**
+ * The full path to the migrations
+ */
+ private $migrationsDir;
+
/**
* Run the database migration engine, passing on the command-line
* arguments.
*
* @param $args The command line parameters.
*/
public function run($args) {
// Catch errors
try {
+
+ // Remember the arguments
+ $this->args = $args;
// Initialize the engine
$this->init();
// Check if we need to create a migration
if (isset($args[0]) && !empty($args[0])) {
$this->applyMigrations($args[0]);
} else {
$this->applyMigrations();
}
} catch (Exception $e) {
echo('ERROR: ' . $e->getMessage() . PHP_EOL);
}
}
/**
* Initialize the database migration engine. Several things happen during
* this initialization:
+ * - Constructs the full path to the migrations
* - The system checks if a database connection was configured.
* - The system checks if the database driver supports migrations.
* - If the schema_version table doesn't exist yet, it gets created.
*/
protected function init() {
+ // Construct the path to the migrations dir
+ $this->migrationsDir = Yii::app()->basePath;
+ if (!empty($module)) {
+ $this->migrationsDir .= '/modules/' . trim($module, '/');
+ }
+ $this->migrationsDir .= '/' . self::MIGRATIONS_DIR;
+
// Check if a database connection was configured
try {
Yii::app()->db;
} catch (Exception $e) {
throw new CDbMigrationEngineException(
'Database configuration is missing in your configuration file.'
);
}
// Load the migration adapter
switch (Yii::app()->db->driverName) {
case 'mysql':
$this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
break;
case 'sqlite':
$this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
break;
default:
throw new CDbMigrationEngineException(
'Database of type ' . Yii::app()->db->driverName
. ' does not support migrations (yet).'
);
}
// Check if the schema version table exists
if (Yii::app()->db->schema->getTable('schema_version') == null) {
// Create the table
echo('Creating initial schema_version table' . PHP_EOL);
// Use the adapter to create the table
$this->adapter->createTable(
self::SCHEMA_TABLE,
array(
array(self::SCHEMA_FIELD, 'string'),
)
);
// Create an index on the column
$this->adapter->addIndex(
self::SCHEMA_TABLE,
'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
array(self::SCHEMA_FIELD),
true
);
}
}
/**
* Get the list of migrations that are applied to the database. This
* basically reads out the schema_version table from the database.
*
* @returns An array with the IDs of the already applied database
* migrations as found in the database.
*/
protected function getAppliedMigrations() {
// Get the field and table name
$field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
$table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
// Construct the SQL statement
$sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
// Get the list
return Yii::app()->db->createCommand($sql)->queryColumn(
self::SCHEMA_FIELD
);
}
/**
* Get the list of possible migrations from the file system. This will read
* the contents of the migrations directory and the migrations directory
* inside each installed and enabled module.
*
* @returns An array with the IDs of the possible database migrations as
* found in the database.
*/
protected function getPossibleMigrations() {
// Get the migrations for the default application
$migrations = $this->getPossibleMigrationsForModule();
/*
// Get the migrations for each installed and enabled module
foreach (Yii::app()->modules as $module => $moduleData) {
$migrations = array_merge(
$migrations, $this->getPossibleMigrationsForModule($module)
);
}
*/
// Sort them based on the file path (which is the key in the array)
ksort($migrations);
// Returh the list of migrations
return $migrations;
}
/**
* A helper function to get the list of migrations for a specific module.
* If no module is specified, it will return the list of modules from the
* "protected/migrations" directory.
*
* @param $module The name of the module to get the migrations for.
*/
protected function getPossibleMigrationsForModule($module=null) {
- // Get the path to the migrations dir
- $path = Yii::app()->basePath;
- if (!empty($module)) {
- $path .= '/modules/' . trim($module, '/');
- }
- $path .= '/' . self::MIGRATIONS_DIR;
-
// Start with an empty list
$migrations = array();
// Check if the migrations directory actually exists
- if (is_dir($path)) {
+ if (is_dir($this->migrationsDir)) {
// Construct the list of migrations
$migrationFiles = CFileHelper::findFiles(
- $path,
+ $this->migrationsDir,
array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
);
foreach ($migrationFiles as $migration) {
// Check if it's valid
if (substr(basename($migration), 0, 1) != 'm') {
continue;
}
// Include the file
include($migration);
// Get the class name
$className = basename($migration, '.' . self::SCHEMA_EXT);
// Check if the class exists
if (!class_exists($className) || strlen($className) < 16) {
continue;
}
// Check if the class is a valid migration
$migrationReflection = new ReflectionClass($className);
$baseReflection = new ReflectionClass('CDbMigration');
if (!$migrationReflection->isSubclassOf($baseReflection)) {
continue;
}
// Add them to the list
$id = substr($className, 1, 14);
$migrations[$id] = array(
'file' => $migration,
'class' => $className,
);
}
}
// Return the list
return $migrations;
}
/**
* Apply the migrations to the database. This will apply any migration that
* has not been applied to the database yet. It does this in a
* chronological order based on the IDs of the migrations.
*
* @param $version The version to migrate to. If you specify the special
* cases "up" or "down", it will go one migration "up" or
* "down". If it's a number, if will migrate "up" or "down"
* to that specific version.
*/
protected function applyMigrations($version='') {
// Get the list of applied and possible migrations
$applied = $this->getAppliedMigrations();
$possible = $this->getPossibleMigrations();
// Check what which action need to happen
if ($version == 'list') {
// List the status of all migrations
foreach ($possible as $id => $specs) {
if (in_array($id, $applied)) {
echo('Applied: ' . $specs['class'] . PHP_EOL);
} else {
echo('Not Applied: ' . $specs['class'] . PHP_EOL);
}
}
+ } elseif ($version == 'create') {
+
+ // Get the name from the migration
+ $name = 'UntitledMigration';
+ if (isset($this->args[1]) && !empty($this->args[1])) {
+ $name = trim($this->args[1]);
+ }
+ $name = strftime('m%Y%m%d%H%M%S_' . $name);
+
+ // Read the template file
+ $data = file_get_contents(
+ dirname(__FILE__) . '/templates/migration.php'
+ );
+ $data = str_replace('${name}', $name, $data);
+
+ // Save the file
+ if (!is_dir($this->migrationsDir)) {
+ mkdir($this->migrationsDir);
+ }
+ file_put_contents(
+ $this->migrationsDir . '/' . $name . '.php', $data
+ );
+ echo('Created migration: ' . $name . '.php' . PHP_EOL);
+
} elseif ($version == 'down') {
// Get the last migration
$migration = array_pop($applied);
// Apply the migration
if ($migration) {
$this->applyMigration(
$possible[$migration]['class'],
$possible[$migration]['file'],
'down'
);
}
} elseif ($version == 'up') {
// Check if there are still versions to apply
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
// Exit the loop
break;
}
}
} elseif (!empty($version)) {
// Check if it's a valid version number
if (!isset($possible[$version])) {
throw new CDbMigrationEngineException(
'Invalid migration: ' . $version
);
}
// Check if we need to go up or down
if (in_array($version, $applied)) {
// Reverse loop over the possible migrations
foreach (array_reverse($possible, true) as $id => $specs) {
// If we reached the correct version, exit the loop
if ($id == $version) {
break;
}
// Check if it's applied or not
if (in_array($id, $applied)) {
// Remove the migration
$this->applyMigration(
$specs['class'], $specs['file'], 'down'
);
}
}
} else {
// Loop over all possible migrations
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
// If we applied the requested migration, exit the loop
if ($id == $version) {
break;
}
}
}
}
} else {
// Loop over all possible migrations
foreach ($possible as $id => $specs) {
// Check if it's applied or not
if (!in_array($id, $applied)) {
// Apply it
$this->applyMigration(
$specs['class'], $specs['file'], 'up'
);
}
}
}
}
/**
* Apply a specific migration based on the migration name.
*
* @param $class The class name of the migration to apply.
* @param $file The file in which you can find the migration.
* @param $direction The direction in which the migration needs to be
* applied. Needs to be "up" or "down".
*/
protected function applyMigration($class, $file, $direction='up') {
// Include the migration file
require_once($file);
// Create the migration
$migration = new $class($this->adapter);
// Apply the migration
if ($direction == 'up') {
echo('Applying migration: ' . $class . PHP_EOL);
} else {
echo('Removing migration: ' . $class . PHP_EOL);
}
// Perform the migration function transactional
$migration->performTransactional($direction);
// Commit the migration
if ($direction == 'up') {
echo(
'Marking migration as applied: ' . $class . PHP_EOL
);
$cmd = Yii::app()->db->commandBuilder->createInsertCommand(
self::SCHEMA_TABLE,
array(self::SCHEMA_FIELD => $migration->getId())
)->execute();
} else {
echo(
'Marking migration as removed: ' . $class . PHP_EOL
);
$sql = 'DELETE FROM '
. $this->adapter->db->quoteTableName(self::SCHEMA_TABLE)
. ' WHERE '
. $this->adapter->db->quoteColumnName(self::SCHEMA_FIELD)
. ' = '
. $this->adapter->db->quoteValue($migration->getId());
$this->adapter->execute($sql);
}
}
}
\ No newline at end of file
diff --git a/templates/migration.php b/templates/migration.php
new file mode 100644
index 0000000..6495022
--- /dev/null
+++ b/templates/migration.php
@@ -0,0 +1,11 @@
+<?php
+
+class ${name} extends CDbMigration {
+
+ public function up() {
+ }
+
+ public function down() {
+ }
+
+}
\ No newline at end of file
|
elchingon/yii-dbmigrations | 6e348a1fe0b115191fcaaf890ffd71eea73550d7 | Code cleanup. | diff --git a/CDbMigration.php b/CDbMigration.php
index 00941e3..52e85aa 100644
--- a/CDbMigration.php
+++ b/CDbMigration.php
@@ -1,270 +1,269 @@
<?php
/**
* CDbMigration class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* @package extensions.yii-dbmigrations
*/
class CDbMigrationException extends Exception {}
/**
* This class abstracts a database migration. The main functions that you will
* need to implement for creating a migration are the up and down methods.
*
* The up method will be applied when the migration gets installed into the
* system, the down method when the migration gets removed from the system.
*
* @package extensions.yii-dbmigrations
*/
abstract class CDbMigration {
/**
* The CDbMigrationAdapater that is used to perform the actual migrations
* on the database.
*/
public $adapter;
/**
* Class constructor for the CDbMigration class.
*
* @param $adapter The CDbMigrationAdapater that is used to perform the
* actual migrations on the database.
*/
public function __construct(CDbMigrationAdapter $adapter) {
$this->adapter = $adapter;
}
/**
* This method will execute the given class method inside a database
* transaction. It will raise an exception if the class method doesn't
* exist.
*
* For the transaction handling, we rely on the Yii DB functionality. If
* the database doesn't support transactions, the SQL statements will be
* executed one after another without using transactions.
*
* If the command succeeds, the transaction will get committed, if not, a
* rollback of the transaction will happen.
*
* @param $command The name of the class method to execute.
*/
public function performTransactional($command) {
// Check if the class method exists
if (!method_exists($this, $command)) {
throw new CDbMigrationException(
'Invalid migration command: ' . $command
);
}
// Run the command inside a transaction
$transaction = $this->adapter->db->beginTransaction();
try {
$this->$command();
$transaction->commit();
} catch (Exception $e) {
- //echo('ERROR: '. $e->getMessage() . PHP_EOL);
$transaction->rollback();
throw new CDbMigrationException($e->getMessage());
}
}
/**
* The up class method contains all the statements that will be executed
* when the migration is applied to the database.
*/
public function up() {
}
/**
* The up class method contains all the statements that will be executed
* when the migration is removed the database.
*/
public function down() {
}
/**
* This function returns the ID of the migration.
*
* Given the following migration class name:
*
* <code>m20090611153243_CreateTables</code>
*
* The id for this migration will be:
*
* <code>20090611153243</code>
*
* @returns The ID of the migration.
*/
public function getId() {
$id = split('_', get_class($this));
return substr($id[0], 1);
}
/**
* This function returns the name of the migration.
*
* Given the following migration class name:
*
* <code>m20090611153243_CreateTables</code>
*
* The name for this migration will be:
*
* <code>CreateTables</code>
*
* @returns The name of the migration.
*/
public function getName() {
$name = split('_', get_class($this));
return join('_', array_slice($name, 1, sizeof($name) - 1));
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that doesn't return any data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The number of affected rows.
*/
protected function execute($query, $params=array()) {
return $this->adapter->execute($query, $params);
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that returns data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The rows returned from the database.
*/
protected function query($query, $params=array()) {
return $this->adapter->query($query, $params);
}
/**
* The createTable function allows you to create a new table in the
* database.
*
* @param $name The name of the table to create.
* @param $column The column definition for the database table
* @param $options The extra options to pass to the database creation.
*/
protected function createTable($name, $columns=array(), $options=null) {
echo(' >> Creating table: ' . $name . PHP_EOL);
return $this->adapter->createTable($name, $columns, $options);
}
/**
* Rename a table.
*
* @param $name The name of the table to rename.
* @param $new_name The new name for the table.
*/
protected function renameTable($name, $new_name) {
echo(' >> Renaming table: ' . $name . ' to: ' . $new_name . PHP_EOL);
return $this->adapter->renameTable($name, $new_name);
}
/**
* Remove a table from the database.
*
* @param $name The name of the table to remove.
*/
protected function removeTable($name) {
echo(' >> Removing table: ' . $name . PHP_EOL);
return $this->adapter->removeTable($name);
}
/**
* Add a database column to an existing table.
*
* @param $table The table to add the column in.
* @param $column The name of the column to add.
* @param $type The data type for the new column.
* @param $options The extra options to pass to the column.
*/
protected function addColumn($table, $column, $type, $options=null) {
echo(' >> Adding column ' . $column . ' to table: ' . $table . PHP_EOL);
return $this->adapter->addColumn($table, $column, $type, $options);
}
/**
* Rename a database column in an existing table.
*
* @param $table The table to rename the column from.
* @param $name The current name of the column.
* @param $new_name The new name of the column.
*/
protected function renameColumn($table, $name, $new_name) {
echo(
' >> Renaming column ' . $name . ' to: ' . $new_name
. ' in table: ' . $table . PHP_EOL
);
return $this->adapter->renameColumn($table, $name, $new_name);
}
/**
* Change a database column in an existing table.
*
* @param $table The name of the table to change the column from.
* @param $column The name of the column to change.
* @param $type The new data type for the column.
* @param $options The extra options to pass to the column.
*/
protected function changeColumn($table, $column, $type, $options=null) {
echo(
' >> Chaning column ' . $name . ' to: ' . $type
. ' in table: ' . $table . PHP_EOL
);
return $this->adapter->changeColumn($table, $column, $type, $options);
}
/**
* Remove a table column from the database.
*
* @param $table The name of the table to remove the column from.
* @param $column The name of the table column to remove.
*/
protected function removeColumn($table, $column) {
echo(
' >> Removing column ' . $column . ' from table: ' . $table . PHP_EOL
);
return $this->adapter->removeColumn($table, $column);
}
/**
* Add an index to the database or a specific table.
*
* @param $table The name of the table to add the index to.
* @param $name The name of the index to create.
* @param $columns The name of the fields to include in the index.
* @param $unique If set to true, a unique index will be created.
*/
public function addIndex($table, $name, $columns, $unique=false) {
echo(' >> Adding index ' . $name . ' to table: ' . $table . PHP_EOL);
return $this->adapter->addIndex($table, $name, $columns, $unique);
}
/**
* Remove a table index from the database.
*
* @param $table The name of the table to remove the index from.
* @param $column The name of the table index to remove.
*/
protected function removeIndex($table, $name) {
echo(' >> Removing index ' . $name . ' from table: ' . $table . PHP_EOL);
return $this->adapter->removeIndex($table, $name);
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | 02cbab27337363b2a63f5eba3ca6c16d6f6d3f05 | Improved the error handling even more. | diff --git a/CDbMigration.php b/CDbMigration.php
index 519c020..00941e3 100644
--- a/CDbMigration.php
+++ b/CDbMigration.php
@@ -1,269 +1,270 @@
<?php
/**
* CDbMigration class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* @package extensions.yii-dbmigrations
*/
class CDbMigrationException extends Exception {}
/**
* This class abstracts a database migration. The main functions that you will
* need to implement for creating a migration are the up and down methods.
*
* The up method will be applied when the migration gets installed into the
* system, the down method when the migration gets removed from the system.
*
* @package extensions.yii-dbmigrations
*/
abstract class CDbMigration {
/**
* The CDbMigrationAdapater that is used to perform the actual migrations
* on the database.
*/
public $adapter;
/**
* Class constructor for the CDbMigration class.
*
* @param $adapter The CDbMigrationAdapater that is used to perform the
* actual migrations on the database.
*/
public function __construct(CDbMigrationAdapter $adapter) {
$this->adapter = $adapter;
}
/**
* This method will execute the given class method inside a database
* transaction. It will raise an exception if the class method doesn't
* exist.
*
* For the transaction handling, we rely on the Yii DB functionality. If
* the database doesn't support transactions, the SQL statements will be
* executed one after another without using transactions.
*
* If the command succeeds, the transaction will get committed, if not, a
* rollback of the transaction will happen.
*
* @param $command The name of the class method to execute.
*/
public function performTransactional($command) {
// Check if the class method exists
if (!method_exists($this, $command)) {
throw new CDbMigrationException(
'Invalid migration command: ' . $command
);
}
// Run the command inside a transaction
$transaction = $this->adapter->db->beginTransaction();
try {
$this->$command();
$transaction->commit();
} catch (Exception $e) {
- echo('ERROR: '. $e->getMessage() . PHP_EOL);
+ //echo('ERROR: '. $e->getMessage() . PHP_EOL);
$transaction->rollback();
+ throw new CDbMigrationException($e->getMessage());
}
}
/**
* The up class method contains all the statements that will be executed
* when the migration is applied to the database.
*/
public function up() {
}
/**
* The up class method contains all the statements that will be executed
* when the migration is removed the database.
*/
public function down() {
}
/**
* This function returns the ID of the migration.
*
* Given the following migration class name:
*
* <code>m20090611153243_CreateTables</code>
*
* The id for this migration will be:
*
* <code>20090611153243</code>
*
* @returns The ID of the migration.
*/
public function getId() {
$id = split('_', get_class($this));
return substr($id[0], 1);
}
/**
* This function returns the name of the migration.
*
* Given the following migration class name:
*
* <code>m20090611153243_CreateTables</code>
*
* The name for this migration will be:
*
* <code>CreateTables</code>
*
* @returns The name of the migration.
*/
public function getName() {
$name = split('_', get_class($this));
return join('_', array_slice($name, 1, sizeof($name) - 1));
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that doesn't return any data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The number of affected rows.
*/
protected function execute($query, $params=array()) {
return $this->adapter->execute($query, $params);
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that returns data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The rows returned from the database.
*/
protected function query($query, $params=array()) {
return $this->adapter->query($query, $params);
}
/**
* The createTable function allows you to create a new table in the
* database.
*
* @param $name The name of the table to create.
* @param $column The column definition for the database table
* @param $options The extra options to pass to the database creation.
*/
protected function createTable($name, $columns=array(), $options=null) {
echo(' >> Creating table: ' . $name . PHP_EOL);
return $this->adapter->createTable($name, $columns, $options);
}
/**
* Rename a table.
*
* @param $name The name of the table to rename.
* @param $new_name The new name for the table.
*/
protected function renameTable($name, $new_name) {
echo(' >> Renaming table: ' . $name . ' to: ' . $new_name . PHP_EOL);
return $this->adapter->renameTable($name, $new_name);
}
/**
* Remove a table from the database.
*
* @param $name The name of the table to remove.
*/
protected function removeTable($name) {
echo(' >> Removing table: ' . $name . PHP_EOL);
return $this->adapter->removeTable($name);
}
/**
* Add a database column to an existing table.
*
* @param $table The table to add the column in.
* @param $column The name of the column to add.
* @param $type The data type for the new column.
* @param $options The extra options to pass to the column.
*/
protected function addColumn($table, $column, $type, $options=null) {
echo(' >> Adding column ' . $column . ' to table: ' . $table . PHP_EOL);
return $this->adapter->addColumn($table, $column, $type, $options);
}
/**
* Rename a database column in an existing table.
*
* @param $table The table to rename the column from.
* @param $name The current name of the column.
* @param $new_name The new name of the column.
*/
protected function renameColumn($table, $name, $new_name) {
echo(
' >> Renaming column ' . $name . ' to: ' . $new_name
. ' in table: ' . $table . PHP_EOL
);
return $this->adapter->renameColumn($table, $name, $new_name);
}
/**
* Change a database column in an existing table.
*
* @param $table The name of the table to change the column from.
* @param $column The name of the column to change.
* @param $type The new data type for the column.
* @param $options The extra options to pass to the column.
*/
protected function changeColumn($table, $column, $type, $options=null) {
echo(
' >> Chaning column ' . $name . ' to: ' . $type
. ' in table: ' . $table . PHP_EOL
);
return $this->adapter->changeColumn($table, $column, $type, $options);
}
/**
* Remove a table column from the database.
*
* @param $table The name of the table to remove the column from.
* @param $column The name of the table column to remove.
*/
protected function removeColumn($table, $column) {
echo(
' >> Removing column ' . $column . ' from table: ' . $table . PHP_EOL
);
return $this->adapter->removeColumn($table, $column);
}
/**
* Add an index to the database or a specific table.
*
* @param $table The name of the table to add the index to.
* @param $name The name of the index to create.
* @param $columns The name of the fields to include in the index.
* @param $unique If set to true, a unique index will be created.
*/
public function addIndex($table, $name, $columns, $unique=false) {
echo(' >> Adding index ' . $name . ' to table: ' . $table . PHP_EOL);
return $this->adapter->addIndex($table, $name, $columns, $unique);
}
/**
* Remove a table index from the database.
*
* @param $table The name of the table to remove the index from.
* @param $column The name of the table index to remove.
*/
protected function removeIndex($table, $name) {
echo(' >> Removing index ' . $name . ' from table: ' . $table . PHP_EOL);
return $this->adapter->removeIndex($table, $name);
}
}
\ No newline at end of file
diff --git a/CDbMigrationCommand.php b/CDbMigrationCommand.php
index 72e4c0c..75b6696 100644
--- a/CDbMigrationCommand.php
+++ b/CDbMigrationCommand.php
@@ -1,81 +1,85 @@
<?php
/**
* CDbMigrationCommand class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the different extension components.
*/
Yii::import('application.extensions.yii-dbmigrations.*');
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* This class creates the migrate console command so that you can use it with
* the yiic tool inside your project.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationCommand extends CConsoleCommand {
/**
* Return the help for the migrate command.
*/
public function getHelp() {
return <<<EOD
USAGE
migrate [version|up|down|list]
DESCRIPTION
This command applies the database migrations which can be found in the
migrations directory in your project folder.
PARAMETERS
* version: options, the ID of the migration to migrate the database to.
* up: optional, apply the first migration that is not applied to the database
yet.
* down: remove the last applied migration from the database.
* list: list all the migrations available in the application and show if they
are applied or not.
EXAMPLES
* Apply all migrations that are not applied yet:
migrate
* Migrate up to version 20090612163144 if it's not applied yet:
migrate 20090612163144
* Migrate down to version 20090612163144 if it's applied already:
migrate 20090612163144
* Apply the first migration that is not applied to the database yet:
migrate up
* Remove the last applied migration:
migrate down
* List all the migrations found in the application and their status:
migrate list
EOD;
}
/**
* Runs the actual command passing along the command line parameters.
*
* @param $args The command line parameters
*/
public function run($args) {
- $engine = new CDbMigrationEngine();
- $engine->run($args);
+ try {
+ $engine = new CDbMigrationEngine();
+ $engine->run($args);
+ } catch (Exception $e) {
+ echo('FATAL ERROR: ' . $e->getMessage());
+ }
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | e680494eb9f5e297e2c18f359e45dbff8bdbd3f1 | Removed the options when altering a database column. | diff --git a/CDbMigrationAdapter.php b/CDbMigrationAdapter.php
index 1a0b057..caf076e 100644
--- a/CDbMigrationAdapter.php
+++ b/CDbMigrationAdapter.php
@@ -1,224 +1,221 @@
<?php
/**
* CDbMigrationAdapter class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* @package extensions.yii-dbmigrations
*/
abstract class CDbMigrationAdapter {
/**
* The database connection
*/
public $db;
/**
* Class Constructor
*/
public function __construct(CDbConnection $db) {
$this->db = $db;
}
/**
* Convert a type to a native database type
*/
protected function convertToNativeType($theType) {
if (isset($this->nativeDatabaseTypes[$theType])) {
return $this->nativeDatabaseTypes[$theType];
} else {
return $theType;
}
}
/**
* Convert the field information to native types
*/
protected function convertFields($fields) {
$result = array();
foreach ($fields as $field) {
if (is_array($field)) {
if (isset($field[0])) {
$field[0] = $this->db->quoteColumnName($field[0]);
}
if (isset($field[1])) {
$field[1] = $this->convertToNativeType($field[1]);
}
$result[] = join(' ', $field);
} else {
$result[] = $this->db->quoteColumnName($field);
}
}
return join(', ', $result);
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that doesn't return any data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The number of affected rows.
*/
public function execute($query, $params=array()) {
return $this->db->createCommand($query)->execute();
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that returns data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The rows returned from the database.
*/
public function query($query, $params=array()) {
return $this->db->createCommand($query)->queryAll();
}
/**
* Retrieve the type information from a database column.
*
* @returns The current data type of the column.
*/
public function columnInfo($table, $name) {
}
/**
* The createTable function allows you to create a new table in the
* database.
*
* @param $name The name of the table to create.
* @param $column The column definition for the database table
* @param $options The extra options to pass to the database creation.
*/
public function createTable($name, $columns=array(), $options=null) {
$sql = 'CREATE TABLE ' . $this->db->quoteTableName($name) . ' ('
. $this->convertFields($columns)
. ') ' . $options;
return $this->execute($sql);
}
/**
* Rename a table.
*
* @param $name The name of the table to rename.
* @param $new_name The new name for the table.
*/
public function renameTable($name, $new_name) {
$sql = 'RENAME TABLE ' . $this->db->quoteTableName($name) . ' TO '
. $this->db->quoteTableName($new_name);
return $this->execute($sql);
}
/**
* Remove a table from the database.
*
* @param $name The name of the table to remove.
*/
public function removeTable($name) {
$sql = 'DROP TABLE ' . $this->db->quoteTableName($name);
return $this->execute($sql);
}
/**
* Add a database column to an existing table.
*
* @param $table The table to add the column in.
* @param $column The name of the column to add.
* @param $type The data type for the new column.
* @param $options The extra options to pass to the column.
*/
public function addColumn($table, $column, $type, $options=null) {
$type = $this->convertToNativeType($type);
- if (empty($options)) {
- $options = 'NOT NULL';
- }
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD '
. $this->db->quoteColumnName($column) . ' ' . $type . ' '
. $options;
return $this->execute($sql);
}
/**
* Rename a database column in an existing table.
*
* @param $table The table to rename the column from.
* @param $name The current name of the column.
* @param $new_name The new name of the column.
*/
public function renameColumn($table, $name, $new_name) {
$type = $this->columnInfo($table, $name);
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
. $this->db->quoteColumnName($name) . ' '
. $this->db->quoteColumnName($new_name) . ' ' . $type;
return $this->execute($sql);
}
/**
* Change a database column in an existing table.
*
* @param $table The name of the table to change the column from.
* @param $column The name of the column to change.
* @param $type The new data type for the column.
* @param $options The extra options to pass to the column.
*/
public function changeColumn($table, $column, $type, $options=null) {
$type = $this->convertToNativeType($type);
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
. $this->db->quoteColumnName($column) . ' '
. $this->db->quoteColumnName($column) . ' ' . $type . ' '
. $options;
return $this->execute($sql);
}
/**
* Remove a table column from the database.
*
* @param $table The name of the table to remove the column from.
* @param $column The name of the table column to remove.
*/
public function removeColumn($table, $column) {
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' DROP '
. $this->db->quoteColumnName($column);
return $this->execute($sql);
}
/**
* Add an index to the database or a specific table.
*
* @param $table The name of the table to add the index to.
* @param $name The name of the index to create.
* @param $columns The name of the fields to include in the index.
* @param $unique If set to true, a unique index will be created.
*/
public function addIndex($table, $name, $columns, $unique=false) {
$sql = 'CREATE ';
$sql .= ($unique) ? 'UNIQUE ' : '';
$sql .= 'INDEX ' . $this->db->quoteColumnName($name) . ' ON '
. $this->db->quoteTableName($table) . ' ('
. $this->convertFields($columns)
. ')';
return $this->execute($sql);
}
/**
* Remove a table index from the database.
*
* @param $table The name of the table to remove the index from.
* @param $column The name of the table index to remove.
*/
public function removeIndex($table, $name) {
$sql = 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON '
. $this->db->quoteTableName($table);
return $this->execute($sql);
}
}
|
elchingon/yii-dbmigrations | 29088f6b805f21aae3bcdc34d36c0e02bdcba725 | Fixed the removeIndex function for SQLite. | diff --git a/adapters/CDbMigrationAdapterSqlite.php b/adapters/CDbMigrationAdapterSqlite.php
index 42b3dab..740ee00 100644
--- a/adapters/CDbMigrationAdapterSqlite.php
+++ b/adapters/CDbMigrationAdapterSqlite.php
@@ -1,100 +1,111 @@
<?php
/**
* CDbMigrationAdapterSqlite class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* The SQLite specific version of the database migration adapter.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationAdapterSqlite extends CDbMigrationAdapter {
/**
* The mapping of the database type definitions to the native database
* types of the database backend.
*/
protected $nativeDatabaseTypes = array(
'primary_key' => 'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL',
'string' => 'varchar(255)',
'text' => 'text',
'integer' => 'integer',
'float' => 'float',
'decimal' => 'decimal',
'datetime' => 'datetime',
'timestamp' => 'datetime',
'time' => 'time',
'date' => 'date',
'binary' => 'blob',
'boolean' => 'tinyint(1)',
'bool' => 'tinyint(1)',
);
/**
* Retrieve the type information from a database column.
*
* @returns The current data type of the column.
*/
public function columnInfo($table, $name) {
throw new CDbMigrationException(
'columnInfo is not supported for SQLite'
);
}
/**
* Rename a table.
*
* @param $name The name of the table to rename.
* @param $new_name The new name for the table.
*/
public function renameTable($name, $new_name) {
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($name) . ' RENAME TO '
. $this->db->quoteTableName($new_name);
return $this->execute($sql);
}
/**
* Rename a database column in an existing table.
*
* @param $table The table to rename the column from.
* @param $name The current name of the column.
* @param $new_name The new name of the column.
*/
public function renameColumn($table, $name, $new_name) {
throw new CDbMigrationException(
'renameColumn is not supported for SQLite'
);
}
/**
* Change a database column in an existing table.
*
* @param $table The name of the table to change the column from.
* @param $column The name of the column to change.
* @param $type The new data type for the column.
* @param $options The extra options to pass to the column.
*/
public function changeColumn($table, $column, $type, $options=null) {
throw new CDbMigrationException(
'changeColumn is not supported for SQLite'
);
}
/**
* Remove a table column from the database.
*
* @param $table The name of the table to remove the column from.
* @param $column The name of the table column to remove.
*/
public function removeColumn($table, $column) {
throw new CDbMigrationException(
'removeColumn is not supported for SQLite'
);
}
+ /**
+ * Remove a table index from the database.
+ *
+ * @param $table The name of the table to remove the index from.
+ * @param $column The name of the table index to remove.
+ */
+ public function removeIndex($table, $name) {
+ $sql = 'DROP INDEX ' . $this->db->quoteTableName($name);
+ return $this->execute($sql);
+ }
+
}
|
elchingon/yii-dbmigrations | d6668402a106c82c8d510be332e6b0009b6338e8 | Added better error handling. | diff --git a/CDbMigration.php b/CDbMigration.php
index 9c8d5be..519c020 100644
--- a/CDbMigration.php
+++ b/CDbMigration.php
@@ -1,268 +1,269 @@
<?php
/**
* CDbMigration class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* @package extensions.yii-dbmigrations
*/
class CDbMigrationException extends Exception {}
/**
* This class abstracts a database migration. The main functions that you will
* need to implement for creating a migration are the up and down methods.
*
* The up method will be applied when the migration gets installed into the
* system, the down method when the migration gets removed from the system.
*
* @package extensions.yii-dbmigrations
*/
abstract class CDbMigration {
/**
* The CDbMigrationAdapater that is used to perform the actual migrations
* on the database.
*/
public $adapter;
/**
* Class constructor for the CDbMigration class.
*
* @param $adapter The CDbMigrationAdapater that is used to perform the
* actual migrations on the database.
*/
public function __construct(CDbMigrationAdapter $adapter) {
$this->adapter = $adapter;
}
/**
* This method will execute the given class method inside a database
* transaction. It will raise an exception if the class method doesn't
* exist.
*
* For the transaction handling, we rely on the Yii DB functionality. If
* the database doesn't support transactions, the SQL statements will be
* executed one after another without using transactions.
*
* If the command succeeds, the transaction will get committed, if not, a
* rollback of the transaction will happen.
*
* @param $command The name of the class method to execute.
*/
public function performTransactional($command) {
// Check if the class method exists
if (!method_exists($this, $command)) {
throw new CDbMigrationException(
'Invalid migration command: ' . $command
);
}
// Run the command inside a transaction
$transaction = $this->adapter->db->beginTransaction();
try {
$this->$command();
$transaction->commit();
} catch (Exception $e) {
+ echo('ERROR: '. $e->getMessage() . PHP_EOL);
$transaction->rollback();
}
}
/**
* The up class method contains all the statements that will be executed
* when the migration is applied to the database.
*/
public function up() {
}
/**
* The up class method contains all the statements that will be executed
* when the migration is removed the database.
*/
public function down() {
}
/**
* This function returns the ID of the migration.
*
* Given the following migration class name:
*
* <code>m20090611153243_CreateTables</code>
*
* The id for this migration will be:
*
* <code>20090611153243</code>
*
* @returns The ID of the migration.
*/
public function getId() {
$id = split('_', get_class($this));
return substr($id[0], 1);
}
/**
* This function returns the name of the migration.
*
* Given the following migration class name:
*
* <code>m20090611153243_CreateTables</code>
*
* The name for this migration will be:
*
* <code>CreateTables</code>
*
* @returns The name of the migration.
*/
public function getName() {
$name = split('_', get_class($this));
return join('_', array_slice($name, 1, sizeof($name) - 1));
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that doesn't return any data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The number of affected rows.
*/
protected function execute($query, $params=array()) {
return $this->adapter->execute($query, $params);
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that returns data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The rows returned from the database.
*/
protected function query($query, $params=array()) {
return $this->adapter->query($query, $params);
}
/**
* The createTable function allows you to create a new table in the
* database.
*
* @param $name The name of the table to create.
* @param $column The column definition for the database table
* @param $options The extra options to pass to the database creation.
*/
protected function createTable($name, $columns=array(), $options=null) {
echo(' >> Creating table: ' . $name . PHP_EOL);
return $this->adapter->createTable($name, $columns, $options);
}
/**
* Rename a table.
*
* @param $name The name of the table to rename.
* @param $new_name The new name for the table.
*/
protected function renameTable($name, $new_name) {
echo(' >> Renaming table: ' . $name . ' to: ' . $new_name . PHP_EOL);
return $this->adapter->renameTable($name, $new_name);
}
/**
* Remove a table from the database.
*
* @param $name The name of the table to remove.
*/
protected function removeTable($name) {
echo(' >> Removing table: ' . $name . PHP_EOL);
return $this->adapter->removeTable($name);
}
/**
* Add a database column to an existing table.
*
* @param $table The table to add the column in.
* @param $column The name of the column to add.
* @param $type The data type for the new column.
* @param $options The extra options to pass to the column.
*/
protected function addColumn($table, $column, $type, $options=null) {
echo(' >> Adding column ' . $column . ' to table: ' . $table . PHP_EOL);
return $this->adapter->addColumn($table, $column, $type, $options);
}
/**
* Rename a database column in an existing table.
*
* @param $table The table to rename the column from.
* @param $name The current name of the column.
* @param $new_name The new name of the column.
*/
protected function renameColumn($table, $name, $new_name) {
echo(
' >> Renaming column ' . $name . ' to: ' . $new_name
. ' in table: ' . $table . PHP_EOL
);
return $this->adapter->renameColumn($table, $name, $new_name);
}
/**
* Change a database column in an existing table.
*
* @param $table The name of the table to change the column from.
* @param $column The name of the column to change.
* @param $type The new data type for the column.
* @param $options The extra options to pass to the column.
*/
protected function changeColumn($table, $column, $type, $options=null) {
echo(
' >> Chaning column ' . $name . ' to: ' . $type
. ' in table: ' . $table . PHP_EOL
);
return $this->adapter->changeColumn($table, $column, $type, $options);
}
/**
* Remove a table column from the database.
*
* @param $table The name of the table to remove the column from.
* @param $column The name of the table column to remove.
*/
protected function removeColumn($table, $column) {
echo(
' >> Removing column ' . $column . ' from table: ' . $table . PHP_EOL
);
return $this->adapter->removeColumn($table, $column);
}
/**
* Add an index to the database or a specific table.
*
* @param $table The name of the table to add the index to.
* @param $name The name of the index to create.
* @param $columns The name of the fields to include in the index.
* @param $unique If set to true, a unique index will be created.
*/
public function addIndex($table, $name, $columns, $unique=false) {
echo(' >> Adding index ' . $name . ' to table: ' . $table . PHP_EOL);
return $this->adapter->addIndex($table, $name, $columns, $unique);
}
/**
* Remove a table index from the database.
*
* @param $table The name of the table to remove the index from.
* @param $column The name of the table index to remove.
*/
protected function removeIndex($table, $name) {
echo(' >> Removing index ' . $name . ' from table: ' . $table . PHP_EOL);
return $this->adapter->removeIndex($table, $name);
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | fc1f903373dbc16b92ff522b7eb080085b06945c | Implemented the help for the migrate command. | diff --git a/CDbMigrationCommand.php b/CDbMigrationCommand.php
index 31932d5..72e4c0c 100644
--- a/CDbMigrationCommand.php
+++ b/CDbMigrationCommand.php
@@ -1,42 +1,81 @@
<?php
/**
* CDbMigrationCommand class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the different extension components.
*/
Yii::import('application.extensions.yii-dbmigrations.*');
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* This class creates the migrate console command so that you can use it with
* the yiic tool inside your project.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationCommand extends CConsoleCommand {
/**
* Return the help for the migrate command.
*/
public function getHelp() {
- return 'Used to run database migrations';
+ return <<<EOD
+USAGE
+ migrate [version|up|down|list]
+
+DESCRIPTION
+ This command applies the database migrations which can be found in the
+ migrations directory in your project folder.
+
+PARAMETERS
+ * version: options, the ID of the migration to migrate the database to.
+
+ * up: optional, apply the first migration that is not applied to the database
+ yet.
+
+ * down: remove the last applied migration from the database.
+
+ * list: list all the migrations available in the application and show if they
+ are applied or not.
+
+EXAMPLES
+ * Apply all migrations that are not applied yet:
+ migrate
+
+ * Migrate up to version 20090612163144 if it's not applied yet:
+ migrate 20090612163144
+
+ * Migrate down to version 20090612163144 if it's applied already:
+ migrate 20090612163144
+
+ * Apply the first migration that is not applied to the database yet:
+ migrate up
+
+ * Remove the last applied migration:
+ migrate down
+
+ * List all the migrations found in the application and their status:
+ migrate list
+
+EOD;
+
}
/**
* Runs the actual command passing along the command line parameters.
*
* @param $args The command line parameters
*/
public function run($args) {
$engine = new CDbMigrationEngine();
$engine->run($args);
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | df6dc57d29ba5608300b40ef9c9fe26b0e8ebf0d | Removed the documentation about migrations and modules as we first need to look on what the best way is to work with these. | diff --git a/README.textile b/README.textile
index 11408c4..ae84c3c 100644
--- a/README.textile
+++ b/README.textile
@@ -1,232 +1,224 @@
h1. Yii DB Migrations
A database migrations engine for the "Yii framework":http://www.yiiframework.com. It comes in the form of an extension which can be dropped into any existing Yii framework application.
It relies on the database abstraction layer of the Yii framework to talk to the database engine.
It's largely inspired on the migrations functionality of the Ruby on Rails framework.
h2. Why bother in the first place?
You might wonder why you need database migrations in the first place. Sure, you could use plain SQL files to apply updates to the database, but they have a big disadvantage: they are database specific.
Imagine you initially create your database using SQLite and later on decide to change to MySQL. When you use plain SQL files, you will need to rewrite them using MySQL's flavor of SQL. Also, you will need to create some tool that knows what has been applied already to the database and what's not applied yet.
Meet database migrations. By defining a higher level interface to creating and maintaining the database schema, you can define it in a database agnostic way.
By using PHP functions to create tables, indexes, fields, ... you can write the schema once and apply it to any database backend supported. The added bonus is that the yii-dbmigrations extension keeps track of which migrations have been applied already and which ones still need to be applied.
h2. Current limitations
Be aware that the current version is still very alpha.
There are only two database engines supported:
* MySQL
* SQLite
In the current version, it's only possible to migrate up, it cannot (yet) remove already installed migrations.
h2. Installing the extension
h3. Putting the files in the right location
Installing the extension is quite easy. Once you downloaded the files from github, you need to put all the files in a folder called "yii-dbmigrations" and put it in the <code>protected/extensions</code> folder from your project.
h3. Configuring the database connection
You need to make sure you configure database access properly in the configuration file of your project. As the console applications in the Yii framework look at the <code>protected/config/console.php</code> file, you need to make sure you configure the <code>db</code> settings under the <code>components</code> key in the configuration array. For MySQL, the configuration will look as follows:
<pre>
'components' => array(
'db'=>array(
'class' => 'CDbConnection',
'connectionString'=>'mysql:host=localhost;dbname=my_db',
'charset' => 'UTF8',
'username'=>'root',
'password'=>'root',
),
),
</pre>
For SQLite, the configuration looks as follows:
<pre>
'components' => array(
'db'=>array(
'connectionString'=>'sqlite:'.dirname(__FILE__).'/../data/my_db.db',
),
),
</pre>
h3. Configuring the command map
To make the <code>yiic</code> tool know about the <code>migrate</code> command, you need to add a <code>commandMap</code> key to the application configuration.
In there, you need to put the following configuration:
<pre>
'commandMap' => array(
'migrate' => array(
'class'=>'application.extensions.yii-dbmigrations.CDbMigrationCommand',
),
),
</pre>
h3. Testing your installation
To test if the installation was succesfull, you can run the yiic command and should see the following output:
<pre>
Yii command runner (based on Yii v1.0.6)
Usage: protected/yiic <command-name> [parameters...]
The following commands are available:
- migrate
- message
- shell
- webapp
To see individual command help, use the following:
protected/yiic help <command-name>
</pre>
It should mention that the <code>migrate</code> command is available.
h2. Creating migrations
h3. Naming conventions
You can create migrations by creating files in the <code>protected/migrations</code> folder or in the <code>migrations</code> folder inside your module. The file names for the migrations should follow a specific naming convention:
<pre>
m20090614213453_MigrationName.php
</pre>
The migration file names always start with the letter m followed by 14 digit timestamp and an underscore. After that, you can give a name to the migration so that you can easily identify the migration.
-If your migration is part of a module, it's a good idea to add the name of the module between the migration ID and name so that the name looks as follows:
-
-<pre>
-m20090614213453_ModuleName_MigrationName.php
-</pre>
-
-This will ensure that there is much less chance for naming conflicts between migrations in different modules.
-
h3. Implementing the migration
In the migration file, you need to create a class that extends the parent class <code>CDbMigration</code>. The <code>CDbMigration</code> class needs to have the <code>up</code> and <code>down</code> methods as you can see in the following sample migration:
<pre>
class m20090611153243_CreateTables extends CDbMigration {
public function up() {
$this->createTable(
'posts',
array(
array('id', 'primary_key'),
array('title', 'string'),
array('body', 'text'),
)
);
$this->addIndex(
'posts', 'posts_title', array('title')
);
}
public function down() {
$this->removeTable('posts');
}
}
</pre>
h3. Supported functionality
In the migration class, you have the following functionality available:
* execute: execute a raw SQL statement that doesn't return any data.
* query: execute a raw SQL statement that returns data.
* createTable: create a new table
* renameTable: rename a table
* removeTable: remove a table
* addColumn: add a column to a table
* renameColumn: rename a column in a table
* changeColumn: change the definition of a column in a table
* removeColumn: remove a column from a table
* addIndex: add an index to the database or table
* removeIndex: remove an index from the database or table
When specifying fields, we also support a type mapping so that you can use generic type definitions instead of database specific type definitions. The following types are supported:
* primary_key
* string
* text
* integer
* float
* decimal
* datetime
* timestamp
* time
* date
* binary
* boolean
* bool
You can also specify a database specific type when defining a field, but this will make your migrations less portable across database engines.
h2. Applying migrations
Once you created the migrations, you can apply them to your database by running the <code>migrate</code> command:
<pre>
protected/yiic migrate
</pre>
You will see the following output:
<pre>
Creating initial schema_version table
Applying migration: m20090611153243_CreateTables
>> Creating table: posts
>> Adding index posts_title to table: posts
Marking migration as applied: m20090611153243_CreateTables
Applying migration: m20090612162832_CreateTags
>> Creating table: tags
>> Creating table: post_tags
>> Adding index post_tags_post_tag to table: post_tags
Marking migration as applied: m20090612162832_CreateTags
Applying migration: m20090612163144_RenameTagsTable
>> Renaming table: post_tags to: post_tags_link_table
Marking migration as applied: m20090612163144_RenameTagsTable
Applying migration: m20090616153243_Test_CreateTables
>> Creating table: test_pages
>> Adding index test_pages_title to table: test_pages
Marking migration as applied: m20090616153243_Test_CreateTables
</pre>
It will apply all the migrations found in the <code>protected/migrations</code> directory provided they were not applied to the database yet.
It will also apply any migrations found in the <code>migrations</code> directory inside each module which is enabled in the application.
If you run the <code>migrate</code> command again, it will show that the migrations were applied already:
<pre>
Skipping applied migration: m20090611153243_CreateTables
Skipping applied migration: m20090612162832_CreateTags
Skipping applied migration: m20090612163144_RenameTagsTable
Skipping applied migration: m20090616153243_Test_CreateTables
</pre>
Since the <code>migrate</code> command checks based on the ID of each migration, it can detect that a migration is already applied to the database and therefor doesn't need to be applied anymore.
h2. Author information
This extension is created and maintained by Pieter Claerhout. You can contact the author on:
* Website: "http://www.yellowduck.be":http://www.yellowduck.be
* Twitter: "http://twitter.com/pieterclaerhout":http://twitter.com/pieterclaerhout
* Github: "http://github.com/pieterclaerhout/yii-dbmigrations/tree/master":http://github.com/pieterclaerhout/yii-dbmigrations/tree/master
|
elchingon/yii-dbmigrations | 11d267edfa5627b598e33249bd9f5c67a3b6b126 | Made it possible to migrate in different directions: - Up - Down - All migrations that are not applied yet - List all migrations and their status - Migrate to a specific version | diff --git a/CDbMigrationEngine.php b/CDbMigrationEngine.php
index 35ea78e..c21df82 100644
--- a/CDbMigrationEngine.php
+++ b/CDbMigrationEngine.php
@@ -1,399 +1,453 @@
<?php
/**
* CDbMigrationEngine class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the adapters we are going to use for the migrations.
*/
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* A database migration engine exception
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngineException extends Exception {}
/**
* The CDbMigrationEngine class is the actual engine that can do all the
* migrations related functionality.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngine {
/**
* The migration adapter to use
*/
private $adapter;
/**
* The name of the table that contains the schema information.
*/
const SCHEMA_TABLE = 'schema_version';
/**
* The field in the schema_version table that contains the id of the
* installed migrations.
*/
const SCHEMA_FIELD = 'id';
/**
* The extension used for the migration files.
*/
const SCHEMA_EXT = 'php';
/**
* The directory in which the migrations can be found.
*/
const MIGRATIONS_DIR = 'migrations';
/**
* Run the database migration engine, passing on the command-line
* arguments.
*
* @param $args The command line parameters.
*/
public function run($args) {
// Catch errors
try {
// Initialize the engine
$this->init();
// Check if we need to create a migration
if (isset($args[0]) && !empty($args[0])) {
$this->applyMigrations($args[0]);
} else {
$this->applyMigrations();
}
} catch (Exception $e) {
echo('ERROR: ' . $e->getMessage() . PHP_EOL);
}
}
/**
* Initialize the database migration engine. Several things happen during
* this initialization:
* - The system checks if a database connection was configured.
* - The system checks if the database driver supports migrations.
* - If the schema_version table doesn't exist yet, it gets created.
*/
protected function init() {
// Check if a database connection was configured
try {
Yii::app()->db;
} catch (Exception $e) {
throw new CDbMigrationEngineException(
'Database configuration is missing in your configuration file.'
);
}
// Load the migration adapter
switch (Yii::app()->db->driverName) {
case 'mysql':
$this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
break;
case 'sqlite':
$this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
break;
default:
throw new CDbMigrationEngineException(
'Database of type ' . Yii::app()->db->driverName
. ' does not support migrations (yet).'
);
}
// Check if the schema version table exists
if (Yii::app()->db->schema->getTable('schema_version') == null) {
// Create the table
echo('Creating initial schema_version table' . PHP_EOL);
// Use the adapter to create the table
$this->adapter->createTable(
self::SCHEMA_TABLE,
array(
array(self::SCHEMA_FIELD, 'string'),
)
);
// Create an index on the column
$this->adapter->addIndex(
self::SCHEMA_TABLE,
'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
array(self::SCHEMA_FIELD),
true
);
}
}
/**
* Get the list of migrations that are applied to the database. This
* basically reads out the schema_version table from the database.
*
* @returns An array with the IDs of the already applied database
* migrations as found in the database.
*/
protected function getAppliedMigrations() {
// Get the field and table name
$field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
$table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
// Construct the SQL statement
$sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
// Get the list
return Yii::app()->db->createCommand($sql)->queryColumn(
self::SCHEMA_FIELD
);
}
/**
* Get the list of possible migrations from the file system. This will read
* the contents of the migrations directory and the migrations directory
* inside each installed and enabled module.
*
* @returns An array with the IDs of the possible database migrations as
* found in the database.
*/
protected function getPossibleMigrations() {
// Get the migrations for the default application
$migrations = $this->getPossibleMigrationsForModule();
/*
// Get the migrations for each installed and enabled module
foreach (Yii::app()->modules as $module => $moduleData) {
$migrations = array_merge(
$migrations, $this->getPossibleMigrationsForModule($module)
);
}
*/
// Sort them based on the file path (which is the key in the array)
ksort($migrations);
// Returh the list of migrations
return $migrations;
}
/**
* A helper function to get the list of migrations for a specific module.
* If no module is specified, it will return the list of modules from the
* "protected/migrations" directory.
*
* @param $module The name of the module to get the migrations for.
*/
protected function getPossibleMigrationsForModule($module=null) {
// Get the path to the migrations dir
$path = Yii::app()->basePath;
if (!empty($module)) {
$path .= '/modules/' . trim($module, '/');
}
$path .= '/' . self::MIGRATIONS_DIR;
// Start with an empty list
$migrations = array();
// Check if the migrations directory actually exists
if (is_dir($path)) {
// Construct the list of migrations
$migrationFiles = CFileHelper::findFiles(
$path,
array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
);
foreach ($migrationFiles as $migration) {
// Check if it's valid
if (substr(basename($migration), 0, 1) != 'm') {
continue;
}
// Include the file
include($migration);
// Get the class name
$className = basename($migration, '.' . self::SCHEMA_EXT);
// Check if the class exists
if (!class_exists($className) || strlen($className) < 16) {
continue;
}
// Check if the class is a valid migration
$migrationReflection = new ReflectionClass($className);
$baseReflection = new ReflectionClass('CDbMigration');
if (!$migrationReflection->isSubclassOf($baseReflection)) {
continue;
}
// Add them to the list
$id = substr($className, 1, 14);
$migrations[$id] = array(
'file' => $migration,
'class' => $className,
);
}
}
// Return the list
return $migrations;
}
/**
* Apply the migrations to the database. This will apply any migration that
* has not been applied to the database yet. It does this in a
* chronological order based on the IDs of the migrations.
*
* @param $version The version to migrate to. If you specify the special
* cases "up" or "down", it will go one migration "up" or
* "down". If it's a number, if will migrate "up" or "down"
* to that specific version.
*/
protected function applyMigrations($version='') {
// Get the list of applied and possible migrations
- $applied = $this->getAppliedMigrations();
+ $applied = $this->getAppliedMigrations();
$possible = $this->getPossibleMigrations();
- // Check what needs to happen
- if ($version == 'down') {
+ // Check what which action need to happen
+ if ($version == 'list') {
- // Check if there are any applied migrations
- if (sizeof($applied) == 0) {
- throw new CDbMigrationEngineException(
- 'No migrations are applied to the database yet.'
- );
+ // List the status of all migrations
+ foreach ($possible as $id => $specs) {
+ if (in_array($id, $applied)) {
+ echo('Applied: ' . $specs['class'] . PHP_EOL);
+ } else {
+ echo('Not Applied: ' . $specs['class'] . PHP_EOL);
+ }
}
- // Get the last applied migration
- $lastMigration = array_pop($applied);
+ } elseif ($version == 'down') {
- // Get the details
- $migration = $this->createMigration(
- $possible[$lastMigration]['class'],
- $possible[$lastMigration]['file']
- );
+ // Get the last migration
+ $migration = array_pop($applied);
// Apply the migration
- $this->applyMigration($migration, 'down');
-
- // Return
- return;
+ if ($migration) {
+ $this->applyMigration(
+ $possible[$migration]['class'],
+ $possible[$migration]['file'],
+ 'down'
+ );
+ }
- }
-
- // We are updating one or more revisions
- if (empty($version) || $version == 'up') {
+ } elseif ($version == 'up') {
- // Loop over all possible migrations
- foreach ($possible as $migrationId => $migrationSpecs) {
+ // Check if there are still versions to apply
+ foreach ($possible as $id => $specs) {
- // Include the migration file
- require_once($migrationSpecs['file']);
+ // Check if it's applied or not
+ if (!in_array($id, $applied)) {
+
+ // Apply it
+ $this->applyMigration(
+ $specs['class'], $specs['file'], 'up'
+ );
+
+ // Exit the loop
+ break;
+
+ }
- // Create the migration instance
- $migration = $this->createMigration(
- $migrationSpecs['class'], $migrationSpecs['file']
+ }
+
+ } elseif (!empty($version)) {
+
+ // Check if it's a valid version number
+ if (!isset($possible[$version])) {
+ throw new CDbMigrationEngineException(
+ 'Invalid migration: ' . $version
);
+ }
+
+ // Check if we need to go up or down
+ if (in_array($version, $applied)) {
- // Check if it's already applied to the database
- if (!in_array($migration->getId(), $applied)) {
-
- // Apply the migration to the database
- $this->applyMigration($migration);
+ // Reverse loop over the possible migrations
+ foreach (array_reverse($possible, true) as $id => $specs) {
- // If we do up, we stop after the first one
- if ($version == 'up') {
+ // If we reached the correct version, exit the loop
+ if ($id == $version) {
break;
}
+
+ // Check if it's applied or not
+ if (in_array($id, $applied)) {
+
+ // Remove the migration
+ $this->applyMigration(
+ $specs['class'], $specs['file'], 'down'
+ );
+
+ }
+
+ }
+
+ } else {
+
+ // Loop over all possible migrations
+ foreach ($possible as $id => $specs) {
+
+ // Check if it's applied or not
+ if (!in_array($id, $applied)) {
+
+ // Apply it
+ $this->applyMigration(
+ $specs['class'], $specs['file'], 'up'
+ );
+
+ // If we applied the requested migration, exit the loop
+ if ($id == $version) {
+ break;
+ }
+
+ }
+
+ }
+ }
+
+ } else {
+
+ // Loop over all possible migrations
+ foreach ($possible as $id => $specs) {
+
+ // Check if it's applied or not
+ if (!in_array($id, $applied)) {
+
+ // Apply it
+ $this->applyMigration(
+ $specs['class'], $specs['file'], 'up'
+ );
+
}
}
}
}
/**
- * This function creates a migration instance.
+ * Apply a specific migration based on the migration name.
*
- * @param $id The ID of the migration.
- * @param $file The file in which the migration exists
+ * @param $class The class name of the migration to apply.
+ * @param $file The file in which you can find the migration.
+ * @param $direction The direction in which the migration needs to be
+ * applied. Needs to be "up" or "down".
*/
- protected function createMigration($class, $file) {
+ protected function applyMigration($class, $file, $direction='up') {
// Include the migration file
require_once($file);
- // Create the migration instance
- return new $class($this->adapter);
-
- }
-
- /**
- * Apply a specific migration based on the migration name.
- *
- * @param $migration The name of the migration to apply.
- * @param $direction The direction in which the migration needs to be
- * applied. Needs to be "up" or "down".
- */
- protected function applyMigration($migration, $direction='up') {
+ // Create the migration
+ $migration = new $class($this->adapter);
// Apply the migration
if ($direction == 'up') {
- echo('Applying migration: ' . get_class($migration) . PHP_EOL);
+ echo('Applying migration: ' . $class . PHP_EOL);
} else {
- echo('Removing migration: ' . get_class($migration) . PHP_EOL);
+ echo('Removing migration: ' . $class . PHP_EOL);
}
// Perform the migration function transactional
$migration->performTransactional($direction);
// Commit the migration
if ($direction == 'up') {
echo(
- 'Marking migration as applied: ' . get_class($migration) . PHP_EOL
+ 'Marking migration as applied: ' . $class . PHP_EOL
);
$cmd = Yii::app()->db->commandBuilder->createInsertCommand(
self::SCHEMA_TABLE,
array(self::SCHEMA_FIELD => $migration->getId())
)->execute();
} else {
echo(
- 'Marking migration as removed: ' . get_class($migration) . PHP_EOL
+ 'Marking migration as removed: ' . $class . PHP_EOL
);
$sql = 'DELETE FROM '
. $this->adapter->db->quoteTableName(self::SCHEMA_TABLE)
. ' WHERE '
. $this->adapter->db->quoteColumnName(self::SCHEMA_FIELD)
. ' = '
. $this->adapter->db->quoteValue($migration->getId());
$this->adapter->execute($sql);
}
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | 0cffffd601c3027dbb8d2542e0729752f5783fc0 | Implemented the yiic migrate up command. | diff --git a/CDbMigrationEngine.php b/CDbMigrationEngine.php
index 30b0623..35ea78e 100644
--- a/CDbMigrationEngine.php
+++ b/CDbMigrationEngine.php
@@ -1,396 +1,399 @@
<?php
/**
* CDbMigrationEngine class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the adapters we are going to use for the migrations.
*/
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* A database migration engine exception
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngineException extends Exception {}
/**
* The CDbMigrationEngine class is the actual engine that can do all the
* migrations related functionality.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngine {
/**
* The migration adapter to use
*/
private $adapter;
/**
* The name of the table that contains the schema information.
*/
const SCHEMA_TABLE = 'schema_version';
/**
* The field in the schema_version table that contains the id of the
* installed migrations.
*/
const SCHEMA_FIELD = 'id';
/**
* The extension used for the migration files.
*/
const SCHEMA_EXT = 'php';
/**
* The directory in which the migrations can be found.
*/
const MIGRATIONS_DIR = 'migrations';
/**
* Run the database migration engine, passing on the command-line
* arguments.
*
* @param $args The command line parameters.
*/
public function run($args) {
// Catch errors
try {
// Initialize the engine
$this->init();
// Check if we need to create a migration
- if (isset($args[0]) && ($args[0] == 'down')) {
- $this->applyMigrations('down');
+ if (isset($args[0]) && !empty($args[0])) {
+ $this->applyMigrations($args[0]);
} else {
$this->applyMigrations();
}
} catch (Exception $e) {
echo('ERROR: ' . $e->getMessage() . PHP_EOL);
}
}
/**
* Initialize the database migration engine. Several things happen during
* this initialization:
* - The system checks if a database connection was configured.
* - The system checks if the database driver supports migrations.
* - If the schema_version table doesn't exist yet, it gets created.
*/
protected function init() {
// Check if a database connection was configured
try {
Yii::app()->db;
} catch (Exception $e) {
throw new CDbMigrationEngineException(
'Database configuration is missing in your configuration file.'
);
}
// Load the migration adapter
switch (Yii::app()->db->driverName) {
case 'mysql':
$this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
break;
case 'sqlite':
$this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
break;
default:
throw new CDbMigrationEngineException(
'Database of type ' . Yii::app()->db->driverName
. ' does not support migrations (yet).'
);
}
// Check if the schema version table exists
if (Yii::app()->db->schema->getTable('schema_version') == null) {
// Create the table
echo('Creating initial schema_version table' . PHP_EOL);
// Use the adapter to create the table
$this->adapter->createTable(
self::SCHEMA_TABLE,
array(
array(self::SCHEMA_FIELD, 'string'),
)
);
// Create an index on the column
$this->adapter->addIndex(
self::SCHEMA_TABLE,
'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
array(self::SCHEMA_FIELD),
true
);
}
}
/**
* Get the list of migrations that are applied to the database. This
* basically reads out the schema_version table from the database.
*
* @returns An array with the IDs of the already applied database
* migrations as found in the database.
*/
protected function getAppliedMigrations() {
// Get the field and table name
$field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
$table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
// Construct the SQL statement
$sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
// Get the list
return Yii::app()->db->createCommand($sql)->queryColumn(
self::SCHEMA_FIELD
);
}
/**
* Get the list of possible migrations from the file system. This will read
* the contents of the migrations directory and the migrations directory
* inside each installed and enabled module.
*
* @returns An array with the IDs of the possible database migrations as
* found in the database.
*/
protected function getPossibleMigrations() {
// Get the migrations for the default application
$migrations = $this->getPossibleMigrationsForModule();
/*
// Get the migrations for each installed and enabled module
foreach (Yii::app()->modules as $module => $moduleData) {
$migrations = array_merge(
$migrations, $this->getPossibleMigrationsForModule($module)
);
}
*/
// Sort them based on the file path (which is the key in the array)
ksort($migrations);
// Returh the list of migrations
return $migrations;
}
/**
* A helper function to get the list of migrations for a specific module.
* If no module is specified, it will return the list of modules from the
* "protected/migrations" directory.
*
* @param $module The name of the module to get the migrations for.
*/
protected function getPossibleMigrationsForModule($module=null) {
// Get the path to the migrations dir
$path = Yii::app()->basePath;
if (!empty($module)) {
$path .= '/modules/' . trim($module, '/');
}
$path .= '/' . self::MIGRATIONS_DIR;
// Start with an empty list
$migrations = array();
// Check if the migrations directory actually exists
if (is_dir($path)) {
// Construct the list of migrations
$migrationFiles = CFileHelper::findFiles(
$path,
array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
);
foreach ($migrationFiles as $migration) {
// Check if it's valid
if (substr(basename($migration), 0, 1) != 'm') {
continue;
}
// Include the file
include($migration);
// Get the class name
$className = basename($migration, '.' . self::SCHEMA_EXT);
// Check if the class exists
if (!class_exists($className) || strlen($className) < 16) {
continue;
}
// Check if the class is a valid migration
$migrationReflection = new ReflectionClass($className);
$baseReflection = new ReflectionClass('CDbMigration');
if (!$migrationReflection->isSubclassOf($baseReflection)) {
continue;
}
// Add them to the list
$id = substr($className, 1, 14);
$migrations[$id] = array(
'file' => $migration,
'class' => $className,
);
}
}
// Return the list
return $migrations;
}
/**
* Apply the migrations to the database. This will apply any migration that
* has not been applied to the database yet. It does this in a
* chronological order based on the IDs of the migrations.
*
* @param $version The version to migrate to. If you specify the special
* cases "up" or "down", it will go one migration "up" or
* "down". If it's a number, if will migrate "up" or "down"
* to that specific version.
*/
protected function applyMigrations($version='') {
// Get the list of applied and possible migrations
$applied = $this->getAppliedMigrations();
$possible = $this->getPossibleMigrations();
// Check what needs to happen
if ($version == 'down') {
// Check if there are any applied migrations
if (sizeof($applied) == 0) {
throw new CDbMigrationEngineException(
'No migrations are applied to the database yet.'
);
}
// Get the last applied migration
$lastMigration = array_pop($applied);
// Get the details
$migration = $this->createMigration(
$possible[$lastMigration]['class'],
$possible[$lastMigration]['file']
);
// Apply the migration
$this->applyMigration($migration, 'down');
// Return
return;
}
- // Loop over all possible migrations
- foreach ($possible as $migrationId => $migrationSpecs) {
+ // We are updating one or more revisions
+ if (empty($version) || $version == 'up') {
- // Include the migration file
- require_once($migrationSpecs['file']);
-
- // Create the migration instance
- $migration = $this->createMigration(
- $migrationSpecs['class'], $migrationSpecs['file']
- );
-
- // Check if it's already applied to the database
- if (!in_array($migration->getId(), $applied)) {
-
- // Apply the migration to the database
- $this->applyMigration($migration);
+ // Loop over all possible migrations
+ foreach ($possible as $migrationId => $migrationSpecs) {
- } else {
+ // Include the migration file
+ require_once($migrationSpecs['file']);
- // Skip the already applied migration
- echo(
- 'Skipping applied migration: ' . get_class($migration) . PHP_EOL
+ // Create the migration instance
+ $migration = $this->createMigration(
+ $migrationSpecs['class'], $migrationSpecs['file']
);
+ // Check if it's already applied to the database
+ if (!in_array($migration->getId(), $applied)) {
+
+ // Apply the migration to the database
+ $this->applyMigration($migration);
+
+ // If we do up, we stop after the first one
+ if ($version == 'up') {
+ break;
+ }
+
+ }
+
}
}
}
/**
* This function creates a migration instance.
*
* @param $id The ID of the migration.
* @param $file The file in which the migration exists
*/
protected function createMigration($class, $file) {
// Include the migration file
require_once($file);
// Create the migration instance
return new $class($this->adapter);
}
/**
* Apply a specific migration based on the migration name.
*
* @param $migration The name of the migration to apply.
* @param $direction The direction in which the migration needs to be
* applied. Needs to be "up" or "down".
*/
protected function applyMigration($migration, $direction='up') {
// Apply the migration
if ($direction == 'up') {
echo('Applying migration: ' . get_class($migration) . PHP_EOL);
} else {
echo('Removing migration: ' . get_class($migration) . PHP_EOL);
}
// Perform the migration function transactional
$migration->performTransactional($direction);
// Commit the migration
if ($direction == 'up') {
echo(
'Marking migration as applied: ' . get_class($migration) . PHP_EOL
);
$cmd = Yii::app()->db->commandBuilder->createInsertCommand(
self::SCHEMA_TABLE,
array(self::SCHEMA_FIELD => $migration->getId())
)->execute();
} else {
echo(
'Marking migration as removed: ' . get_class($migration) . PHP_EOL
);
$sql = 'DELETE FROM '
. $this->adapter->db->quoteTableName(self::SCHEMA_TABLE)
. ' WHERE '
. $this->adapter->db->quoteColumnName(self::SCHEMA_FIELD)
. ' = '
. $this->adapter->db->quoteValue($migration->getId());
$this->adapter->execute($sql);
}
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | 30ee8d0fa9500adf1c189c21a562c34175e47f33 | Implemented the yiic migrate down functionality. | diff --git a/CDbMigrationEngine.php b/CDbMigrationEngine.php
index 1ff2420..30b0623 100644
--- a/CDbMigrationEngine.php
+++ b/CDbMigrationEngine.php
@@ -1,325 +1,396 @@
<?php
/**
* CDbMigrationEngine class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the adapters we are going to use for the migrations.
*/
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* A database migration engine exception
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngineException extends Exception {}
/**
* The CDbMigrationEngine class is the actual engine that can do all the
* migrations related functionality.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngine {
/**
* The migration adapter to use
*/
private $adapter;
/**
* The name of the table that contains the schema information.
*/
const SCHEMA_TABLE = 'schema_version';
/**
* The field in the schema_version table that contains the id of the
* installed migrations.
*/
const SCHEMA_FIELD = 'id';
/**
* The extension used for the migration files.
*/
const SCHEMA_EXT = 'php';
/**
* The directory in which the migrations can be found.
*/
const MIGRATIONS_DIR = 'migrations';
/**
* Run the database migration engine, passing on the command-line
* arguments.
*
* @param $args The command line parameters.
*/
public function run($args) {
// Catch errors
try {
// Initialize the engine
$this->init();
// Check if we need to create a migration
- if (isset($args[0]) && ($args[0] == 'create')) {
- $this->create($args[0]);
+ if (isset($args[0]) && ($args[0] == 'down')) {
+ $this->applyMigrations('down');
} else {
$this->applyMigrations();
}
} catch (Exception $e) {
echo('ERROR: ' . $e->getMessage() . PHP_EOL);
}
}
/**
* Initialize the database migration engine. Several things happen during
* this initialization:
* - The system checks if a database connection was configured.
* - The system checks if the database driver supports migrations.
* - If the schema_version table doesn't exist yet, it gets created.
*/
protected function init() {
// Check if a database connection was configured
try {
Yii::app()->db;
} catch (Exception $e) {
throw new CDbMigrationEngineException(
'Database configuration is missing in your configuration file.'
);
}
// Load the migration adapter
switch (Yii::app()->db->driverName) {
case 'mysql':
$this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
break;
case 'sqlite':
$this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
break;
default:
throw new CDbMigrationEngineException(
'Database of type ' . Yii::app()->db->driverName
. ' does not support migrations (yet).'
);
}
// Check if the schema version table exists
if (Yii::app()->db->schema->getTable('schema_version') == null) {
// Create the table
echo('Creating initial schema_version table' . PHP_EOL);
// Use the adapter to create the table
$this->adapter->createTable(
self::SCHEMA_TABLE,
array(
array(self::SCHEMA_FIELD, 'string'),
)
);
// Create an index on the column
$this->adapter->addIndex(
self::SCHEMA_TABLE,
'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
array(self::SCHEMA_FIELD),
true
);
}
}
/**
* Get the list of migrations that are applied to the database. This
* basically reads out the schema_version table from the database.
*
* @returns An array with the IDs of the already applied database
* migrations as found in the database.
*/
protected function getAppliedMigrations() {
// Get the field and table name
$field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
$table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
// Construct the SQL statement
$sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
// Get the list
return Yii::app()->db->createCommand($sql)->queryColumn(
self::SCHEMA_FIELD
);
}
/**
* Get the list of possible migrations from the file system. This will read
* the contents of the migrations directory and the migrations directory
* inside each installed and enabled module.
*
* @returns An array with the IDs of the possible database migrations as
* found in the database.
*/
protected function getPossibleMigrations() {
// Get the migrations for the default application
$migrations = $this->getPossibleMigrationsForModule();
+ /*
// Get the migrations for each installed and enabled module
foreach (Yii::app()->modules as $module => $moduleData) {
$migrations = array_merge(
$migrations, $this->getPossibleMigrationsForModule($module)
);
}
+ */
// Sort them based on the file path (which is the key in the array)
ksort($migrations);
// Returh the list of migrations
return $migrations;
}
/**
* A helper function to get the list of migrations for a specific module.
* If no module is specified, it will return the list of modules from the
* "protected/migrations" directory.
*
* @param $module The name of the module to get the migrations for.
*/
protected function getPossibleMigrationsForModule($module=null) {
// Get the path to the migrations dir
$path = Yii::app()->basePath;
if (!empty($module)) {
$path .= '/modules/' . trim($module, '/');
}
$path .= '/' . self::MIGRATIONS_DIR;
// Start with an empty list
$migrations = array();
// Check if the migrations directory actually exists
if (is_dir($path)) {
// Construct the list of migrations
$migrationFiles = CFileHelper::findFiles(
$path,
array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
);
foreach ($migrationFiles as $migration) {
// Check if it's valid
if (substr(basename($migration), 0, 1) != 'm') {
continue;
}
// Include the file
include($migration);
// Get the class name
$className = basename($migration, '.' . self::SCHEMA_EXT);
// Check if the class exists
- if (!class_exists($className)) {
+ if (!class_exists($className) || strlen($className) < 16) {
continue;
}
// Check if the class is a valid migration
$migrationReflection = new ReflectionClass($className);
$baseReflection = new ReflectionClass('CDbMigration');
if (!$migrationReflection->isSubclassOf($baseReflection)) {
continue;
}
- // Add it the list
- $migrations[$migration] = basename(
- $migration, '.' . self::SCHEMA_EXT
+ // Add them to the list
+ $id = substr($className, 1, 14);
+ $migrations[$id] = array(
+ 'file' => $migration,
+ 'class' => $className,
);
}
}
// Return the list
return $migrations;
}
/**
* Apply the migrations to the database. This will apply any migration that
* has not been applied to the database yet. It does this in a
* chronological order based on the IDs of the migrations.
+ *
+ * @param $version The version to migrate to. If you specify the special
+ * cases "up" or "down", it will go one migration "up" or
+ * "down". If it's a number, if will migrate "up" or "down"
+ * to that specific version.
*/
- protected function applyMigrations() {
+ protected function applyMigrations($version='') {
// Get the list of applied and possible migrations
$applied = $this->getAppliedMigrations();
$possible = $this->getPossibleMigrations();
+ // Check what needs to happen
+ if ($version == 'down') {
+
+ // Check if there are any applied migrations
+ if (sizeof($applied) == 0) {
+ throw new CDbMigrationEngineException(
+ 'No migrations are applied to the database yet.'
+ );
+ }
+
+ // Get the last applied migration
+ $lastMigration = array_pop($applied);
+
+ // Get the details
+ $migration = $this->createMigration(
+ $possible[$lastMigration]['class'],
+ $possible[$lastMigration]['file']
+ );
+
+ // Apply the migration
+ $this->applyMigration($migration, 'down');
+
+ // Return
+ return;
+
+ }
+
// Loop over all possible migrations
- foreach ($possible as $migrationFile => $migration) {
+ foreach ($possible as $migrationId => $migrationSpecs) {
// Include the migration file
- require_once($migrationFile);
+ require_once($migrationSpecs['file']);
// Create the migration instance
- $migration = new $migration($this->adapter);
+ $migration = $this->createMigration(
+ $migrationSpecs['class'], $migrationSpecs['file']
+ );
// Check if it's already applied to the database
if (!in_array($migration->getId(), $applied)) {
// Apply the migration to the database
$this->applyMigration($migration);
} else {
// Skip the already applied migration
echo(
'Skipping applied migration: ' . get_class($migration) . PHP_EOL
);
}
-
+
}
+
+ }
+
+ /**
+ * This function creates a migration instance.
+ *
+ * @param $id The ID of the migration.
+ * @param $file The file in which the migration exists
+ */
+ protected function createMigration($class, $file) {
+
+ // Include the migration file
+ require_once($file);
+
+ // Create the migration instance
+ return new $class($this->adapter);
}
/**
* Apply a specific migration based on the migration name.
*
* @param $migration The name of the migration to apply.
* @param $direction The direction in which the migration needs to be
* applied. Needs to be "up" or "down".
*/
protected function applyMigration($migration, $direction='up') {
// Apply the migration
- echo('Applying migration: ' . get_class($migration) . PHP_EOL);
+ if ($direction == 'up') {
+ echo('Applying migration: ' . get_class($migration) . PHP_EOL);
+ } else {
+ echo('Removing migration: ' . get_class($migration) . PHP_EOL);
+ }
// Perform the migration function transactional
$migration->performTransactional($direction);
// Commit the migration
- echo(
- 'Marking migration as applied: ' . get_class($migration) . PHP_EOL
- );
- $cmd = Yii::app()->db->commandBuilder->createInsertCommand(
- self::SCHEMA_TABLE,
- array(self::SCHEMA_FIELD => $migration->getId())
- )->execute();
+ if ($direction == 'up') {
+ echo(
+ 'Marking migration as applied: ' . get_class($migration) . PHP_EOL
+ );
+ $cmd = Yii::app()->db->commandBuilder->createInsertCommand(
+ self::SCHEMA_TABLE,
+ array(self::SCHEMA_FIELD => $migration->getId())
+ )->execute();
+ } else {
+ echo(
+ 'Marking migration as removed: ' . get_class($migration) . PHP_EOL
+ );
+ $sql = 'DELETE FROM '
+ . $this->adapter->db->quoteTableName(self::SCHEMA_TABLE)
+ . ' WHERE '
+ . $this->adapter->db->quoteColumnName(self::SCHEMA_FIELD)
+ . ' = '
+ . $this->adapter->db->quoteValue($migration->getId());
+ $this->adapter->execute($sql);
+ }
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | 12cfc75c96bbd3eb3dfebb2e1df56d6dc8582949 | Added more checks to see if a migration file actually contains a migration. | diff --git a/CDbMigrationEngine.php b/CDbMigrationEngine.php
index 6dac97a..1ff2420 100644
--- a/CDbMigrationEngine.php
+++ b/CDbMigrationEngine.php
@@ -1,301 +1,325 @@
<?php
/**
* CDbMigrationEngine class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the adapters we are going to use for the migrations.
*/
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* A database migration engine exception
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngineException extends Exception {}
/**
* The CDbMigrationEngine class is the actual engine that can do all the
* migrations related functionality.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngine {
/**
* The migration adapter to use
*/
private $adapter;
/**
* The name of the table that contains the schema information.
*/
const SCHEMA_TABLE = 'schema_version';
/**
* The field in the schema_version table that contains the id of the
* installed migrations.
*/
const SCHEMA_FIELD = 'id';
/**
* The extension used for the migration files.
*/
const SCHEMA_EXT = 'php';
/**
* The directory in which the migrations can be found.
*/
const MIGRATIONS_DIR = 'migrations';
/**
* Run the database migration engine, passing on the command-line
* arguments.
*
* @param $args The command line parameters.
*/
public function run($args) {
// Catch errors
try {
// Initialize the engine
$this->init();
// Check if we need to create a migration
if (isset($args[0]) && ($args[0] == 'create')) {
$this->create($args[0]);
} else {
$this->applyMigrations();
}
} catch (Exception $e) {
echo('ERROR: ' . $e->getMessage() . PHP_EOL);
}
}
/**
* Initialize the database migration engine. Several things happen during
* this initialization:
* - The system checks if a database connection was configured.
* - The system checks if the database driver supports migrations.
* - If the schema_version table doesn't exist yet, it gets created.
*/
protected function init() {
// Check if a database connection was configured
try {
Yii::app()->db;
} catch (Exception $e) {
throw new CDbMigrationEngineException(
'Database configuration is missing in your configuration file.'
);
}
// Load the migration adapter
switch (Yii::app()->db->driverName) {
case 'mysql':
$this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
break;
case 'sqlite':
$this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
break;
default:
throw new CDbMigrationEngineException(
'Database of type ' . Yii::app()->db->driverName
. ' does not support migrations (yet).'
);
}
// Check if the schema version table exists
if (Yii::app()->db->schema->getTable('schema_version') == null) {
// Create the table
echo('Creating initial schema_version table' . PHP_EOL);
// Use the adapter to create the table
$this->adapter->createTable(
self::SCHEMA_TABLE,
array(
array(self::SCHEMA_FIELD, 'string'),
)
);
// Create an index on the column
$this->adapter->addIndex(
self::SCHEMA_TABLE,
'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
array(self::SCHEMA_FIELD),
true
);
}
}
/**
* Get the list of migrations that are applied to the database. This
* basically reads out the schema_version table from the database.
*
* @returns An array with the IDs of the already applied database
* migrations as found in the database.
*/
protected function getAppliedMigrations() {
// Get the field and table name
$field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
$table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
// Construct the SQL statement
$sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
// Get the list
return Yii::app()->db->createCommand($sql)->queryColumn(
self::SCHEMA_FIELD
);
}
/**
* Get the list of possible migrations from the file system. This will read
* the contents of the migrations directory and the migrations directory
* inside each installed and enabled module.
*
* @returns An array with the IDs of the possible database migrations as
* found in the database.
*/
protected function getPossibleMigrations() {
// Get the migrations for the default application
$migrations = $this->getPossibleMigrationsForModule();
// Get the migrations for each installed and enabled module
foreach (Yii::app()->modules as $module => $moduleData) {
$migrations = array_merge(
$migrations, $this->getPossibleMigrationsForModule($module)
);
}
// Sort them based on the file path (which is the key in the array)
ksort($migrations);
// Returh the list of migrations
return $migrations;
}
/**
* A helper function to get the list of migrations for a specific module.
* If no module is specified, it will return the list of modules from the
* "protected/migrations" directory.
*
* @param $module The name of the module to get the migrations for.
- *
- * @todo Add more checking to see if a file is actually a migration.
*/
protected function getPossibleMigrationsForModule($module=null) {
// Get the path to the migrations dir
$path = Yii::app()->basePath;
if (!empty($module)) {
$path .= '/modules/' . trim($module, '/');
}
$path .= '/' . self::MIGRATIONS_DIR;
// Start with an empty list
$migrations = array();
// Check if the migrations directory actually exists
if (is_dir($path)) {
// Construct the list of migrations
$migrationFiles = CFileHelper::findFiles(
$path,
array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
);
foreach ($migrationFiles as $migration) {
+
+ // Check if it's valid
+ if (substr(basename($migration), 0, 1) != 'm') {
+ continue;
+ }
+
+ // Include the file
+ include($migration);
+
+ // Get the class name
+ $className = basename($migration, '.' . self::SCHEMA_EXT);
+
+ // Check if the class exists
+ if (!class_exists($className)) {
+ continue;
+ }
+
+ // Check if the class is a valid migration
+ $migrationReflection = new ReflectionClass($className);
+ $baseReflection = new ReflectionClass('CDbMigration');
+ if (!$migrationReflection->isSubclassOf($baseReflection)) {
+ continue;
+ }
+
+ // Add it the list
$migrations[$migration] = basename(
$migration, '.' . self::SCHEMA_EXT
);
+
}
}
// Return the list
return $migrations;
}
/**
* Apply the migrations to the database. This will apply any migration that
* has not been applied to the database yet. It does this in a
* chronological order based on the IDs of the migrations.
*/
protected function applyMigrations() {
// Get the list of applied and possible migrations
$applied = $this->getAppliedMigrations();
$possible = $this->getPossibleMigrations();
// Loop over all possible migrations
foreach ($possible as $migrationFile => $migration) {
// Include the migration file
- require($migrationFile);
+ require_once($migrationFile);
// Create the migration instance
$migration = new $migration($this->adapter);
// Check if it's already applied to the database
if (!in_array($migration->getId(), $applied)) {
// Apply the migration to the database
$this->applyMigration($migration);
} else {
// Skip the already applied migration
echo(
'Skipping applied migration: ' . get_class($migration) . PHP_EOL
);
}
}
}
/**
* Apply a specific migration based on the migration name.
*
* @param $migration The name of the migration to apply.
* @param $direction The direction in which the migration needs to be
* applied. Needs to be "up" or "down".
*/
protected function applyMigration($migration, $direction='up') {
// Apply the migration
echo('Applying migration: ' . get_class($migration) . PHP_EOL);
// Perform the migration function transactional
$migration->performTransactional($direction);
// Commit the migration
echo(
'Marking migration as applied: ' . get_class($migration) . PHP_EOL
);
$cmd = Yii::app()->db->commandBuilder->createInsertCommand(
self::SCHEMA_TABLE,
array(self::SCHEMA_FIELD => $migration->getId())
)->execute();
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | 2ab1964d92258fc753776e8a175404ed030264c8 | Implemented the columnInfo function for MySQL. | diff --git a/CDbMigration.php b/CDbMigration.php
index a83c092..9c8d5be 100644
--- a/CDbMigration.php
+++ b/CDbMigration.php
@@ -1,268 +1,268 @@
<?php
/**
* CDbMigration class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* @package extensions.yii-dbmigrations
*/
class CDbMigrationException extends Exception {}
/**
* This class abstracts a database migration. The main functions that you will
* need to implement for creating a migration are the up and down methods.
*
* The up method will be applied when the migration gets installed into the
* system, the down method when the migration gets removed from the system.
*
* @package extensions.yii-dbmigrations
*/
abstract class CDbMigration {
/**
* The CDbMigrationAdapater that is used to perform the actual migrations
* on the database.
*/
- private $adapter;
+ public $adapter;
/**
* Class constructor for the CDbMigration class.
*
* @param $adapter The CDbMigrationAdapater that is used to perform the
* actual migrations on the database.
*/
public function __construct(CDbMigrationAdapter $adapter) {
$this->adapter = $adapter;
}
/**
* This method will execute the given class method inside a database
* transaction. It will raise an exception if the class method doesn't
* exist.
*
* For the transaction handling, we rely on the Yii DB functionality. If
* the database doesn't support transactions, the SQL statements will be
* executed one after another without using transactions.
*
* If the command succeeds, the transaction will get committed, if not, a
* rollback of the transaction will happen.
*
* @param $command The name of the class method to execute.
*/
public function performTransactional($command) {
// Check if the class method exists
if (!method_exists($this, $command)) {
throw new CDbMigrationException(
'Invalid migration command: ' . $command
);
}
// Run the command inside a transaction
$transaction = $this->adapter->db->beginTransaction();
try {
$this->$command();
$transaction->commit();
} catch (Exception $e) {
$transaction->rollback();
}
}
/**
* The up class method contains all the statements that will be executed
* when the migration is applied to the database.
*/
public function up() {
}
/**
* The up class method contains all the statements that will be executed
* when the migration is removed the database.
*/
public function down() {
}
/**
* This function returns the ID of the migration.
*
* Given the following migration class name:
*
* <code>m20090611153243_CreateTables</code>
*
* The id for this migration will be:
*
* <code>20090611153243</code>
*
* @returns The ID of the migration.
*/
public function getId() {
$id = split('_', get_class($this));
return substr($id[0], 1);
}
/**
* This function returns the name of the migration.
*
* Given the following migration class name:
*
* <code>m20090611153243_CreateTables</code>
*
* The name for this migration will be:
*
* <code>CreateTables</code>
*
* @returns The name of the migration.
*/
public function getName() {
$name = split('_', get_class($this));
return join('_', array_slice($name, 1, sizeof($name) - 1));
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that doesn't return any data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The number of affected rows.
*/
protected function execute($query, $params=array()) {
return $this->adapter->execute($query, $params);
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that returns data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The rows returned from the database.
*/
protected function query($query, $params=array()) {
return $this->adapter->query($query, $params);
}
/**
* The createTable function allows you to create a new table in the
* database.
*
* @param $name The name of the table to create.
* @param $column The column definition for the database table
* @param $options The extra options to pass to the database creation.
*/
protected function createTable($name, $columns=array(), $options=null) {
echo(' >> Creating table: ' . $name . PHP_EOL);
return $this->adapter->createTable($name, $columns, $options);
}
/**
* Rename a table.
*
* @param $name The name of the table to rename.
* @param $new_name The new name for the table.
*/
protected function renameTable($name, $new_name) {
echo(' >> Renaming table: ' . $name . ' to: ' . $new_name . PHP_EOL);
return $this->adapter->renameTable($name, $new_name);
}
/**
* Remove a table from the database.
*
* @param $name The name of the table to remove.
*/
protected function removeTable($name) {
echo(' >> Removing table: ' . $name . PHP_EOL);
return $this->adapter->removeTable($name);
}
/**
* Add a database column to an existing table.
*
* @param $table The table to add the column in.
* @param $column The name of the column to add.
* @param $type The data type for the new column.
* @param $options The extra options to pass to the column.
*/
protected function addColumn($table, $column, $type, $options=null) {
echo(' >> Adding column ' . $column . ' to table: ' . $table . PHP_EOL);
return $this->adapter->addColumn($table, $column, $type, $options);
}
/**
* Rename a database column in an existing table.
*
* @param $table The table to rename the column from.
* @param $name The current name of the column.
* @param $new_name The new name of the column.
*/
protected function renameColumn($table, $name, $new_name) {
echo(
' >> Renaming column ' . $name . ' to: ' . $new_name
. ' in table: ' . $table . PHP_EOL
);
return $this->adapter->renameColumn($table, $name, $new_name);
}
/**
* Change a database column in an existing table.
*
* @param $table The name of the table to change the column from.
* @param $column The name of the column to change.
* @param $type The new data type for the column.
* @param $options The extra options to pass to the column.
*/
protected function changeColumn($table, $column, $type, $options=null) {
echo(
' >> Chaning column ' . $name . ' to: ' . $type
. ' in table: ' . $table . PHP_EOL
);
return $this->adapter->changeColumn($table, $column, $type, $options);
}
/**
* Remove a table column from the database.
*
* @param $table The name of the table to remove the column from.
* @param $column The name of the table column to remove.
*/
protected function removeColumn($table, $column) {
echo(
' >> Removing column ' . $column . ' from table: ' . $table . PHP_EOL
);
return $this->adapter->removeColumn($table, $column);
}
/**
* Add an index to the database or a specific table.
*
* @param $table The name of the table to add the index to.
* @param $name The name of the index to create.
* @param $columns The name of the fields to include in the index.
* @param $unique If set to true, a unique index will be created.
*/
public function addIndex($table, $name, $columns, $unique=false) {
echo(' >> Adding index ' . $name . ' to table: ' . $table . PHP_EOL);
return $this->adapter->addIndex($table, $name, $columns, $unique);
}
/**
* Remove a table index from the database.
*
* @param $table The name of the table to remove the index from.
* @param $column The name of the table index to remove.
*/
protected function removeIndex($table, $name) {
echo(' >> Removing index ' . $name . ' from table: ' . $table . PHP_EOL);
return $this->adapter->removeIndex($table, $name);
}
}
\ No newline at end of file
diff --git a/CDbMigrationAdapter.php b/CDbMigrationAdapter.php
index a1249fb..1a0b057 100644
--- a/CDbMigrationAdapter.php
+++ b/CDbMigrationAdapter.php
@@ -1,226 +1,224 @@
<?php
/**
* CDbMigrationAdapter class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* @package extensions.yii-dbmigrations
*/
abstract class CDbMigrationAdapter {
/**
* The database connection
*/
public $db;
/**
* Class Constructor
*/
public function __construct(CDbConnection $db) {
$this->db = $db;
}
/**
* Convert a type to a native database type
*/
protected function convertToNativeType($theType) {
if (isset($this->nativeDatabaseTypes[$theType])) {
return $this->nativeDatabaseTypes[$theType];
} else {
return $theType;
}
}
/**
* Convert the field information to native types
*/
protected function convertFields($fields) {
$result = array();
foreach ($fields as $field) {
if (is_array($field)) {
if (isset($field[0])) {
$field[0] = $this->db->quoteColumnName($field[0]);
}
if (isset($field[1])) {
$field[1] = $this->convertToNativeType($field[1]);
}
$result[] = join(' ', $field);
} else {
$result[] = $this->db->quoteColumnName($field);
}
}
return join(', ', $result);
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that doesn't return any data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The number of affected rows.
*/
public function execute($query, $params=array()) {
return $this->db->createCommand($query)->execute();
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that returns data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The rows returned from the database.
*/
public function query($query, $params=array()) {
return $this->db->createCommand($query)->queryAll();
}
/**
* Retrieve the type information from a database column.
*
- * @todo Still to be implemented.
+ * @returns The current data type of the column.
*/
public function columnInfo($table, $name) {
}
/**
* The createTable function allows you to create a new table in the
* database.
*
* @param $name The name of the table to create.
* @param $column The column definition for the database table
* @param $options The extra options to pass to the database creation.
*/
public function createTable($name, $columns=array(), $options=null) {
$sql = 'CREATE TABLE ' . $this->db->quoteTableName($name) . ' ('
. $this->convertFields($columns)
. ') ' . $options;
return $this->execute($sql);
}
/**
* Rename a table.
*
* @param $name The name of the table to rename.
* @param $new_name The new name for the table.
*/
public function renameTable($name, $new_name) {
$sql = 'RENAME TABLE ' . $this->db->quoteTableName($name) . ' TO '
. $this->db->quoteTableName($new_name);
return $this->execute($sql);
}
/**
* Remove a table from the database.
*
* @param $name The name of the table to remove.
*/
public function removeTable($name) {
$sql = 'DROP TABLE ' . $this->db->quoteTableName($name);
return $this->execute($sql);
}
/**
* Add a database column to an existing table.
*
* @param $table The table to add the column in.
* @param $column The name of the column to add.
* @param $type The data type for the new column.
* @param $options The extra options to pass to the column.
*/
public function addColumn($table, $column, $type, $options=null) {
$type = $this->convertToNativeType($type);
if (empty($options)) {
$options = 'NOT NULL';
}
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD '
. $this->db->quoteColumnName($column) . ' ' . $type . ' '
. $options;
return $this->execute($sql);
}
/**
* Rename a database column in an existing table.
*
* @param $table The table to rename the column from.
* @param $name The current name of the column.
* @param $new_name The new name of the column.
- *
- * @todo We need to retain the column definition
*/
public function renameColumn($table, $name, $new_name) {
$type = $this->columnInfo($table, $name);
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
. $this->db->quoteColumnName($name) . ' '
. $this->db->quoteColumnName($new_name) . ' ' . $type;
return $this->execute($sql);
}
/**
* Change a database column in an existing table.
*
* @param $table The name of the table to change the column from.
* @param $column The name of the column to change.
* @param $type The new data type for the column.
* @param $options The extra options to pass to the column.
*/
public function changeColumn($table, $column, $type, $options=null) {
$type = $this->convertToNativeType($type);
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
. $this->db->quoteColumnName($column) . ' '
. $this->db->quoteColumnName($column) . ' ' . $type . ' '
. $options;
return $this->execute($sql);
}
/**
* Remove a table column from the database.
*
* @param $table The name of the table to remove the column from.
* @param $column The name of the table column to remove.
*/
public function removeColumn($table, $column) {
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' DROP '
. $this->db->quoteColumnName($column);
return $this->execute($sql);
}
/**
* Add an index to the database or a specific table.
*
* @param $table The name of the table to add the index to.
* @param $name The name of the index to create.
* @param $columns The name of the fields to include in the index.
* @param $unique If set to true, a unique index will be created.
*/
public function addIndex($table, $name, $columns, $unique=false) {
$sql = 'CREATE ';
$sql .= ($unique) ? 'UNIQUE ' : '';
$sql .= 'INDEX ' . $this->db->quoteColumnName($name) . ' ON '
. $this->db->quoteTableName($table) . ' ('
. $this->convertFields($columns)
. ')';
return $this->execute($sql);
}
/**
* Remove a table index from the database.
*
* @param $table The name of the table to remove the index from.
* @param $column The name of the table index to remove.
*/
public function removeIndex($table, $name) {
$sql = 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON '
. $this->db->quoteTableName($table);
return $this->execute($sql);
}
}
diff --git a/adapters/CDbMigrationAdapterMysql.php b/adapters/CDbMigrationAdapterMysql.php
index ab08f55..b02e90f 100644
--- a/adapters/CDbMigrationAdapterMysql.php
+++ b/adapters/CDbMigrationAdapterMysql.php
@@ -1,36 +1,74 @@
<?php
/**
* CDbMigrationAdapterMysql class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
+ * The SQLite specific version of the database migration adapter.
+ *
* @package extensions.yii-dbmigrations
*/
class CDbMigrationAdapterMysql extends CDbMigrationAdapter {
/**
* The mapping of the database type definitions to the native database
* types of the database backend.
*/
protected $nativeDatabaseTypes = array(
'primary_key' => 'int(11) DEFAULT NULL auto_increment PRIMARY KEY',
'string' => 'varchar(255)',
'text' => 'text',
'integer' => 'int(4)',
'float' => 'float',
'decimal' => 'decimal',
'datetime' => 'datetime',
'timestamp' => 'datetime',
'time' => 'time',
'date' => 'date',
'binary' => 'blob',
'boolean' => 'tinyint(1)',
'bool' => 'tinyint(1)',
);
+ /**
+ * Retrieve the type information from a database column.
+ *
+ * @returns The current data type of the column.
+ */
+ public function columnInfo($table, $name) {
+
+ // Get the column info from the database
+ $sql = 'SHOW COLUMNS FROM ' . $this->db->quoteTableName($table)
+ . ' LIKE ' . $this->db->quoteValue($name);
+ $columnInfo = $this->db->createCommand($sql)->queryRow();
+
+ // Check if we have column info
+ if ($columnInfo === false) {
+ throw new CDbMigrationException(
+ 'Column: ' . $name . ' not found in table: ' . $table
+ );
+ }
+
+ // Construct the column type as text
+ $type = $columnInfo['Type'];
+ if ($columnInfo['Null'] !== 'YES') {
+ $type .= ' NOT NULL';
+ }
+ if (!empty($columnInfo['Default'])) {
+ $type .= ' DEFAULT ' . $this->db->quoteValue($columnInfo['Default']);
+ }
+ if (!empty($columnInfo['Extra'])) {
+ $type .= ' ' . $columnInfo['Extra'];
+ }
+
+ // Return the column type
+ return $type;
+
+ }
+
}
diff --git a/adapters/CDbMigrationAdapterSqlite.php b/adapters/CDbMigrationAdapterSqlite.php
index f1fb9b1..42b3dab 100644
--- a/adapters/CDbMigrationAdapterSqlite.php
+++ b/adapters/CDbMigrationAdapterSqlite.php
@@ -1,87 +1,100 @@
<?php
/**
* CDbMigrationAdapterSqlite class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
+ * The SQLite specific version of the database migration adapter.
+ *
* @package extensions.yii-dbmigrations
*/
class CDbMigrationAdapterSqlite extends CDbMigrationAdapter {
/**
* The mapping of the database type definitions to the native database
* types of the database backend.
*/
protected $nativeDatabaseTypes = array(
'primary_key' => 'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL',
'string' => 'varchar(255)',
'text' => 'text',
'integer' => 'integer',
'float' => 'float',
'decimal' => 'decimal',
'datetime' => 'datetime',
'timestamp' => 'datetime',
'time' => 'time',
'date' => 'date',
'binary' => 'blob',
'boolean' => 'tinyint(1)',
'bool' => 'tinyint(1)',
);
+ /**
+ * Retrieve the type information from a database column.
+ *
+ * @returns The current data type of the column.
+ */
+ public function columnInfo($table, $name) {
+ throw new CDbMigrationException(
+ 'columnInfo is not supported for SQLite'
+ );
+ }
+
/**
* Rename a table.
*
* @param $name The name of the table to rename.
* @param $new_name The new name for the table.
*/
public function renameTable($name, $new_name) {
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($name) . ' RENAME TO '
. $this->db->quoteTableName($new_name);
return $this->execute($sql);
}
/**
* Rename a database column in an existing table.
*
* @param $table The table to rename the column from.
* @param $name The current name of the column.
* @param $new_name The new name of the column.
*/
public function renameColumn($table, $name, $new_name) {
throw new CDbMigrationException(
'renameColumn is not supported for SQLite'
);
}
/**
* Change a database column in an existing table.
*
* @param $table The name of the table to change the column from.
* @param $column The name of the column to change.
* @param $type The new data type for the column.
* @param $options The extra options to pass to the column.
*/
public function changeColumn($table, $column, $type, $options=null) {
throw new CDbMigrationException(
'changeColumn is not supported for SQLite'
);
}
/**
* Remove a table column from the database.
*
* @param $table The name of the table to remove the column from.
* @param $column The name of the table column to remove.
*/
public function removeColumn($table, $column) {
throw new CDbMigrationException(
'removeColumn is not supported for SQLite'
);
}
}
|
elchingon/yii-dbmigrations | 26d07c68c3dfcbb191439b403035d69bf8816ff2 | Added all the docstrings. | diff --git a/CDbMigration.php b/CDbMigration.php
index f726fee..a83c092 100644
--- a/CDbMigration.php
+++ b/CDbMigration.php
@@ -1,247 +1,268 @@
<?php
/**
* CDbMigration class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* @package extensions.yii-dbmigrations
*/
class CDbMigrationException extends Exception {}
/**
* This class abstracts a database migration. The main functions that you will
* need to implement for creating a migration are the up and down methods.
*
* The up method will be applied when the migration gets installed into the
* system, the down method when the migration gets removed from the system.
*
* @package extensions.yii-dbmigrations
*/
abstract class CDbMigration {
/**
* The CDbMigrationAdapater that is used to perform the actual migrations
* on the database.
*/
private $adapter;
/**
* Class constructor for the CDbMigration class.
*
* @param $adapter The CDbMigrationAdapater that is used to perform the
* actual migrations on the database.
*/
public function __construct(CDbMigrationAdapter $adapter) {
$this->adapter = $adapter;
}
/**
* This method will execute the given class method inside a database
* transaction. It will raise an exception if the class method doesn't
* exist.
*
* For the transaction handling, we rely on the Yii DB functionality. If
* the database doesn't support transactions, the SQL statements will be
* executed one after another without using transactions.
*
* If the command succeeds, the transaction will get committed, if not, a
* rollback of the transaction will happen.
*
* @param $command The name of the class method to execute.
*/
public function performTransactional($command) {
// Check if the class method exists
if (!method_exists($this, $command)) {
throw new CDbMigrationException(
'Invalid migration command: ' . $command
);
}
// Run the command inside a transaction
$transaction = $this->adapter->db->beginTransaction();
try {
$this->$command();
$transaction->commit();
} catch (Exception $e) {
$transaction->rollback();
}
}
/**
* The up class method contains all the statements that will be executed
* when the migration is applied to the database.
*/
public function up() {
}
/**
* The up class method contains all the statements that will be executed
* when the migration is removed the database.
*/
public function down() {
}
/**
* This function returns the ID of the migration.
*
* Given the following migration class name:
*
* <code>m20090611153243_CreateTables</code>
*
* The id for this migration will be:
*
* <code>20090611153243</code>
*
* @returns The ID of the migration.
*/
public function getId() {
$id = split('_', get_class($this));
return substr($id[0], 1);
}
/**
* This function returns the name of the migration.
*
* Given the following migration class name:
*
* <code>m20090611153243_CreateTables</code>
*
* The name for this migration will be:
*
* <code>CreateTables</code>
*
* @returns The name of the migration.
*/
public function getName() {
$name = split('_', get_class($this));
return join('_', array_slice($name, 1, sizeof($name) - 1));
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that doesn't return any data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The number of affected rows.
*/
protected function execute($query, $params=array()) {
return $this->adapter->execute($query, $params);
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that returns data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The rows returned from the database.
*/
protected function query($query, $params=array()) {
return $this->adapter->query($query, $params);
}
/**
* The createTable function allows you to create a new table in the
* database.
*
* @param $name The name of the table to create.
* @param $column The column definition for the database table
* @param $options The extra options to pass to the database creation.
*/
protected function createTable($name, $columns=array(), $options=null) {
echo(' >> Creating table: ' . $name . PHP_EOL);
return $this->adapter->createTable($name, $columns, $options);
}
/**
* Rename a table.
*
* @param $name The name of the table to rename.
* @param $new_name The new name for the table.
*/
protected function renameTable($name, $new_name) {
echo(' >> Renaming table: ' . $name . ' to: ' . $new_name . PHP_EOL);
return $this->adapter->renameTable($name, $new_name);
}
/**
* Remove a table from the database.
*
* @param $name The name of the table to remove.
*/
protected function removeTable($name) {
echo(' >> Removing table: ' . $name . PHP_EOL);
return $this->adapter->removeTable($name);
}
- // Add a database column
+ /**
+ * Add a database column to an existing table.
+ *
+ * @param $table The table to add the column in.
+ * @param $column The name of the column to add.
+ * @param $type The data type for the new column.
+ * @param $options The extra options to pass to the column.
+ */
protected function addColumn($table, $column, $type, $options=null) {
echo(' >> Adding column ' . $column . ' to table: ' . $table . PHP_EOL);
return $this->adapter->addColumn($table, $column, $type, $options);
}
/**
- * Rename a database column
+ * Rename a database column in an existing table.
+ *
+ * @param $table The table to rename the column from.
+ * @param $name The current name of the column.
+ * @param $new_name The new name of the column.
*/
protected function renameColumn($table, $name, $new_name) {
echo(
' >> Renaming column ' . $name . ' to: ' . $new_name
. ' in table: ' . $table . PHP_EOL
);
return $this->adapter->renameColumn($table, $name, $new_name);
}
/**
- * Change a database column
+ * Change a database column in an existing table.
+ *
+ * @param $table The name of the table to change the column from.
+ * @param $column The name of the column to change.
+ * @param $type The new data type for the column.
+ * @param $options The extra options to pass to the column.
*/
protected function changeColumn($table, $column, $type, $options=null) {
echo(
' >> Chaning column ' . $name . ' to: ' . $type
. ' in table: ' . $table . PHP_EOL
);
return $this->adapter->changeColumn($table, $column, $type, $options);
}
/**
* Remove a table column from the database.
*
* @param $table The name of the table to remove the column from.
* @param $column The name of the table column to remove.
*/
protected function removeColumn($table, $column) {
echo(
' >> Removing column ' . $column . ' from table: ' . $table . PHP_EOL
);
return $this->adapter->removeColumn($table, $column);
}
/**
- * Add an index
+ * Add an index to the database or a specific table.
+ *
+ * @param $table The name of the table to add the index to.
+ * @param $name The name of the index to create.
+ * @param $columns The name of the fields to include in the index.
+ * @param $unique If set to true, a unique index will be created.
*/
public function addIndex($table, $name, $columns, $unique=false) {
echo(' >> Adding index ' . $name . ' to table: ' . $table . PHP_EOL);
return $this->adapter->addIndex($table, $name, $columns, $unique);
}
/**
* Remove a table index from the database.
*
* @param $table The name of the table to remove the index from.
* @param $column The name of the table index to remove.
*/
protected function removeIndex($table, $name) {
echo(' >> Removing index ' . $name . ' from table: ' . $table . PHP_EOL);
return $this->adapter->removeIndex($table, $name);
}
}
\ No newline at end of file
diff --git a/CDbMigrationAdapter.php b/CDbMigrationAdapter.php
index af0b776..a1249fb 100644
--- a/CDbMigrationAdapter.php
+++ b/CDbMigrationAdapter.php
@@ -1,207 +1,226 @@
<?php
/**
* CDbMigrationAdapter class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* @package extensions.yii-dbmigrations
*/
abstract class CDbMigrationAdapter {
/**
* The database connection
*/
public $db;
/**
* Class Constructor
*/
public function __construct(CDbConnection $db) {
$this->db = $db;
}
/**
* Convert a type to a native database type
*/
protected function convertToNativeType($theType) {
if (isset($this->nativeDatabaseTypes[$theType])) {
return $this->nativeDatabaseTypes[$theType];
} else {
return $theType;
}
}
/**
* Convert the field information to native types
*/
protected function convertFields($fields) {
$result = array();
foreach ($fields as $field) {
if (is_array($field)) {
if (isset($field[0])) {
$field[0] = $this->db->quoteColumnName($field[0]);
}
if (isset($field[1])) {
$field[1] = $this->convertToNativeType($field[1]);
}
$result[] = join(' ', $field);
} else {
$result[] = $this->db->quoteColumnName($field);
}
}
return join(', ', $result);
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that doesn't return any data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The number of affected rows.
*/
public function execute($query, $params=array()) {
return $this->db->createCommand($query)->execute();
}
/**
* With the execute function, you can execute a raw SQL query against the
* database. The SQL query should be one that returns data.
*
* @param $query The SQL query to execute.
* @param $params The parameters to pass to the SQL query.
*
* @returns The rows returned from the database.
*/
public function query($query, $params=array()) {
return $this->db->createCommand($query)->queryAll();
}
/**
* Retrieve the type information from a database column.
*
* @todo Still to be implemented.
*/
public function columnInfo($table, $name) {
}
/**
* The createTable function allows you to create a new table in the
* database.
*
* @param $name The name of the table to create.
* @param $column The column definition for the database table
* @param $options The extra options to pass to the database creation.
*/
public function createTable($name, $columns=array(), $options=null) {
$sql = 'CREATE TABLE ' . $this->db->quoteTableName($name) . ' ('
. $this->convertFields($columns)
. ') ' . $options;
return $this->execute($sql);
}
/**
* Rename a table.
*
* @param $name The name of the table to rename.
* @param $new_name The new name for the table.
*/
public function renameTable($name, $new_name) {
$sql = 'RENAME TABLE ' . $this->db->quoteTableName($name) . ' TO '
. $this->db->quoteTableName($new_name);
return $this->execute($sql);
}
/**
* Remove a table from the database.
*
* @param $name The name of the table to remove.
*/
public function removeTable($name) {
$sql = 'DROP TABLE ' . $this->db->quoteTableName($name);
return $this->execute($sql);
}
/**
- * Add a database column
+ * Add a database column to an existing table.
+ *
+ * @param $table The table to add the column in.
+ * @param $column The name of the column to add.
+ * @param $type The data type for the new column.
+ * @param $options The extra options to pass to the column.
*/
public function addColumn($table, $column, $type, $options=null) {
$type = $this->convertToNativeType($type);
if (empty($options)) {
$options = 'NOT NULL';
}
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD '
. $this->db->quoteColumnName($column) . ' ' . $type . ' '
. $options;
return $this->execute($sql);
}
/**
- * Change a database column
+ * Rename a database column in an existing table.
+ *
+ * @param $table The table to rename the column from.
+ * @param $name The current name of the column.
+ * @param $new_name The new name of the column.
+ *
+ * @todo We need to retain the column definition
*/
- public function changeColumn($table, $column, $type, $options=null) {
- $type = $this->convertToNativeType($type);
+ public function renameColumn($table, $name, $new_name) {
+ $type = $this->columnInfo($table, $name);
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
- . $this->db->quoteColumnName($column) . ' '
- . $this->db->quoteColumnName($column) . ' ' . $type . ' '
- . $options;
+ . $this->db->quoteColumnName($name) . ' '
+ . $this->db->quoteColumnName($new_name) . ' ' . $type;
return $this->execute($sql);
}
/**
- * Rename a database column
+ * Change a database column in an existing table.
*
- * @todo We need to retain the column definition
+ * @param $table The name of the table to change the column from.
+ * @param $column The name of the column to change.
+ * @param $type The new data type for the column.
+ * @param $options The extra options to pass to the column.
*/
- public function renameColumn($table, $name, $new_name) {
- $type = $this->columnInfo($table, $name);
+ public function changeColumn($table, $column, $type, $options=null) {
+ $type = $this->convertToNativeType($type);
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
- . $this->db->quoteColumnName($name) . ' '
- . $this->db->quoteColumnName($new_name) . ' ' . $type;
+ . $this->db->quoteColumnName($column) . ' '
+ . $this->db->quoteColumnName($column) . ' ' . $type . ' '
+ . $options;
return $this->execute($sql);
}
/**
* Remove a table column from the database.
*
* @param $table The name of the table to remove the column from.
* @param $column The name of the table column to remove.
*/
public function removeColumn($table, $column) {
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' DROP '
. $this->db->quoteColumnName($column);
return $this->execute($sql);
}
/**
- * Add an index
+ * Add an index to the database or a specific table.
+ *
+ * @param $table The name of the table to add the index to.
+ * @param $name The name of the index to create.
+ * @param $columns The name of the fields to include in the index.
+ * @param $unique If set to true, a unique index will be created.
*/
public function addIndex($table, $name, $columns, $unique=false) {
$sql = 'CREATE ';
$sql .= ($unique) ? 'UNIQUE ' : '';
$sql .= 'INDEX ' . $this->db->quoteColumnName($name) . ' ON '
. $this->db->quoteTableName($table) . ' ('
. $this->convertFields($columns)
. ')';
return $this->execute($sql);
}
/**
* Remove a table index from the database.
*
* @param $table The name of the table to remove the index from.
* @param $column The name of the table index to remove.
*/
public function removeIndex($table, $name) {
$sql = 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON '
. $this->db->quoteTableName($table);
return $this->execute($sql);
}
}
diff --git a/CDbMigrationEngine.php b/CDbMigrationEngine.php
index ceb4ed9..6dac97a 100644
--- a/CDbMigrationEngine.php
+++ b/CDbMigrationEngine.php
@@ -1,260 +1,301 @@
<?php
/**
* CDbMigrationEngine class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the adapters we are going to use for the migrations.
*/
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* A database migration engine exception
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngineException extends Exception {}
/**
* The CDbMigrationEngine class is the actual engine that can do all the
* migrations related functionality.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngine {
/**
* The migration adapter to use
*/
private $adapter;
/**
- * The name of the table and column for the schema information
+ * The name of the table that contains the schema information.
*/
const SCHEMA_TABLE = 'schema_version';
+
+ /**
+ * The field in the schema_version table that contains the id of the
+ * installed migrations.
+ */
const SCHEMA_FIELD = 'id';
+
+ /**
+ * The extension used for the migration files.
+ */
const SCHEMA_EXT = 'php';
+
+ /**
+ * The directory in which the migrations can be found.
+ */
const MIGRATIONS_DIR = 'migrations';
/**
- * Run the specified command
+ * Run the database migration engine, passing on the command-line
+ * arguments.
+ *
+ * @param $args The command line parameters.
*/
public function run($args) {
// Catch errors
try {
// Initialize the engine
$this->init();
// Check if we need to create a migration
if (isset($args[0]) && ($args[0] == 'create')) {
$this->create($args[0]);
} else {
$this->applyMigrations();
}
} catch (Exception $e) {
echo('ERROR: ' . $e->getMessage() . PHP_EOL);
}
}
/**
- * Initialize the schema version table
+ * Initialize the database migration engine. Several things happen during
+ * this initialization:
+ * - The system checks if a database connection was configured.
+ * - The system checks if the database driver supports migrations.
+ * - If the schema_version table doesn't exist yet, it gets created.
*/
protected function init() {
// Check if a database connection was configured
try {
Yii::app()->db;
} catch (Exception $e) {
throw new CDbMigrationEngineException(
'Database configuration is missing in your configuration file.'
);
}
// Load the migration adapter
switch (Yii::app()->db->driverName) {
case 'mysql':
$this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
break;
case 'sqlite':
$this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
break;
default:
throw new CDbMigrationEngineException(
'Database of type ' . Yii::app()->db->driverName
. ' does not support migrations (yet).'
);
}
// Check if the schema version table exists
if (Yii::app()->db->schema->getTable('schema_version') == null) {
// Create the table
echo('Creating initial schema_version table' . PHP_EOL);
// Use the adapter to create the table
$this->adapter->createTable(
self::SCHEMA_TABLE,
array(
array(self::SCHEMA_FIELD, 'string'),
)
);
// Create an index on the column
$this->adapter->addIndex(
self::SCHEMA_TABLE,
'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
array(self::SCHEMA_FIELD),
true
);
}
}
/**
- * Get the list of migrations that are applied to the database
+ * Get the list of migrations that are applied to the database. This
+ * basically reads out the schema_version table from the database.
+ *
+ * @returns An array with the IDs of the already applied database
+ * migrations as found in the database.
*/
protected function getAppliedMigrations() {
// Get the field and table name
$field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
$table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
// Construct the SQL statement
$sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
// Get the list
return Yii::app()->db->createCommand($sql)->queryColumn(
self::SCHEMA_FIELD
);
}
/**
- * Get the list of possible migrations
+ * Get the list of possible migrations from the file system. This will read
+ * the contents of the migrations directory and the migrations directory
+ * inside each installed and enabled module.
+ *
+ * @returns An array with the IDs of the possible database migrations as
+ * found in the database.
*/
protected function getPossibleMigrations() {
// Get the migrations for the default application
$migrations = $this->getPossibleMigrationsForModule();
// Get the migrations for each installed and enabled module
foreach (Yii::app()->modules as $module => $moduleData) {
$migrations = array_merge(
$migrations, $this->getPossibleMigrationsForModule($module)
);
}
// Sort them based on the file path (which is the key in the array)
ksort($migrations);
// Returh the list of migrations
return $migrations;
}
/**
- * Get the list of migrations for a specific module
+ * A helper function to get the list of migrations for a specific module.
+ * If no module is specified, it will return the list of modules from the
+ * "protected/migrations" directory.
+ *
+ * @param $module The name of the module to get the migrations for.
+ *
+ * @todo Add more checking to see if a file is actually a migration.
*/
protected function getPossibleMigrationsForModule($module=null) {
// Get the path to the migrations dir
$path = Yii::app()->basePath;
if (!empty($module)) {
$path .= '/modules/' . trim($module, '/');
}
$path .= '/' . self::MIGRATIONS_DIR;
// Start with an empty list
$migrations = array();
// Check if the migrations directory actually exists
if (is_dir($path)) {
// Construct the list of migrations
$migrationFiles = CFileHelper::findFiles(
$path,
array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
);
foreach ($migrationFiles as $migration) {
$migrations[$migration] = basename(
$migration, '.' . self::SCHEMA_EXT
);
}
}
// Return the list
return $migrations;
}
/**
- * Apply the migrations
+ * Apply the migrations to the database. This will apply any migration that
+ * has not been applied to the database yet. It does this in a
+ * chronological order based on the IDs of the migrations.
*/
protected function applyMigrations() {
// Get the list of applied and possible migrations
$applied = $this->getAppliedMigrations();
$possible = $this->getPossibleMigrations();
// Loop over all possible migrations
foreach ($possible as $migrationFile => $migration) {
// Include the migration file
require($migrationFile);
// Create the migration instance
$migration = new $migration($this->adapter);
// Check if it's already applied to the database
if (!in_array($migration->getId(), $applied)) {
// Apply the migration to the database
$this->applyMigration($migration);
} else {
// Skip the already applied migration
echo(
'Skipping applied migration: ' . get_class($migration) . PHP_EOL
);
}
}
}
/**
- * Apply a specific migration
+ * Apply a specific migration based on the migration name.
+ *
+ * @param $migration The name of the migration to apply.
+ * @param $direction The direction in which the migration needs to be
+ * applied. Needs to be "up" or "down".
*/
- protected function applyMigration($migration) {
+ protected function applyMigration($migration, $direction='up') {
// Apply the migration
echo('Applying migration: ' . get_class($migration) . PHP_EOL);
- // Create the migration instance
- $migration->performTransactional('up');
+ // Perform the migration function transactional
+ $migration->performTransactional($direction);
// Commit the migration
echo(
'Marking migration as applied: ' . get_class($migration) . PHP_EOL
);
$cmd = Yii::app()->db->commandBuilder->createInsertCommand(
self::SCHEMA_TABLE,
array(self::SCHEMA_FIELD => $migration->getId())
)->execute();
}
}
\ No newline at end of file
diff --git a/adapters/CDbMigrationAdapterMysql.php b/adapters/CDbMigrationAdapterMysql.php
index 88abbd9..ab08f55 100644
--- a/adapters/CDbMigrationAdapterMysql.php
+++ b/adapters/CDbMigrationAdapterMysql.php
@@ -1,33 +1,36 @@
<?php
/**
* CDbMigrationAdapterMysql class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* @package extensions.yii-dbmigrations
*/
class CDbMigrationAdapterMysql extends CDbMigrationAdapter {
- // Return a map of the native database types
+ /**
+ * The mapping of the database type definitions to the native database
+ * types of the database backend.
+ */
protected $nativeDatabaseTypes = array(
'primary_key' => 'int(11) DEFAULT NULL auto_increment PRIMARY KEY',
'string' => 'varchar(255)',
'text' => 'text',
'integer' => 'int(4)',
'float' => 'float',
'decimal' => 'decimal',
'datetime' => 'datetime',
'timestamp' => 'datetime',
'time' => 'time',
'date' => 'date',
'binary' => 'blob',
'boolean' => 'tinyint(1)',
'bool' => 'tinyint(1)',
);
}
diff --git a/adapters/CDbMigrationAdapterSqlite.php b/adapters/CDbMigrationAdapterSqlite.php
index 0b46fd0..f1fb9b1 100644
--- a/adapters/CDbMigrationAdapterSqlite.php
+++ b/adapters/CDbMigrationAdapterSqlite.php
@@ -1,61 +1,87 @@
<?php
/**
* CDbMigrationAdapterSqlite class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* @package extensions.yii-dbmigrations
*/
class CDbMigrationAdapterSqlite extends CDbMigrationAdapter {
- // Return a map of the native database types
+ /**
+ * The mapping of the database type definitions to the native database
+ * types of the database backend.
+ */
protected $nativeDatabaseTypes = array(
'primary_key' => 'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL',
'string' => 'varchar(255)',
'text' => 'text',
'integer' => 'integer',
'float' => 'float',
'decimal' => 'decimal',
'datetime' => 'datetime',
'timestamp' => 'datetime',
'time' => 'time',
'date' => 'date',
'binary' => 'blob',
'boolean' => 'tinyint(1)',
'bool' => 'tinyint(1)',
);
- // Rename a table
+ /**
+ * Rename a table.
+ *
+ * @param $name The name of the table to rename.
+ * @param $new_name The new name for the table.
+ */
public function renameTable($name, $new_name) {
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($name) . ' RENAME TO '
. $this->db->quoteTableName($new_name);
return $this->execute($sql);
}
- // Change a database column
- public function changeColumn($table, $column, $type, $options=null) {
+ /**
+ * Rename a database column in an existing table.
+ *
+ * @param $table The table to rename the column from.
+ * @param $name The current name of the column.
+ * @param $new_name The new name of the column.
+ */
+ public function renameColumn($table, $name, $new_name) {
throw new CDbMigrationException(
- 'changeColumn is not supported for SQLite'
+ 'renameColumn is not supported for SQLite'
);
}
- // Change a database column
- public function renameColumn($table, $name, $new_name) {
+ /**
+ * Change a database column in an existing table.
+ *
+ * @param $table The name of the table to change the column from.
+ * @param $column The name of the column to change.
+ * @param $type The new data type for the column.
+ * @param $options The extra options to pass to the column.
+ */
+ public function changeColumn($table, $column, $type, $options=null) {
throw new CDbMigrationException(
- 'renameColumn is not supported for SQLite'
+ 'changeColumn is not supported for SQLite'
);
}
- // Remove a column
+ /**
+ * Remove a table column from the database.
+ *
+ * @param $table The name of the table to remove the column from.
+ * @param $column The name of the table column to remove.
+ */
public function removeColumn($table, $column) {
throw new CDbMigrationException(
'removeColumn is not supported for SQLite'
);
}
}
|
elchingon/yii-dbmigrations | 803936997e8be018cd49ec19e1baa15fb6e15f9d | Started adding more docstrings. | diff --git a/CDbMigration.php b/CDbMigration.php
index 8845063..f726fee 100644
--- a/CDbMigration.php
+++ b/CDbMigration.php
@@ -1,143 +1,247 @@
<?php
/**
* CDbMigration class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* @package extensions.yii-dbmigrations
*/
class CDbMigrationException extends Exception {}
/**
+ * This class abstracts a database migration. The main functions that you will
+ * need to implement for creating a migration are the up and down methods.
+ *
+ * The up method will be applied when the migration gets installed into the
+ * system, the down method when the migration gets removed from the system.
+ *
* @package extensions.yii-dbmigrations
*/
abstract class CDbMigration {
- // The adapter to use
+ /**
+ * The CDbMigrationAdapater that is used to perform the actual migrations
+ * on the database.
+ */
private $adapter;
- // Constructor
+ /**
+ * Class constructor for the CDbMigration class.
+ *
+ * @param $adapter The CDbMigrationAdapater that is used to perform the
+ * actual migrations on the database.
+ */
public function __construct(CDbMigrationAdapter $adapter) {
$this->adapter = $adapter;
}
- // Perform a command transactional
+ /**
+ * This method will execute the given class method inside a database
+ * transaction. It will raise an exception if the class method doesn't
+ * exist.
+ *
+ * For the transaction handling, we rely on the Yii DB functionality. If
+ * the database doesn't support transactions, the SQL statements will be
+ * executed one after another without using transactions.
+ *
+ * If the command succeeds, the transaction will get committed, if not, a
+ * rollback of the transaction will happen.
+ *
+ * @param $command The name of the class method to execute.
+ */
public function performTransactional($command) {
- // Check if the command exists
+ // Check if the class method exists
if (!method_exists($this, $command)) {
throw new CDbMigrationException(
'Invalid migration command: ' . $command
);
}
// Run the command inside a transaction
$transaction = $this->adapter->db->beginTransaction();
try {
$this->$command();
$transaction->commit();
} catch (Exception $e) {
$transaction->rollback();
}
-
}
- // Migrate up
+ /**
+ * The up class method contains all the statements that will be executed
+ * when the migration is applied to the database.
+ */
public function up() {
}
- // Migrate down
+ /**
+ * The up class method contains all the statements that will be executed
+ * when the migration is removed the database.
+ */
public function down() {
}
- // Get the id of the migration
+ /**
+ * This function returns the ID of the migration.
+ *
+ * Given the following migration class name:
+ *
+ * <code>m20090611153243_CreateTables</code>
+ *
+ * The id for this migration will be:
+ *
+ * <code>20090611153243</code>
+ *
+ * @returns The ID of the migration.
+ */
public function getId() {
$id = split('_', get_class($this));
return substr($id[0], 1);
}
- // Get the name of the migration
+ /**
+ * This function returns the name of the migration.
+ *
+ * Given the following migration class name:
+ *
+ * <code>m20090611153243_CreateTables</code>
+ *
+ * The name for this migration will be:
+ *
+ * <code>CreateTables</code>
+ *
+ * @returns The name of the migration.
+ */
public function getName() {
$name = split('_', get_class($this));
- return $name[1];
- }
-
- // Execute a raw SQL statement
+ return join('_', array_slice($name, 1, sizeof($name) - 1));
+ }
+
+ /**
+ * With the execute function, you can execute a raw SQL query against the
+ * database. The SQL query should be one that doesn't return any data.
+ *
+ * @param $query The SQL query to execute.
+ * @param $params The parameters to pass to the SQL query.
+ *
+ * @returns The number of affected rows.
+ */
protected function execute($query, $params=array()) {
return $this->adapter->execute($query, $params);
}
- // Execute a raw SQL statement
+ /**
+ * With the execute function, you can execute a raw SQL query against the
+ * database. The SQL query should be one that returns data.
+ *
+ * @param $query The SQL query to execute.
+ * @param $params The parameters to pass to the SQL query.
+ *
+ * @returns The rows returned from the database.
+ */
protected function query($query, $params=array()) {
return $this->adapter->query($query, $params);
}
- // Create a table
+ /**
+ * The createTable function allows you to create a new table in the
+ * database.
+ *
+ * @param $name The name of the table to create.
+ * @param $column The column definition for the database table
+ * @param $options The extra options to pass to the database creation.
+ */
protected function createTable($name, $columns=array(), $options=null) {
echo(' >> Creating table: ' . $name . PHP_EOL);
return $this->adapter->createTable($name, $columns, $options);
}
- // Rename a table
+ /**
+ * Rename a table.
+ *
+ * @param $name The name of the table to rename.
+ * @param $new_name The new name for the table.
+ */
protected function renameTable($name, $new_name) {
echo(' >> Renaming table: ' . $name . ' to: ' . $new_name . PHP_EOL);
return $this->adapter->renameTable($name, $new_name);
}
- // Drop a table
+ /**
+ * Remove a table from the database.
+ *
+ * @param $name The name of the table to remove.
+ */
protected function removeTable($name) {
echo(' >> Removing table: ' . $name . PHP_EOL);
return $this->adapter->removeTable($name);
}
// Add a database column
protected function addColumn($table, $column, $type, $options=null) {
echo(' >> Adding column ' . $column . ' to table: ' . $table . PHP_EOL);
return $this->adapter->addColumn($table, $column, $type, $options);
}
- // Rename a database column
+ /**
+ * Rename a database column
+ */
protected function renameColumn($table, $name, $new_name) {
echo(
' >> Renaming column ' . $name . ' to: ' . $new_name
. ' in table: ' . $table . PHP_EOL
);
return $this->adapter->renameColumn($table, $name, $new_name);
}
- // Change a database column
+ /**
+ * Change a database column
+ */
protected function changeColumn($table, $column, $type, $options=null) {
echo(
' >> Chaning column ' . $name . ' to: ' . $type
. ' in table: ' . $table . PHP_EOL
);
return $this->adapter->changeColumn($table, $column, $type, $options);
}
- // Remove a column
+ /**
+ * Remove a table column from the database.
+ *
+ * @param $table The name of the table to remove the column from.
+ * @param $column The name of the table column to remove.
+ */
protected function removeColumn($table, $column) {
echo(
' >> Removing column ' . $column . ' from table: ' . $table . PHP_EOL
);
return $this->adapter->removeColumn($table, $column);
}
- // Add an index
+ /**
+ * Add an index
+ */
public function addIndex($table, $name, $columns, $unique=false) {
echo(' >> Adding index ' . $name . ' to table: ' . $table . PHP_EOL);
return $this->adapter->addIndex($table, $name, $columns, $unique);
}
- // Remove an index
- protected function removeIndex($table, $column) {
+ /**
+ * Remove a table index from the database.
+ *
+ * @param $table The name of the table to remove the index from.
+ * @param $column The name of the table index to remove.
+ */
+ protected function removeIndex($table, $name) {
echo(' >> Removing index ' . $name . ' from table: ' . $table . PHP_EOL);
- return $this->adapter->removeIndex($table, $column);
+ return $this->adapter->removeIndex($table, $name);
}
}
\ No newline at end of file
diff --git a/CDbMigrationAdapter.php b/CDbMigrationAdapter.php
index 495da37..af0b776 100644
--- a/CDbMigrationAdapter.php
+++ b/CDbMigrationAdapter.php
@@ -1,146 +1,207 @@
<?php
/**
* CDbMigrationAdapter class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* @package extensions.yii-dbmigrations
*/
abstract class CDbMigrationAdapter {
- // The database connection
+ /**
+ * The database connection
+ */
public $db;
- // Constructor
+ /**
+ * Class Constructor
+ */
public function __construct(CDbConnection $db) {
$this->db = $db;
}
- // Convert a type to a native database type
+ /**
+ * Convert a type to a native database type
+ */
protected function convertToNativeType($theType) {
if (isset($this->nativeDatabaseTypes[$theType])) {
return $this->nativeDatabaseTypes[$theType];
} else {
return $theType;
}
}
- // Convert the field information to native types
+ /**
+ * Convert the field information to native types
+ */
protected function convertFields($fields) {
$result = array();
foreach ($fields as $field) {
if (is_array($field)) {
if (isset($field[0])) {
$field[0] = $this->db->quoteColumnName($field[0]);
}
if (isset($field[1])) {
$field[1] = $this->convertToNativeType($field[1]);
}
$result[] = join(' ', $field);
} else {
$result[] = $this->db->quoteColumnName($field);
}
}
return join(', ', $result);
}
- // Execute a raw SQL statement
- // @todo We need to be able to bind parameters
+ /**
+ * With the execute function, you can execute a raw SQL query against the
+ * database. The SQL query should be one that doesn't return any data.
+ *
+ * @param $query The SQL query to execute.
+ * @param $params The parameters to pass to the SQL query.
+ *
+ * @returns The number of affected rows.
+ */
public function execute($query, $params=array()) {
return $this->db->createCommand($query)->execute();
}
- // Execute a raw SQL statement
- // @todo We need to be able to bind parameters
+ /**
+ * With the execute function, you can execute a raw SQL query against the
+ * database. The SQL query should be one that returns data.
+ *
+ * @param $query The SQL query to execute.
+ * @param $params The parameters to pass to the SQL query.
+ *
+ * @returns The rows returned from the database.
+ */
public function query($query, $params=array()) {
return $this->db->createCommand($query)->queryAll();
}
- // Get the column info
- public function columnInfo($name) {
+ /**
+ * Retrieve the type information from a database column.
+ *
+ * @todo Still to be implemented.
+ */
+ public function columnInfo($table, $name) {
}
- // Create a table
+ /**
+ * The createTable function allows you to create a new table in the
+ * database.
+ *
+ * @param $name The name of the table to create.
+ * @param $column The column definition for the database table
+ * @param $options The extra options to pass to the database creation.
+ */
public function createTable($name, $columns=array(), $options=null) {
$sql = 'CREATE TABLE ' . $this->db->quoteTableName($name) . ' ('
. $this->convertFields($columns)
. ') ' . $options;
return $this->execute($sql);
}
- // Rename a table
+ /**
+ * Rename a table.
+ *
+ * @param $name The name of the table to rename.
+ * @param $new_name The new name for the table.
+ */
public function renameTable($name, $new_name) {
$sql = 'RENAME TABLE ' . $this->db->quoteTableName($name) . ' TO '
. $this->db->quoteTableName($new_name);
return $this->execute($sql);
}
- // Drop a table
+ /**
+ * Remove a table from the database.
+ *
+ * @param $name The name of the table to remove.
+ */
public function removeTable($name) {
$sql = 'DROP TABLE ' . $this->db->quoteTableName($name);
return $this->execute($sql);
}
- // Add a database column
+ /**
+ * Add a database column
+ */
public function addColumn($table, $column, $type, $options=null) {
$type = $this->convertToNativeType($type);
if (empty($options)) {
$options = 'NOT NULL';
}
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD '
. $this->db->quoteColumnName($column) . ' ' . $type . ' '
. $options;
return $this->execute($sql);
}
- // Change a database column
+ /**
+ * Change a database column
+ */
public function changeColumn($table, $column, $type, $options=null) {
$type = $this->convertToNativeType($type);
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
. $this->db->quoteColumnName($column) . ' '
. $this->db->quoteColumnName($column) . ' ' . $type . ' '
. $options;
return $this->execute($sql);
}
- // Rename a database column
- // @todo We need to retain the column definition
+ /**
+ * Rename a database column
+ *
+ * @todo We need to retain the column definition
+ */
public function renameColumn($table, $name, $new_name) {
- $type = $this->columnInfo($name);
+ $type = $this->columnInfo($table, $name);
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
. $this->db->quoteColumnName($name) . ' '
. $this->db->quoteColumnName($new_name) . ' ' . $type;
return $this->execute($sql);
}
- // Remove a column
+ /**
+ * Remove a table column from the database.
+ *
+ * @param $table The name of the table to remove the column from.
+ * @param $column The name of the table column to remove.
+ */
public function removeColumn($table, $column) {
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' DROP '
. $this->db->quoteColumnName($column);
return $this->execute($sql);
}
- // Add an index
+ /**
+ * Add an index
+ */
public function addIndex($table, $name, $columns, $unique=false) {
$sql = 'CREATE ';
$sql .= ($unique) ? 'UNIQUE ' : '';
$sql .= 'INDEX ' . $this->db->quoteColumnName($name) . ' ON '
. $this->db->quoteTableName($table) . ' ('
. $this->convertFields($columns)
. ')';
return $this->execute($sql);
}
- // Remove an index
+ /**
+ * Remove a table index from the database.
+ *
+ * @param $table The name of the table to remove the index from.
+ * @param $column The name of the table index to remove.
+ */
public function removeIndex($table, $name) {
$sql = 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON '
. $this->db->quoteTableName($table);
return $this->execute($sql);
}
}
diff --git a/CDbMigrationEngine.php b/CDbMigrationEngine.php
index 139548b..ceb4ed9 100644
--- a/CDbMigrationEngine.php
+++ b/CDbMigrationEngine.php
@@ -1,242 +1,260 @@
<?php
/**
* CDbMigrationEngine class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the adapters we are going to use for the migrations.
*/
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* A database migration engine exception
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngineException extends Exception {}
/**
* The CDbMigrationEngine class is the actual engine that can do all the
* migrations related functionality.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngine {
- // The migration adapter to use
+ /**
+ * The migration adapter to use
+ */
private $adapter;
- // The name of the table and column for the schema information
+ /**
+ * The name of the table and column for the schema information
+ */
const SCHEMA_TABLE = 'schema_version';
const SCHEMA_FIELD = 'id';
const SCHEMA_EXT = 'php';
const MIGRATIONS_DIR = 'migrations';
- // Run the specified command
+ /**
+ * Run the specified command
+ */
public function run($args) {
// Catch errors
try {
// Initialize the engine
$this->init();
// Check if we need to create a migration
if (isset($args[0]) && ($args[0] == 'create')) {
$this->create($args[0]);
} else {
$this->applyMigrations();
}
} catch (Exception $e) {
echo('ERROR: ' . $e->getMessage() . PHP_EOL);
}
}
- // Initialize the schema version table
+ /**
+ * Initialize the schema version table
+ */
protected function init() {
// Check if a database connection was configured
try {
Yii::app()->db;
} catch (Exception $e) {
throw new CDbMigrationEngineException(
'Database configuration is missing in your configuration file.'
);
}
// Load the migration adapter
switch (Yii::app()->db->driverName) {
case 'mysql':
$this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
break;
case 'sqlite':
$this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
break;
default:
throw new CDbMigrationEngineException(
'Database of type ' . Yii::app()->db->driverName
. ' does not support migrations (yet).'
);
}
// Check if the schema version table exists
if (Yii::app()->db->schema->getTable('schema_version') == null) {
// Create the table
echo('Creating initial schema_version table' . PHP_EOL);
// Use the adapter to create the table
$this->adapter->createTable(
self::SCHEMA_TABLE,
array(
array(self::SCHEMA_FIELD, 'string'),
)
);
// Create an index on the column
$this->adapter->addIndex(
self::SCHEMA_TABLE,
'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
array(self::SCHEMA_FIELD),
true
);
}
}
- // Get the list of migrations that are applied to the database
+ /**
+ * Get the list of migrations that are applied to the database
+ */
protected function getAppliedMigrations() {
// Get the field and table name
$field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
$table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
// Construct the SQL statement
$sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
// Get the list
return Yii::app()->db->createCommand($sql)->queryColumn(
self::SCHEMA_FIELD
);
}
- // Get the list of possible migrations
+ /**
+ * Get the list of possible migrations
+ */
protected function getPossibleMigrations() {
// Get the migrations for the default application
$migrations = $this->getPossibleMigrationsForModule();
// Get the migrations for each installed and enabled module
foreach (Yii::app()->modules as $module => $moduleData) {
$migrations = array_merge(
$migrations, $this->getPossibleMigrationsForModule($module)
);
}
// Sort them based on the file path (which is the key in the array)
ksort($migrations);
// Returh the list of migrations
return $migrations;
}
- // Get the list of migrations for a specific module
+ /**
+ * Get the list of migrations for a specific module
+ */
protected function getPossibleMigrationsForModule($module=null) {
// Get the path to the migrations dir
$path = Yii::app()->basePath;
if (!empty($module)) {
$path .= '/modules/' . trim($module, '/');
}
$path .= '/' . self::MIGRATIONS_DIR;
// Start with an empty list
$migrations = array();
// Check if the migrations directory actually exists
if (is_dir($path)) {
// Construct the list of migrations
$migrationFiles = CFileHelper::findFiles(
$path,
array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
);
foreach ($migrationFiles as $migration) {
$migrations[$migration] = basename(
$migration, '.' . self::SCHEMA_EXT
);
}
}
// Return the list
return $migrations;
}
- // Apply the migrations
+ /**
+ * Apply the migrations
+ */
protected function applyMigrations() {
// Get the list of applied and possible migrations
$applied = $this->getAppliedMigrations();
$possible = $this->getPossibleMigrations();
// Loop over all possible migrations
foreach ($possible as $migrationFile => $migration) {
// Include the migration file
require($migrationFile);
// Create the migration instance
$migration = new $migration($this->adapter);
// Check if it's already applied to the database
if (!in_array($migration->getId(), $applied)) {
// Apply the migration to the database
$this->applyMigration($migration);
} else {
// Skip the already applied migration
echo(
'Skipping applied migration: ' . get_class($migration) . PHP_EOL
);
}
}
}
- // Apply a specific migration
+ /**
+ * Apply a specific migration
+ */
protected function applyMigration($migration) {
// Apply the migration
echo('Applying migration: ' . get_class($migration) . PHP_EOL);
// Create the migration instance
$migration->performTransactional('up');
// Commit the migration
echo(
'Marking migration as applied: ' . get_class($migration) . PHP_EOL
);
$cmd = Yii::app()->db->commandBuilder->createInsertCommand(
self::SCHEMA_TABLE,
array(self::SCHEMA_FIELD => $migration->getId())
)->execute();
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | e79ed295af43c268b360f2bd1c9400739c1ca920 | Fixed the links in the readme file. | diff --git a/README.textile b/README.textile
index d66a88d..11408c4 100644
--- a/README.textile
+++ b/README.textile
@@ -1,232 +1,232 @@
h1. Yii DB Migrations
-A database migrations engine for the Yii framework. It comes in the form of an extension which can be dropped into any existing Yii framework application.
+A database migrations engine for the "Yii framework":http://www.yiiframework.com. It comes in the form of an extension which can be dropped into any existing Yii framework application.
It relies on the database abstraction layer of the Yii framework to talk to the database engine.
It's largely inspired on the migrations functionality of the Ruby on Rails framework.
h2. Why bother in the first place?
You might wonder why you need database migrations in the first place. Sure, you could use plain SQL files to apply updates to the database, but they have a big disadvantage: they are database specific.
Imagine you initially create your database using SQLite and later on decide to change to MySQL. When you use plain SQL files, you will need to rewrite them using MySQL's flavor of SQL. Also, you will need to create some tool that knows what has been applied already to the database and what's not applied yet.
Meet database migrations. By defining a higher level interface to creating and maintaining the database schema, you can define it in a database agnostic way.
By using PHP functions to create tables, indexes, fields, ... you can write the schema once and apply it to any database backend supported. The added bonus is that the yii-dbmigrations extension keeps track of which migrations have been applied already and which ones still need to be applied.
h2. Current limitations
Be aware that the current version is still very alpha.
There are only two database engines supported:
* MySQL
* SQLite
In the current version, it's only possible to migrate up, it cannot (yet) remove already installed migrations.
h2. Installing the extension
h3. Putting the files in the right location
Installing the extension is quite easy. Once you downloaded the files from github, you need to put all the files in a folder called "yii-dbmigrations" and put it in the <code>protected/extensions</code> folder from your project.
h3. Configuring the database connection
You need to make sure you configure database access properly in the configuration file of your project. As the console applications in the Yii framework look at the <code>protected/config/console.php</code> file, you need to make sure you configure the <code>db</code> settings under the <code>components</code> key in the configuration array. For MySQL, the configuration will look as follows:
<pre>
'components' => array(
'db'=>array(
'class' => 'CDbConnection',
'connectionString'=>'mysql:host=localhost;dbname=my_db',
'charset' => 'UTF8',
'username'=>'root',
'password'=>'root',
),
),
</pre>
For SQLite, the configuration looks as follows:
<pre>
'components' => array(
'db'=>array(
'connectionString'=>'sqlite:'.dirname(__FILE__).'/../data/my_db.db',
),
),
</pre>
h3. Configuring the command map
To make the <code>yiic</code> tool know about the <code>migrate</code> command, you need to add a <code>commandMap</code> key to the application configuration.
In there, you need to put the following configuration:
<pre>
'commandMap' => array(
'migrate' => array(
'class'=>'application.extensions.yii-dbmigrations.CDbMigrationCommand',
),
),
</pre>
h3. Testing your installation
To test if the installation was succesfull, you can run the yiic command and should see the following output:
<pre>
Yii command runner (based on Yii v1.0.6)
Usage: protected/yiic <command-name> [parameters...]
The following commands are available:
- migrate
- message
- shell
- webapp
To see individual command help, use the following:
protected/yiic help <command-name>
</pre>
It should mention that the <code>migrate</code> command is available.
h2. Creating migrations
h3. Naming conventions
You can create migrations by creating files in the <code>protected/migrations</code> folder or in the <code>migrations</code> folder inside your module. The file names for the migrations should follow a specific naming convention:
<pre>
m20090614213453_MigrationName.php
</pre>
The migration file names always start with the letter m followed by 14 digit timestamp and an underscore. After that, you can give a name to the migration so that you can easily identify the migration.
If your migration is part of a module, it's a good idea to add the name of the module between the migration ID and name so that the name looks as follows:
<pre>
m20090614213453_ModuleName_MigrationName.php
</pre>
This will ensure that there is much less chance for naming conflicts between migrations in different modules.
h3. Implementing the migration
In the migration file, you need to create a class that extends the parent class <code>CDbMigration</code>. The <code>CDbMigration</code> class needs to have the <code>up</code> and <code>down</code> methods as you can see in the following sample migration:
<pre>
class m20090611153243_CreateTables extends CDbMigration {
public function up() {
$this->createTable(
'posts',
array(
array('id', 'primary_key'),
array('title', 'string'),
array('body', 'text'),
)
);
$this->addIndex(
'posts', 'posts_title', array('title')
);
}
public function down() {
$this->removeTable('posts');
}
}
</pre>
h3. Supported functionality
In the migration class, you have the following functionality available:
* execute: execute a raw SQL statement that doesn't return any data.
* query: execute a raw SQL statement that returns data.
* createTable: create a new table
* renameTable: rename a table
* removeTable: remove a table
* addColumn: add a column to a table
* renameColumn: rename a column in a table
* changeColumn: change the definition of a column in a table
* removeColumn: remove a column from a table
* addIndex: add an index to the database or table
* removeIndex: remove an index from the database or table
When specifying fields, we also support a type mapping so that you can use generic type definitions instead of database specific type definitions. The following types are supported:
* primary_key
* string
* text
* integer
* float
* decimal
* datetime
* timestamp
* time
* date
* binary
* boolean
* bool
You can also specify a database specific type when defining a field, but this will make your migrations less portable across database engines.
h2. Applying migrations
Once you created the migrations, you can apply them to your database by running the <code>migrate</code> command:
<pre>
protected/yiic migrate
</pre>
You will see the following output:
<pre>
Creating initial schema_version table
Applying migration: m20090611153243_CreateTables
>> Creating table: posts
>> Adding index posts_title to table: posts
Marking migration as applied: m20090611153243_CreateTables
Applying migration: m20090612162832_CreateTags
>> Creating table: tags
>> Creating table: post_tags
>> Adding index post_tags_post_tag to table: post_tags
Marking migration as applied: m20090612162832_CreateTags
Applying migration: m20090612163144_RenameTagsTable
>> Renaming table: post_tags to: post_tags_link_table
Marking migration as applied: m20090612163144_RenameTagsTable
Applying migration: m20090616153243_Test_CreateTables
>> Creating table: test_pages
>> Adding index test_pages_title to table: test_pages
Marking migration as applied: m20090616153243_Test_CreateTables
</pre>
It will apply all the migrations found in the <code>protected/migrations</code> directory provided they were not applied to the database yet.
It will also apply any migrations found in the <code>migrations</code> directory inside each module which is enabled in the application.
If you run the <code>migrate</code> command again, it will show that the migrations were applied already:
<pre>
Skipping applied migration: m20090611153243_CreateTables
Skipping applied migration: m20090612162832_CreateTags
Skipping applied migration: m20090612163144_RenameTagsTable
Skipping applied migration: m20090616153243_Test_CreateTables
</pre>
Since the <code>migrate</code> command checks based on the ID of each migration, it can detect that a migration is already applied to the database and therefor doesn't need to be applied anymore.
h2. Author information
This extension is created and maintained by Pieter Claerhout. You can contact the author on:
-* Website: http://www.yellowduck.be
-* Twitter: http://twitter.com/pieterclaerhout
-* Github: http://github.com/pieterclaerhout/yii-dbmigrations/tree/master
+* Website: "http://www.yellowduck.be":http://www.yellowduck.be
+* Twitter: "http://twitter.com/pieterclaerhout":http://twitter.com/pieterclaerhout
+* Github: "http://github.com/pieterclaerhout/yii-dbmigrations/tree/master":http://github.com/pieterclaerhout/yii-dbmigrations/tree/master
|
elchingon/yii-dbmigrations | 12a50afb3bdcf55057733a718e2f6cea8caf4d4e | The migrations are now performed transactional. | diff --git a/CDbMigration.php b/CDbMigration.php
index 2f2593a..8845063 100644
--- a/CDbMigration.php
+++ b/CDbMigration.php
@@ -1,121 +1,143 @@
<?php
/**
* CDbMigration class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* @package extensions.yii-dbmigrations
*/
class CDbMigrationException extends Exception {}
/**
* @package extensions.yii-dbmigrations
*/
abstract class CDbMigration {
// The adapter to use
private $adapter;
// Constructor
public function __construct(CDbMigrationAdapter $adapter) {
$this->adapter = $adapter;
}
+ // Perform a command transactional
+ public function performTransactional($command) {
+
+ // Check if the command exists
+ if (!method_exists($this, $command)) {
+ throw new CDbMigrationException(
+ 'Invalid migration command: ' . $command
+ );
+ }
+
+ // Run the command inside a transaction
+ $transaction = $this->adapter->db->beginTransaction();
+ try {
+ $this->$command();
+ $transaction->commit();
+ } catch (Exception $e) {
+ $transaction->rollback();
+ }
+
+
+ }
+
// Migrate up
public function up() {
}
// Migrate down
public function down() {
}
// Get the id of the migration
public function getId() {
$id = split('_', get_class($this));
return substr($id[0], 1);
}
// Get the name of the migration
public function getName() {
$name = split('_', get_class($this));
return $name[1];
}
// Execute a raw SQL statement
protected function execute($query, $params=array()) {
return $this->adapter->execute($query, $params);
}
// Execute a raw SQL statement
protected function query($query, $params=array()) {
return $this->adapter->query($query, $params);
}
// Create a table
protected function createTable($name, $columns=array(), $options=null) {
echo(' >> Creating table: ' . $name . PHP_EOL);
return $this->adapter->createTable($name, $columns, $options);
}
// Rename a table
protected function renameTable($name, $new_name) {
echo(' >> Renaming table: ' . $name . ' to: ' . $new_name . PHP_EOL);
return $this->adapter->renameTable($name, $new_name);
}
// Drop a table
protected function removeTable($name) {
echo(' >> Removing table: ' . $name . PHP_EOL);
return $this->adapter->removeTable($name);
}
// Add a database column
protected function addColumn($table, $column, $type, $options=null) {
echo(' >> Adding column ' . $column . ' to table: ' . $table . PHP_EOL);
return $this->adapter->addColumn($table, $column, $type, $options);
}
// Rename a database column
protected function renameColumn($table, $name, $new_name) {
echo(
' >> Renaming column ' . $name . ' to: ' . $new_name
. ' in table: ' . $table . PHP_EOL
);
return $this->adapter->renameColumn($table, $name, $new_name);
}
// Change a database column
protected function changeColumn($table, $column, $type, $options=null) {
echo(
' >> Chaning column ' . $name . ' to: ' . $type
. ' in table: ' . $table . PHP_EOL
);
return $this->adapter->changeColumn($table, $column, $type, $options);
}
// Remove a column
protected function removeColumn($table, $column) {
echo(
' >> Removing column ' . $column . ' from table: ' . $table . PHP_EOL
);
return $this->adapter->removeColumn($table, $column);
}
// Add an index
public function addIndex($table, $name, $columns, $unique=false) {
echo(' >> Adding index ' . $name . ' to table: ' . $table . PHP_EOL);
return $this->adapter->addIndex($table, $name, $columns, $unique);
}
// Remove an index
protected function removeIndex($table, $column) {
echo(' >> Removing index ' . $name . ' from table: ' . $table . PHP_EOL);
return $this->adapter->removeIndex($table, $column);
}
}
\ No newline at end of file
diff --git a/CDbMigrationEngine.php b/CDbMigrationEngine.php
index 155d83d..139548b 100644
--- a/CDbMigrationEngine.php
+++ b/CDbMigrationEngine.php
@@ -1,242 +1,242 @@
<?php
/**
* CDbMigrationEngine class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the adapters we are going to use for the migrations.
*/
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* A database migration engine exception
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngineException extends Exception {}
/**
* The CDbMigrationEngine class is the actual engine that can do all the
* migrations related functionality.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngine {
// The migration adapter to use
private $adapter;
// The name of the table and column for the schema information
const SCHEMA_TABLE = 'schema_version';
const SCHEMA_FIELD = 'id';
const SCHEMA_EXT = 'php';
const MIGRATIONS_DIR = 'migrations';
// Run the specified command
public function run($args) {
// Catch errors
try {
// Initialize the engine
$this->init();
// Check if we need to create a migration
if (isset($args[0]) && ($args[0] == 'create')) {
$this->create($args[0]);
} else {
$this->applyMigrations();
}
} catch (Exception $e) {
echo('ERROR: ' . $e->getMessage() . PHP_EOL);
}
}
// Initialize the schema version table
protected function init() {
// Check if a database connection was configured
try {
Yii::app()->db;
} catch (Exception $e) {
throw new CDbMigrationEngineException(
'Database configuration is missing in your configuration file.'
);
}
// Load the migration adapter
switch (Yii::app()->db->driverName) {
case 'mysql':
$this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
break;
case 'sqlite':
$this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
break;
default:
throw new CDbMigrationEngineException(
'Database of type ' . Yii::app()->db->driverName
. ' does not support migrations (yet).'
);
}
// Check if the schema version table exists
if (Yii::app()->db->schema->getTable('schema_version') == null) {
// Create the table
echo('Creating initial schema_version table' . PHP_EOL);
// Use the adapter to create the table
$this->adapter->createTable(
self::SCHEMA_TABLE,
array(
array(self::SCHEMA_FIELD, 'string'),
)
);
// Create an index on the column
$this->adapter->addIndex(
self::SCHEMA_TABLE,
'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
array(self::SCHEMA_FIELD),
true
);
}
}
// Get the list of migrations that are applied to the database
protected function getAppliedMigrations() {
// Get the field and table name
$field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
$table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
// Construct the SQL statement
$sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
// Get the list
return Yii::app()->db->createCommand($sql)->queryColumn(
self::SCHEMA_FIELD
);
}
// Get the list of possible migrations
protected function getPossibleMigrations() {
// Get the migrations for the default application
$migrations = $this->getPossibleMigrationsForModule();
// Get the migrations for each installed and enabled module
foreach (Yii::app()->modules as $module => $moduleData) {
$migrations = array_merge(
$migrations, $this->getPossibleMigrationsForModule($module)
);
}
// Sort them based on the file path (which is the key in the array)
ksort($migrations);
// Returh the list of migrations
return $migrations;
}
// Get the list of migrations for a specific module
protected function getPossibleMigrationsForModule($module=null) {
// Get the path to the migrations dir
$path = Yii::app()->basePath;
if (!empty($module)) {
$path .= '/modules/' . trim($module, '/');
}
$path .= '/' . self::MIGRATIONS_DIR;
// Start with an empty list
$migrations = array();
// Check if the migrations directory actually exists
if (is_dir($path)) {
// Construct the list of migrations
$migrationFiles = CFileHelper::findFiles(
$path,
array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
);
foreach ($migrationFiles as $migration) {
$migrations[$migration] = basename(
$migration, '.' . self::SCHEMA_EXT
);
}
}
// Return the list
return $migrations;
}
// Apply the migrations
protected function applyMigrations() {
// Get the list of applied and possible migrations
$applied = $this->getAppliedMigrations();
$possible = $this->getPossibleMigrations();
// Loop over all possible migrations
foreach ($possible as $migrationFile => $migration) {
// Include the migration file
require($migrationFile);
// Create the migration instance
$migration = new $migration($this->adapter);
// Check if it's already applied to the database
if (!in_array($migration->getId(), $applied)) {
// Apply the migration to the database
$this->applyMigration($migration);
} else {
// Skip the already applied migration
echo(
'Skipping applied migration: ' . get_class($migration) . PHP_EOL
);
}
}
}
// Apply a specific migration
protected function applyMigration($migration) {
// Apply the migration
echo('Applying migration: ' . get_class($migration) . PHP_EOL);
// Create the migration instance
- $migration->up();
+ $migration->performTransactional('up');
// Commit the migration
echo(
'Marking migration as applied: ' . get_class($migration) . PHP_EOL
);
$cmd = Yii::app()->db->commandBuilder->createInsertCommand(
self::SCHEMA_TABLE,
array(self::SCHEMA_FIELD => $migration->getId())
)->execute();
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | a2480e89444b5a8faf7c1ba8114edf5406b41268 | Fixed the newlines in the readme file. | diff --git a/README.textile b/README.textile
index 41b63d6..d66a88d 100644
--- a/README.textile
+++ b/README.textile
@@ -1,274 +1,232 @@
h1. Yii DB Migrations
-A database migrations engine for the Yii framework. It comes in the form of an
-extension which can be dropped into any existing Yii framework application.
+A database migrations engine for the Yii framework. It comes in the form of an extension which can be dropped into any existing Yii framework application.
-It relies on the database abstraction layer of the Yii framework to talk to the
-database engine.
+It relies on the database abstraction layer of the Yii framework to talk to the database engine.
-It's largely inspired on the migrations functionality of the Ruby on Rails
-framework.
+It's largely inspired on the migrations functionality of the Ruby on Rails framework.
h2. Why bother in the first place?
-You might wonder why you need database migrations in the first place. Sure, you
-could use plain SQL files to apply updates to the database, but they have a big
-disadvantage: they are database specific.
+You might wonder why you need database migrations in the first place. Sure, you could use plain SQL files to apply updates to the database, but they have a big disadvantage: they are database specific.
-Imagine you initially create your database using SQLite and later on decide to
-change to MySQL. When you use plain SQL files, you will need to rewrite them
-using MySQL's flavor of SQL. Also, you will need to create some tool that knows
-what has been applied already to the database and what's not applied yet.
+Imagine you initially create your database using SQLite and later on decide to change to MySQL. When you use plain SQL files, you will need to rewrite them using MySQL's flavor of SQL. Also, you will need to create some tool that knows what has been applied already to the database and what's not applied yet.
-Meet database migrations. By defining a higher level interface to creating and
-maintaining the database schema, you can define it in a database agnostic way.
+Meet database migrations. By defining a higher level interface to creating and maintaining the database schema, you can define it in a database agnostic way.
-By using PHP functions to create tables, indexes, fields, ... you can write the
-schema once and apply it to any database backend supported. The added bonus is
-that the yii-dbmigrations extension keeps track of which migrations have been
-applied already and which ones still need to be applied.
+By using PHP functions to create tables, indexes, fields, ... you can write the schema once and apply it to any database backend supported. The added bonus is that the yii-dbmigrations extension keeps track of which migrations have been applied already and which ones still need to be applied.
h2. Current limitations
Be aware that the current version is still very alpha.
There are only two database engines supported:
+
* MySQL
* SQLite
-In the current version, it's only possible to migrate up, it cannot (yet) remove
-already installed migrations.
+In the current version, it's only possible to migrate up, it cannot (yet) remove already installed migrations.
h2. Installing the extension
h3. Putting the files in the right location
-Installing the extension is quite easy. Once you downloaded the files from
-github, you need to put all the files in a folder called "yii-dbmigrations" and
-put it in the <code>protected/extensions</code> folder from your project.
+Installing the extension is quite easy. Once you downloaded the files from github, you need to put all the files in a folder called "yii-dbmigrations" and put it in the <code>protected/extensions</code> folder from your project.
h3. Configuring the database connection
-You need to make sure you configure database access properly in the
-configuration file of your project. As the console applications in the Yii
-framework look at the <code>protected/config/console.php</code> file, you need
-to make sure you configure the <code>db</code> settings under the
-<code>components</code> key in the configuration array. For MySQL, the
-configuration will look as follows:
+You need to make sure you configure database access properly in the configuration file of your project. As the console applications in the Yii framework look at the <code>protected/config/console.php</code> file, you need to make sure you configure the <code>db</code> settings under the <code>components</code> key in the configuration array. For MySQL, the configuration will look as follows:
<pre>
'components' => array(
'db'=>array(
'class' => 'CDbConnection',
'connectionString'=>'mysql:host=localhost;dbname=my_db',
'charset' => 'UTF8',
'username'=>'root',
'password'=>'root',
),
),
</pre>
For SQLite, the configuration looks as follows:
<pre>
'components' => array(
'db'=>array(
'connectionString'=>'sqlite:'.dirname(__FILE__).'/../data/my_db.db',
),
),
</pre>
h3. Configuring the command map
-To make the <code>yiic</code> tool know about the <code>migrate</code> command,
-you need to add a <code>commandMap</code> key to the application configuration.
+To make the <code>yiic</code> tool know about the <code>migrate</code> command, you need to add a <code>commandMap</code> key to the application configuration.
In there, you need to put the following configuration:
<pre>
'commandMap' => array(
'migrate' => array(
'class'=>'application.extensions.yii-dbmigrations.CDbMigrationCommand',
),
),
</pre>
h3. Testing your installation
-To test if the installation was succesfull, you can run the yiic command and
-should see the following output:
+To test if the installation was succesfull, you can run the yiic command and should see the following output:
<pre>
Yii command runner (based on Yii v1.0.6)
Usage: protected/yiic <command-name> [parameters...]
The following commands are available:
- migrate
- message
- shell
- webapp
To see individual command help, use the following:
protected/yiic help <command-name>
</pre>
It should mention that the <code>migrate</code> command is available.
h2. Creating migrations
h3. Naming conventions
-You can create migrations by creating files in the
-<code>protected/migrations</code> folder or in the <code>migrations</code>
-folder inside your module. The file names for the migrations
-should follow a specific naming convention:
+You can create migrations by creating files in the <code>protected/migrations</code> folder or in the <code>migrations</code> folder inside your module. The file names for the migrations should follow a specific naming convention:
<pre>
m20090614213453_MigrationName.php
</pre>
-The migration file names always start with the letter m followed by 14 digit
-timestamp and an underscore. After that, you can give a name to the migration so
-that you can easily identify the migration.
+The migration file names always start with the letter m followed by 14 digit timestamp and an underscore. After that, you can give a name to the migration so that you can easily identify the migration.
-If your migration is part of a module, it's a good idea to add the name of the
-module between the migration ID and name so that the name looks as follows:
+If your migration is part of a module, it's a good idea to add the name of the module between the migration ID and name so that the name looks as follows:
<pre>
m20090614213453_ModuleName_MigrationName.php
</pre>
-This will ensure that there is much less chance for naming conflicts between
-migrations in different modules.
+This will ensure that there is much less chance for naming conflicts between migrations in different modules.
h3. Implementing the migration
-In the migration file, you need to create a class that extends the parent class
-<code>CDbMigration</code>. The <code>CDbMigration</code> class needs to have the
-<code>up</code> and <code>down</code> methods as you can see in the following
-sample migration:
+In the migration file, you need to create a class that extends the parent class <code>CDbMigration</code>. The <code>CDbMigration</code> class needs to have the <code>up</code> and <code>down</code> methods as you can see in the following sample migration:
<pre>
class m20090611153243_CreateTables extends CDbMigration {
public function up() {
$this->createTable(
'posts',
array(
array('id', 'primary_key'),
array('title', 'string'),
array('body', 'text'),
)
);
$this->addIndex(
'posts', 'posts_title', array('title')
);
}
public function down() {
$this->removeTable('posts');
}
}
</pre>
h3. Supported functionality
In the migration class, you have the following functionality available:
* execute: execute a raw SQL statement that doesn't return any data.
* query: execute a raw SQL statement that returns data.
* createTable: create a new table
* renameTable: rename a table
* removeTable: remove a table
* addColumn: add a column to a table
* renameColumn: rename a column in a table
* changeColumn: change the definition of a column in a table
* removeColumn: remove a column from a table
* addIndex: add an index to the database or table
* removeIndex: remove an index from the database or table
-When specifying fields, we also support a type mapping so that you can use
-generic type definitions instead of database specific type definitions. The
-following types are supported:
+When specifying fields, we also support a type mapping so that you can use generic type definitions instead of database specific type definitions. The following types are supported:
* primary_key
* string
* text
* integer
* float
* decimal
* datetime
* timestamp
* time
* date
* binary
* boolean
* bool
-You can also specify a database specific type when defining a field, but this
-will make your migrations less portable across database engines.
+You can also specify a database specific type when defining a field, but this will make your migrations less portable across database engines.
h2. Applying migrations
-Once you created the migrations, you can apply them to your database by running
-the <code>migrate</code> command:
+Once you created the migrations, you can apply them to your database by running the <code>migrate</code> command:
<pre>
protected/yiic migrate
</pre>
You will see the following output:
<pre>
Creating initial schema_version table
Applying migration: m20090611153243_CreateTables
>> Creating table: posts
>> Adding index posts_title to table: posts
Marking migration as applied: m20090611153243_CreateTables
Applying migration: m20090612162832_CreateTags
>> Creating table: tags
>> Creating table: post_tags
>> Adding index post_tags_post_tag to table: post_tags
Marking migration as applied: m20090612162832_CreateTags
Applying migration: m20090612163144_RenameTagsTable
>> Renaming table: post_tags to: post_tags_link_table
Marking migration as applied: m20090612163144_RenameTagsTable
Applying migration: m20090616153243_Test_CreateTables
>> Creating table: test_pages
>> Adding index test_pages_title to table: test_pages
Marking migration as applied: m20090616153243_Test_CreateTables
</pre>
-It will apply all the migrations found in the
-<code>protected/migrations</code> directory provided they were not applied to
-the database yet.
+It will apply all the migrations found in the <code>protected/migrations</code> directory provided they were not applied to the database yet.
-It will also apply any migrations found in the <code>migrations</code>
-directory inside each module which is enabled in the application.
+It will also apply any migrations found in the <code>migrations</code> directory inside each module which is enabled in the application.
-If you run the <code>migrate</code> command again, it will show that the
-migrations were applied already:
+If you run the <code>migrate</code> command again, it will show that the migrations were applied already:
<pre>
Skipping applied migration: m20090611153243_CreateTables
Skipping applied migration: m20090612162832_CreateTags
Skipping applied migration: m20090612163144_RenameTagsTable
Skipping applied migration: m20090616153243_Test_CreateTables
</pre>
-Since the <code>migrate</code> command checks based on the ID of each migration,
-it can detect that a migration is already applied to the database and therefor
-doesn't need to be applied anymore.
+Since the <code>migrate</code> command checks based on the ID of each migration, it can detect that a migration is already applied to the database and therefor doesn't need to be applied anymore.
h2. Author information
-This extension is created and maintained by Pieter Claerhout. You can contact
-the author on:
+This extension is created and maintained by Pieter Claerhout. You can contact the author on:
* Website: http://www.yellowduck.be
* Twitter: http://twitter.com/pieterclaerhout
* Github: http://github.com/pieterclaerhout/yii-dbmigrations/tree/master
|
elchingon/yii-dbmigrations | 9f13384dbbd13e6ebdd697933202b26adee29d7f | Added a lot more information to the readme file. | diff --git a/CDbMigrationAdapter.php b/CDbMigrationAdapter.php
index 2e1e730..495da37 100644
--- a/CDbMigrationAdapter.php
+++ b/CDbMigrationAdapter.php
@@ -1,143 +1,146 @@
<?php
/**
* CDbMigrationAdapter class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* @package extensions.yii-dbmigrations
*/
abstract class CDbMigrationAdapter {
// The database connection
public $db;
// Constructor
public function __construct(CDbConnection $db) {
$this->db = $db;
}
// Convert a type to a native database type
protected function convertToNativeType($theType) {
if (isset($this->nativeDatabaseTypes[$theType])) {
return $this->nativeDatabaseTypes[$theType];
} else {
return $theType;
}
}
// Convert the field information to native types
protected function convertFields($fields) {
$result = array();
foreach ($fields as $field) {
if (is_array($field)) {
if (isset($field[0])) {
$field[0] = $this->db->quoteColumnName($field[0]);
}
if (isset($field[1])) {
$field[1] = $this->convertToNativeType($field[1]);
}
$result[] = join(' ', $field);
} else {
$result[] = $this->db->quoteColumnName($field);
}
}
return join(', ', $result);
}
// Execute a raw SQL statement
+ // @todo We need to be able to bind parameters
public function execute($query, $params=array()) {
return $this->db->createCommand($query)->execute();
}
// Execute a raw SQL statement
+ // @todo We need to be able to bind parameters
public function query($query, $params=array()) {
return $this->db->createCommand($query)->queryAll();
}
// Get the column info
public function columnInfo($name) {
}
// Create a table
public function createTable($name, $columns=array(), $options=null) {
$sql = 'CREATE TABLE ' . $this->db->quoteTableName($name) . ' ('
. $this->convertFields($columns)
. ') ' . $options;
return $this->execute($sql);
}
// Rename a table
public function renameTable($name, $new_name) {
$sql = 'RENAME TABLE ' . $this->db->quoteTableName($name) . ' TO '
. $this->db->quoteTableName($new_name);
return $this->execute($sql);
}
// Drop a table
public function removeTable($name) {
$sql = 'DROP TABLE ' . $this->db->quoteTableName($name);
return $this->execute($sql);
}
// Add a database column
public function addColumn($table, $column, $type, $options=null) {
$type = $this->convertToNativeType($type);
if (empty($options)) {
$options = 'NOT NULL';
}
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD '
. $this->db->quoteColumnName($column) . ' ' . $type . ' '
. $options;
return $this->execute($sql);
}
// Change a database column
public function changeColumn($table, $column, $type, $options=null) {
$type = $this->convertToNativeType($type);
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
. $this->db->quoteColumnName($column) . ' '
. $this->db->quoteColumnName($column) . ' ' . $type . ' '
. $options;
return $this->execute($sql);
}
// Rename a database column
+ // @todo We need to retain the column definition
public function renameColumn($table, $name, $new_name) {
$type = $this->columnInfo($name);
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
. $this->db->quoteColumnName($name) . ' '
. $this->db->quoteColumnName($new_name) . ' ' . $type;
return $this->execute($sql);
}
// Remove a column
public function removeColumn($table, $column) {
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' DROP '
. $this->db->quoteColumnName($column);
return $this->execute($sql);
}
// Add an index
public function addIndex($table, $name, $columns, $unique=false) {
$sql = 'CREATE ';
$sql .= ($unique) ? 'UNIQUE ' : '';
$sql .= 'INDEX ' . $this->db->quoteColumnName($name) . ' ON '
. $this->db->quoteTableName($table) . ' ('
. $this->convertFields($columns)
. ')';
return $this->execute($sql);
}
// Remove an index
public function removeIndex($table, $name) {
$sql = 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON '
. $this->db->quoteTableName($table);
return $this->execute($sql);
}
}
diff --git a/README.textile b/README.textile
index 64d4412..41b63d6 100644
--- a/README.textile
+++ b/README.textile
@@ -1,233 +1,274 @@
h1. Yii DB Migrations
A database migrations engine for the Yii framework. It comes in the form of an
extension which can be dropped into any existing Yii framework application.
It relies on the database abstraction layer of the Yii framework to talk to the
database engine.
It's largely inspired on the migrations functionality of the Ruby on Rails
framework.
h2. Why bother in the first place?
You might wonder why you need database migrations in the first place. Sure, you
could use plain SQL files to apply updates to the database, but they have a big
disadvantage: they are database specific.
Imagine you initially create your database using SQLite and later on decide to
change to MySQL. When you use plain SQL files, you will need to rewrite them
using MySQL's flavor of SQL. Also, you will need to create some tool that knows
what has been applied already to the database and what's not applied yet.
Meet database migrations. By defining a higher level interface to creating and
maintaining the database schema, you can define it in a database agnostic way.
By using PHP functions to create tables, indexes, fields, ... you can write the
schema once and apply it to any database backend supported. The added bonus is
that the yii-dbmigrations extension keeps track of which migrations have been
applied already and which ones still need to be applied.
h2. Current limitations
Be aware that the current version is still very alpha.
There are only two database engines supported:
* MySQL
* SQLite
In the current version, it's only possible to migrate up, it cannot (yet) remove
already installed migrations.
h2. Installing the extension
h3. Putting the files in the right location
Installing the extension is quite easy. Once you downloaded the files from
github, you need to put all the files in a folder called "yii-dbmigrations" and
put it in the <code>protected/extensions</code> folder from your project.
h3. Configuring the database connection
You need to make sure you configure database access properly in the
configuration file of your project. As the console applications in the Yii
framework look at the <code>protected/config/console.php</code> file, you need
to make sure you configure the <code>db</code> settings under the
<code>components</code> key in the configuration array. For MySQL, the
configuration will look as follows:
<pre>
'components' => array(
'db'=>array(
'class' => 'CDbConnection',
'connectionString'=>'mysql:host=localhost;dbname=my_db',
'charset' => 'UTF8',
'username'=>'root',
'password'=>'root',
),
),
</pre>
For SQLite, the configuration looks as follows:
<pre>
'components' => array(
'db'=>array(
'connectionString'=>'sqlite:'.dirname(__FILE__).'/../data/my_db.db',
),
),
</pre>
h3. Configuring the command map
To make the <code>yiic</code> tool know about the <code>migrate</code> command,
you need to add a <code>commandMap</code> key to the application configuration.
In there, you need to put the following configuration:
<pre>
'commandMap' => array(
'migrate' => array(
'class'=>'application.extensions.yii-dbmigrations.CDbMigrationCommand',
),
),
</pre>
h3. Testing your installation
To test if the installation was succesfull, you can run the yiic command and
should see the following output:
<pre>
Yii command runner (based on Yii v1.0.6)
Usage: protected/yiic <command-name> [parameters...]
The following commands are available:
- migrate
- message
- shell
- webapp
To see individual command help, use the following:
protected/yiic help <command-name>
</pre>
It should mention that the <code>migrate</code> command is available.
h2. Creating migrations
+h3. Naming conventions
+
You can create migrations by creating files in the
<code>protected/migrations</code> folder or in the <code>migrations</code>
folder inside your module. The file names for the migrations
should follow a specific naming convention:
<pre>
m20090614213453_MigrationName.php
</pre>
The migration file names always start with the letter m followed by 14 digit
timestamp and an underscore. After that, you can give a name to the migration so
that you can easily identify the migration.
If your migration is part of a module, it's a good idea to add the name of the
module between the migration ID and name so that the name looks as follows:
<pre>
m20090614213453_ModuleName_MigrationName.php
</pre>
This will ensure that there is much less chance for naming conflicts between
migrations in different modules.
+h3. Implementing the migration
+
In the migration file, you need to create a class that extends the parent class
<code>CDbMigration</code>. The <code>CDbMigration</code> class needs to have the
<code>up</code> and <code>down</code> methods as you can see in the following
sample migration:
<pre>
class m20090611153243_CreateTables extends CDbMigration {
public function up() {
$this->createTable(
'posts',
array(
array('id', 'primary_key'),
array('title', 'string'),
array('body', 'text'),
)
);
$this->addIndex(
'posts', 'posts_title', array('title')
);
}
public function down() {
$this->removeTable('posts');
}
}
</pre>
+h3. Supported functionality
+
+In the migration class, you have the following functionality available:
+
+* execute: execute a raw SQL statement that doesn't return any data.
+* query: execute a raw SQL statement that returns data.
+* createTable: create a new table
+* renameTable: rename a table
+* removeTable: remove a table
+* addColumn: add a column to a table
+* renameColumn: rename a column in a table
+* changeColumn: change the definition of a column in a table
+* removeColumn: remove a column from a table
+* addIndex: add an index to the database or table
+* removeIndex: remove an index from the database or table
+
+When specifying fields, we also support a type mapping so that you can use
+generic type definitions instead of database specific type definitions. The
+following types are supported:
+
+* primary_key
+* string
+* text
+* integer
+* float
+* decimal
+* datetime
+* timestamp
+* time
+* date
+* binary
+* boolean
+* bool
+
+You can also specify a database specific type when defining a field, but this
+will make your migrations less portable across database engines.
+
h2. Applying migrations
Once you created the migrations, you can apply them to your database by running
the <code>migrate</code> command:
<pre>
protected/yiic migrate
</pre>
You will see the following output:
<pre>
Creating initial schema_version table
Applying migration: m20090611153243_CreateTables
>> Creating table: posts
>> Adding index posts_title to table: posts
Marking migration as applied: m20090611153243_CreateTables
Applying migration: m20090612162832_CreateTags
>> Creating table: tags
>> Creating table: post_tags
>> Adding index post_tags_post_tag to table: post_tags
Marking migration as applied: m20090612162832_CreateTags
Applying migration: m20090612163144_RenameTagsTable
>> Renaming table: post_tags to: post_tags_link_table
Marking migration as applied: m20090612163144_RenameTagsTable
Applying migration: m20090616153243_Test_CreateTables
>> Creating table: test_pages
>> Adding index test_pages_title to table: test_pages
Marking migration as applied: m20090616153243_Test_CreateTables
</pre>
It will apply all the migrations found in the
<code>protected/migrations</code> directory provided they were not applied to
the database yet.
It will also apply any migrations found in the <code>migrations</code>
directory inside each module which is enabled in the application.
If you run the <code>migrate</code> command again, it will show that the
migrations were applied already:
<pre>
Skipping applied migration: m20090611153243_CreateTables
Skipping applied migration: m20090612162832_CreateTags
Skipping applied migration: m20090612163144_RenameTagsTable
Skipping applied migration: m20090616153243_Test_CreateTables
</pre>
Since the <code>migrate</code> command checks based on the ID of each migration,
it can detect that a migration is already applied to the database and therefor
doesn't need to be applied anymore.
h2. Author information
This extension is created and maintained by Pieter Claerhout. You can contact
the author on:
* Website: http://www.yellowduck.be
* Twitter: http://twitter.com/pieterclaerhout
* Github: http://github.com/pieterclaerhout/yii-dbmigrations/tree/master
|
elchingon/yii-dbmigrations | 8ba95d4a8486b21189239a1e0161f59f9ac3e82e | Added a note about migrations in modules. Updated the screendumps of the yiic migrate output. | diff --git a/README.textile b/README.textile
index 2a81357..058d06d 100644
--- a/README.textile
+++ b/README.textile
@@ -1,191 +1,210 @@
h1. Yii DB Migrations
A database migrations engine for the Yii framework. It comes in the form of an
extension which can be dropped into any existing Yii framework application.
It relies on the database abstraction layer of the Yii framework to talk to the
database engine.
It's largely inspired on the migrations functionality of the Ruby on Rails
framework.
h2. Current limitations
Be aware that the current version is still very alpha.
There are only two database engines supported:
* MySQL
* SQLite
In the current version, it's only possible to migrate up, it cannot (yet) remove
already installed migrations.
h2. Installing the extension
h3. Putting the files in the right location
Installing the extension is quite easy. Once you downloaded the files from
github, you need to put all the files in a folder called "yii-dbmigrations" and
put it in the <code>protected/extensions</code> folder from your project.
h3. Configuring the database connection
You need to make sure you configure database access properly in the
configuration file of your project. As the console applications in the Yii
framework look at the <code>protected/config/console.php</code> file, you need
to make sure you configure the <code>db</code> settings under the
<code>components</code> key in the configuration array. For MySQL, the
configuration will look as follows:
<pre>
'components' => array(
'db'=>array(
'class' => 'CDbConnection',
'connectionString'=>'mysql:host=localhost;dbname=my_db',
'charset' => 'UTF8',
'username'=>'root',
'password'=>'root',
),
),
</pre>
For SQLite, the configuration looks as follows:
<pre>
'components' => array(
'db'=>array(
'connectionString'=>'sqlite:'.dirname(__FILE__).'/../data/my_db.db',
),
),
</pre>
h3. Configuring the command map
To make the <code>yiic</code> tool know about the <code>migrate</code> command,
you need to add a <code>commandMap</code> key to the application configuration.
In there, you need to put the following configuration:
<pre>
'commandMap' => array(
'migrate' => array(
'class'=>'application.extensions.yii-dbmigrations.CDbMigrationCommand',
),
),
</pre>
h3. Testing your installation
To test if the installation was succesfull, you can run the yiic command and
should see the following output:
<pre>
Yii command runner (based on Yii v1.0.6)
Usage: protected/yiic <command-name> [parameters...]
The following commands are available:
- migrate
- message
- shell
- webapp
To see individual command help, use the following:
protected/yiic help <command-name>
</pre>
It should mention that the <code>migrate</code> command is available.
h2. Creating migrations
You can create migrations by creating files in the
-<code>protected/migrations</code> folder. The file names for the migrations
+<code>protected/migrations</code> folder or in the <code>migrations</code>
+folder inside your module. The file names for the migrations
should follow a specific naming convention:
<pre>
m20090614213453_MigrationName.php
</pre>
The migration file names always start with the letter m followed by 14 digit
timestamp and an underscore. After that, you can give a name to the migration so
that you can easily identify the migration.
+If your migration is part of a module, it's a good idea to add the name of the
+module between the migration ID and name so that the name looks as follows:
+
+<pre>
+m20090614213453_ModuleName_MigrationName.php
+</pre>
+
+This will ensure that there is much less chance for naming conflicts between
+migrations in different modules.
+
In the migration file, you need to create a class that extends the parent class
<code>CDbMigration</code>. The <code>CDbMigration</code> class needs to have the
<code>up</code> and <code>down</code> methods as you can see in the following
sample migration:
<pre>
class m20090611153243_CreateTables extends CDbMigration {
public function up() {
$this->createTable(
'posts',
array(
array('id', 'primary_key'),
array('title', 'string'),
array('body', 'text'),
)
);
$this->addIndex(
'posts', 'posts_title', array('title')
);
}
public function down() {
$this->removeTable('posts');
}
}
</pre>
h2. Applying migrations
Once you created the migrations, you can apply them to your database by running
the <code>migrate</code> command:
<pre>
protected/yiic migrate
</pre>
You will see the following output:
<pre>
Creating initial schema_version table
Applying migration: m20090611153243_CreateTables
>> Creating table: posts
>> Adding index posts_title to table: posts
Marking migration as applied: m20090611153243_CreateTables
Applying migration: m20090612162832_CreateTags
>> Creating table: tags
>> Creating table: post_tags
>> Adding index post_tags_post_tag to table: post_tags
Marking migration as applied: m20090612162832_CreateTags
Applying migration: m20090612163144_RenameTagsTable
>> Renaming table: post_tags to: post_tags_link_table
Marking migration as applied: m20090612163144_RenameTagsTable
+Applying migration: m20090616153243_Test_CreateTables
+ >> Creating table: test_pages
+ >> Adding index test_pages_title to table: test_pages
+Marking migration as applied: m20090616153243_Test_CreateTables
</pre>
It will apply all the migrations found in the
<code>protected/migrations</code> directory provided they were not applied to
the database yet.
+It will also apply any migrations found in the <code>migrations</code>
+directory inside each module which is enabled in the application.
+
If you run the <code>migrate</code> command again, it will show that the
migrations were applied already:
<pre>
Skipping applied migration: m20090611153243_CreateTables
Skipping applied migration: m20090612162832_CreateTags
Skipping applied migration: m20090612163144_RenameTagsTable
+Skipping applied migration: m20090616153243_Test_CreateTables
</pre>
h3. Author information
This extension is created and maintained by Pieter Claerhout. You can contact
the author on:
* Website: http://www.yellowduck.be
* Twitter: http://twitter.com/pieterclaerhout
* Github: http://github.com/pieterclaerhout/yii-dbmigrations/tree/master
|
elchingon/yii-dbmigrations | fb824dd9c9234e1d7519f5d111718b2752aa05b0 | An error is no longer thrown if the migrations directory doesn't exist. | diff --git a/CDbMigrationEngine.php b/CDbMigrationEngine.php
index 0808eda..155d83d 100644
--- a/CDbMigrationEngine.php
+++ b/CDbMigrationEngine.php
@@ -1,236 +1,242 @@
<?php
/**
* CDbMigrationEngine class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the adapters we are going to use for the migrations.
*/
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* A database migration engine exception
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngineException extends Exception {}
/**
* The CDbMigrationEngine class is the actual engine that can do all the
* migrations related functionality.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngine {
// The migration adapter to use
private $adapter;
// The name of the table and column for the schema information
const SCHEMA_TABLE = 'schema_version';
const SCHEMA_FIELD = 'id';
const SCHEMA_EXT = 'php';
const MIGRATIONS_DIR = 'migrations';
// Run the specified command
public function run($args) {
// Catch errors
try {
// Initialize the engine
$this->init();
// Check if we need to create a migration
if (isset($args[0]) && ($args[0] == 'create')) {
$this->create($args[0]);
} else {
$this->applyMigrations();
}
} catch (Exception $e) {
echo('ERROR: ' . $e->getMessage() . PHP_EOL);
}
}
// Initialize the schema version table
protected function init() {
// Check if a database connection was configured
try {
Yii::app()->db;
} catch (Exception $e) {
throw new CDbMigrationEngineException(
'Database configuration is missing in your configuration file.'
);
}
// Load the migration adapter
switch (Yii::app()->db->driverName) {
case 'mysql':
$this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
break;
case 'sqlite':
$this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
break;
default:
throw new CDbMigrationEngineException(
'Database of type ' . Yii::app()->db->driverName
. ' does not support migrations (yet).'
);
}
// Check if the schema version table exists
if (Yii::app()->db->schema->getTable('schema_version') == null) {
// Create the table
echo('Creating initial schema_version table' . PHP_EOL);
// Use the adapter to create the table
$this->adapter->createTable(
self::SCHEMA_TABLE,
array(
array(self::SCHEMA_FIELD, 'string'),
)
);
// Create an index on the column
$this->adapter->addIndex(
self::SCHEMA_TABLE,
'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
array(self::SCHEMA_FIELD),
true
);
}
}
// Get the list of migrations that are applied to the database
protected function getAppliedMigrations() {
// Get the field and table name
$field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
$table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
// Construct the SQL statement
$sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
// Get the list
return Yii::app()->db->createCommand($sql)->queryColumn(
self::SCHEMA_FIELD
);
}
// Get the list of possible migrations
protected function getPossibleMigrations() {
// Get the migrations for the default application
$migrations = $this->getPossibleMigrationsForModule();
// Get the migrations for each installed and enabled module
foreach (Yii::app()->modules as $module => $moduleData) {
$migrations = array_merge(
$migrations, $this->getPossibleMigrationsForModule($module)
);
}
// Sort them based on the file path (which is the key in the array)
ksort($migrations);
// Returh the list of migrations
return $migrations;
}
// Get the list of migrations for a specific module
protected function getPossibleMigrationsForModule($module=null) {
// Get the path to the migrations dir
$path = Yii::app()->basePath;
if (!empty($module)) {
$path .= '/modules/' . trim($module, '/');
}
$path .= '/' . self::MIGRATIONS_DIR;
// Start with an empty list
$migrations = array();
- // Construct the list of migrations
- $migrationFiles = CFileHelper::findFiles(
- $path, array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
- );
- foreach ($migrationFiles as $migration) {
- $migrations[$migration] = basename(
- $migration, '.' . self::SCHEMA_EXT
+ // Check if the migrations directory actually exists
+ if (is_dir($path)) {
+
+ // Construct the list of migrations
+ $migrationFiles = CFileHelper::findFiles(
+ $path,
+ array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
);
+ foreach ($migrationFiles as $migration) {
+ $migrations[$migration] = basename(
+ $migration, '.' . self::SCHEMA_EXT
+ );
+ }
+
}
// Return the list
return $migrations;
}
// Apply the migrations
protected function applyMigrations() {
// Get the list of applied and possible migrations
$applied = $this->getAppliedMigrations();
$possible = $this->getPossibleMigrations();
// Loop over all possible migrations
foreach ($possible as $migrationFile => $migration) {
// Include the migration file
require($migrationFile);
// Create the migration instance
$migration = new $migration($this->adapter);
// Check if it's already applied to the database
if (!in_array($migration->getId(), $applied)) {
// Apply the migration to the database
$this->applyMigration($migration);
} else {
// Skip the already applied migration
echo(
'Skipping applied migration: ' . get_class($migration) . PHP_EOL
);
}
}
}
// Apply a specific migration
protected function applyMigration($migration) {
// Apply the migration
echo('Applying migration: ' . get_class($migration) . PHP_EOL);
// Create the migration instance
$migration->up();
// Commit the migration
echo(
'Marking migration as applied: ' . get_class($migration) . PHP_EOL
);
$cmd = Yii::app()->db->commandBuilder->createInsertCommand(
self::SCHEMA_TABLE,
array(self::SCHEMA_FIELD => $migration->getId())
)->execute();
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | 6ebe241eb9ce40e01fa9de0641027dbf3a00567c | The migrations are now also loaded from the modules that are enabled. | diff --git a/CDbMigrationEngine.php b/CDbMigrationEngine.php
index 5a04346..0808eda 100644
--- a/CDbMigrationEngine.php
+++ b/CDbMigrationEngine.php
@@ -1,181 +1,236 @@
<?php
/**
* CDbMigrationEngine class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the adapters we are going to use for the migrations.
*/
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* A database migration engine exception
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngineException extends Exception {}
/**
* The CDbMigrationEngine class is the actual engine that can do all the
* migrations related functionality.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngine {
// The migration adapter to use
private $adapter;
// The name of the table and column for the schema information
- const SCHEMA_TABLE = 'schema_version';
- const SCHEMA_FIELD = 'id';
- const SCHEMA_EXT = 'php';
+ const SCHEMA_TABLE = 'schema_version';
+ const SCHEMA_FIELD = 'id';
+ const SCHEMA_EXT = 'php';
+ const MIGRATIONS_DIR = 'migrations';
// Run the specified command
public function run($args) {
// Catch errors
try {
// Initialize the engine
$this->init();
// Check if we need to create a migration
if (isset($args[0]) && ($args[0] == 'create')) {
$this->create($args[0]);
} else {
$this->applyMigrations();
}
} catch (Exception $e) {
echo('ERROR: ' . $e->getMessage() . PHP_EOL);
}
}
// Initialize the schema version table
protected function init() {
- // Add the migrations directory to the search path
- Yii::import('application.migrations.*');
-
// Check if a database connection was configured
try {
Yii::app()->db;
} catch (Exception $e) {
throw new CDbMigrationEngineException(
'Database configuration is missing in your configuration file.'
);
}
// Load the migration adapter
switch (Yii::app()->db->driverName) {
case 'mysql':
$this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
break;
case 'sqlite':
$this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
break;
default:
throw new CDbMigrationEngineException(
'Database of type ' . Yii::app()->db->driverName
. ' does not support migrations (yet).'
);
}
// Check if the schema version table exists
if (Yii::app()->db->schema->getTable('schema_version') == null) {
// Create the table
echo('Creating initial schema_version table' . PHP_EOL);
// Use the adapter to create the table
$this->adapter->createTable(
self::SCHEMA_TABLE,
array(
array(self::SCHEMA_FIELD, 'string'),
)
);
// Create an index on the column
$this->adapter->addIndex(
self::SCHEMA_TABLE,
'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
array(self::SCHEMA_FIELD),
true
);
}
}
// Get the list of migrations that are applied to the database
protected function getAppliedMigrations() {
// Get the field and table name
$field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
$table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
// Construct the SQL statement
$sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
// Get the list
return Yii::app()->db->createCommand($sql)->queryColumn(
self::SCHEMA_FIELD
);
}
// Get the list of possible migrations
protected function getPossibleMigrations() {
- $migrations = CFileHelper::findFiles(
- Yii::app()->basePath . '/migrations',
- array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
+
+ // Get the migrations for the default application
+ $migrations = $this->getPossibleMigrationsForModule();
+
+ // Get the migrations for each installed and enabled module
+ foreach (Yii::app()->modules as $module => $moduleData) {
+ $migrations = array_merge(
+ $migrations, $this->getPossibleMigrationsForModule($module)
+ );
+ }
+
+ // Sort them based on the file path (which is the key in the array)
+ ksort($migrations);
+
+ // Returh the list of migrations
+ return $migrations;
+
+ }
+
+ // Get the list of migrations for a specific module
+ protected function getPossibleMigrationsForModule($module=null) {
+
+ // Get the path to the migrations dir
+ $path = Yii::app()->basePath;
+ if (!empty($module)) {
+ $path .= '/modules/' . trim($module, '/');
+ }
+ $path .= '/' . self::MIGRATIONS_DIR;
+
+ // Start with an empty list
+ $migrations = array();
+
+ // Construct the list of migrations
+ $migrationFiles = CFileHelper::findFiles(
+ $path, array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
);
- foreach ($migrations as $key=>$migration) {
- $migrations[$key] = basename($migration, '.' . self::SCHEMA_EXT);
+ foreach ($migrationFiles as $migration) {
+ $migrations[$migration] = basename(
+ $migration, '.' . self::SCHEMA_EXT
+ );
}
+
+ // Return the list
return $migrations;
+
}
// Apply the migrations
protected function applyMigrations() {
+
+ // Get the list of applied and possible migrations
$applied = $this->getAppliedMigrations();
$possible = $this->getPossibleMigrations();
- foreach ($possible as $migration) {
+ // Loop over all possible migrations
+ foreach ($possible as $migrationFile => $migration) {
+
+ // Include the migration file
+ require($migrationFile);
+
+ // Create the migration instance
$migration = new $migration($this->adapter);
+
+ // Check if it's already applied to the database
if (!in_array($migration->getId(), $applied)) {
+
+ // Apply the migration to the database
$this->applyMigration($migration);
+
} else {
+
+ // Skip the already applied migration
echo(
'Skipping applied migration: ' . get_class($migration) . PHP_EOL
);
+
}
+
}
+
}
// Apply a specific migration
protected function applyMigration($migration) {
// Apply the migration
echo('Applying migration: ' . get_class($migration) . PHP_EOL);
// Create the migration instance
$migration->up();
// Commit the migration
- echo('Marking migration as applied: ' . get_class($migration) . PHP_EOL);
+ echo(
+ 'Marking migration as applied: ' . get_class($migration) . PHP_EOL
+ );
$cmd = Yii::app()->db->commandBuilder->createInsertCommand(
self::SCHEMA_TABLE,
array(self::SCHEMA_FIELD => $migration->getId())
)->execute();
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | 8302948ae4058cbc1b25ef6c9df887e0ceb1e4c9 | Removed some unneeded comments from the code. | diff --git a/CDbMigrationAdapter.php b/CDbMigrationAdapter.php
index bae07f6..2e1e730 100644
--- a/CDbMigrationAdapter.php
+++ b/CDbMigrationAdapter.php
@@ -1,145 +1,143 @@
<?php
/**
* CDbMigrationAdapter class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* @package extensions.yii-dbmigrations
*/
abstract class CDbMigrationAdapter {
// The database connection
public $db;
// Constructor
public function __construct(CDbConnection $db) {
$this->db = $db;
}
// Convert a type to a native database type
protected function convertToNativeType($theType) {
if (isset($this->nativeDatabaseTypes[$theType])) {
return $this->nativeDatabaseTypes[$theType];
} else {
return $theType;
}
}
// Convert the field information to native types
protected function convertFields($fields) {
$result = array();
foreach ($fields as $field) {
if (is_array($field)) {
if (isset($field[0])) {
$field[0] = $this->db->quoteColumnName($field[0]);
}
if (isset($field[1])) {
$field[1] = $this->convertToNativeType($field[1]);
}
$result[] = join(' ', $field);
} else {
$result[] = $this->db->quoteColumnName($field);
}
}
return join(', ', $result);
}
// Execute a raw SQL statement
public function execute($query, $params=array()) {
- //echo('SQL: ' . $query . PHP_EOL);
return $this->db->createCommand($query)->execute();
}
// Execute a raw SQL statement
public function query($query, $params=array()) {
- //echo('SQL: ' . $query . PHP_EOL);
return $this->db->createCommand($query)->queryAll();
}
// Get the column info
public function columnInfo($name) {
}
// Create a table
public function createTable($name, $columns=array(), $options=null) {
$sql = 'CREATE TABLE ' . $this->db->quoteTableName($name) . ' ('
. $this->convertFields($columns)
. ') ' . $options;
return $this->execute($sql);
}
// Rename a table
public function renameTable($name, $new_name) {
$sql = 'RENAME TABLE ' . $this->db->quoteTableName($name) . ' TO '
. $this->db->quoteTableName($new_name);
return $this->execute($sql);
}
// Drop a table
public function removeTable($name) {
$sql = 'DROP TABLE ' . $this->db->quoteTableName($name);
return $this->execute($sql);
}
// Add a database column
public function addColumn($table, $column, $type, $options=null) {
$type = $this->convertToNativeType($type);
if (empty($options)) {
$options = 'NOT NULL';
}
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD '
. $this->db->quoteColumnName($column) . ' ' . $type . ' '
. $options;
return $this->execute($sql);
}
// Change a database column
public function changeColumn($table, $column, $type, $options=null) {
$type = $this->convertToNativeType($type);
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
. $this->db->quoteColumnName($column) . ' '
. $this->db->quoteColumnName($column) . ' ' . $type . ' '
. $options;
return $this->execute($sql);
}
// Rename a database column
public function renameColumn($table, $name, $new_name) {
$type = $this->columnInfo($name);
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
. $this->db->quoteColumnName($name) . ' '
. $this->db->quoteColumnName($new_name) . ' ' . $type;
return $this->execute($sql);
}
// Remove a column
public function removeColumn($table, $column) {
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' DROP '
. $this->db->quoteColumnName($column);
return $this->execute($sql);
}
// Add an index
public function addIndex($table, $name, $columns, $unique=false) {
$sql = 'CREATE ';
$sql .= ($unique) ? 'UNIQUE ' : '';
$sql .= 'INDEX ' . $this->db->quoteColumnName($name) . ' ON '
. $this->db->quoteTableName($table) . ' ('
. $this->convertFields($columns)
. ')';
return $this->execute($sql);
}
// Remove an index
public function removeIndex($table, $name) {
$sql = 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON '
. $this->db->quoteTableName($table);
return $this->execute($sql);
}
}
diff --git a/samples/m20090611153243_CreateTables.php b/samples/m20090611153243_CreateTables.php
index 8c75809..708af1a 100644
--- a/samples/m20090611153243_CreateTables.php
+++ b/samples/m20090611153243_CreateTables.php
@@ -1,37 +1,26 @@
<?php
class m20090611153243_CreateTables extends CDbMigration {
public function up() {
- /*
- $tables = $this->query("show tables");
- $this->renameTable('test_table', 'posts');
- $this->removeIndex('test_table', 'idx_pk');
- $this->removeColumn('test_table', 'comment_id');
- $this->changeColumn('test_table', 'comment_id', 'boolean');
- $this->addColumn('test_table', 'title', 'string');
- $this->addIndex('posts', 'posts_sort', array('field1', 'field2'), true);
- $this->removeTable('test_table');
- */
-
$this->createTable(
'posts',
array(
array('id', 'primary_key'),
array('title', 'string'),
array('body', 'text'),
)
);
$this->addIndex(
'posts', 'posts_title', array('title')
);
}
public function down() {
$this->removeTable('posts');
}
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | d1cd622b5b1221bc7509f047e26214172cbb291f | Replaced the log function with echo statements. | diff --git a/CDbMigration.php b/CDbMigration.php
index bf36c5d..2f2593a 100644
--- a/CDbMigration.php
+++ b/CDbMigration.php
@@ -1,126 +1,121 @@
<?php
/**
* CDbMigration class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* @package extensions.yii-dbmigrations
*/
class CDbMigrationException extends Exception {}
/**
* @package extensions.yii-dbmigrations
*/
abstract class CDbMigration {
// The adapter to use
private $adapter;
// Constructor
public function __construct(CDbMigrationAdapter $adapter) {
$this->adapter = $adapter;
}
// Migrate up
public function up() {
}
// Migrate down
public function down() {
}
- // Helper for logging a message
- protected function log($msg) {
- echo(strftime('%Y-%m-%d %H:%M:%S') . ' ' . $msg . PHP_EOL);
- }
-
// Get the id of the migration
public function getId() {
$id = split('_', get_class($this));
return substr($id[0], 1);
}
// Get the name of the migration
public function getName() {
$name = split('_', get_class($this));
return $name[1];
}
// Execute a raw SQL statement
protected function execute($query, $params=array()) {
return $this->adapter->execute($query, $params);
}
// Execute a raw SQL statement
protected function query($query, $params=array()) {
return $this->adapter->query($query, $params);
}
// Create a table
protected function createTable($name, $columns=array(), $options=null) {
- $this->log(' >> Creating table: ' . $name);
+ echo(' >> Creating table: ' . $name . PHP_EOL);
return $this->adapter->createTable($name, $columns, $options);
}
// Rename a table
protected function renameTable($name, $new_name) {
- $this->log(' >> Renaming table: ' . $name . ' to: ' . $new_name);
+ echo(' >> Renaming table: ' . $name . ' to: ' . $new_name . PHP_EOL);
return $this->adapter->renameTable($name, $new_name);
}
// Drop a table
protected function removeTable($name) {
- $this->log(' >> Removing table: ' . $name);
+ echo(' >> Removing table: ' . $name . PHP_EOL);
return $this->adapter->removeTable($name);
}
// Add a database column
protected function addColumn($table, $column, $type, $options=null) {
- $this->log(' >> Adding column ' . $column . ' to table: ' . $table);
+ echo(' >> Adding column ' . $column . ' to table: ' . $table . PHP_EOL);
return $this->adapter->addColumn($table, $column, $type, $options);
}
// Rename a database column
protected function renameColumn($table, $name, $new_name) {
- $this->log(
+ echo(
' >> Renaming column ' . $name . ' to: ' . $new_name
- . ' in table: ' . $table
+ . ' in table: ' . $table . PHP_EOL
);
return $this->adapter->renameColumn($table, $name, $new_name);
}
// Change a database column
protected function changeColumn($table, $column, $type, $options=null) {
- $this->log(
+ echo(
' >> Chaning column ' . $name . ' to: ' . $type
- . ' in table: ' . $table
+ . ' in table: ' . $table . PHP_EOL
);
return $this->adapter->changeColumn($table, $column, $type, $options);
}
// Remove a column
protected function removeColumn($table, $column) {
- $this->log(
- ' >> Removing column ' . $column . ' from table: ' . $table
+ echo(
+ ' >> Removing column ' . $column . ' from table: ' . $table . PHP_EOL
);
return $this->adapter->removeColumn($table, $column);
}
// Add an index
public function addIndex($table, $name, $columns, $unique=false) {
- $this->log(' >> Adding index ' . $name . ' to table: ' . $table);
+ echo(' >> Adding index ' . $name . ' to table: ' . $table . PHP_EOL);
return $this->adapter->addIndex($table, $name, $columns, $unique);
}
// Remove an index
protected function removeIndex($table, $column) {
- $this->log(' >> Removing index ' . $name . ' from table: ' . $table);
+ echo(' >> Removing index ' . $name . ' from table: ' . $table . PHP_EOL);
return $this->adapter->removeIndex($table, $column);
}
}
\ No newline at end of file
diff --git a/CDbMigrationEngine.php b/CDbMigrationEngine.php
index e6575be..5a04346 100644
--- a/CDbMigrationEngine.php
+++ b/CDbMigrationEngine.php
@@ -1,186 +1,181 @@
<?php
/**
* CDbMigrationEngine class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the adapters we are going to use for the migrations.
*/
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* A database migration engine exception
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngineException extends Exception {}
/**
* The CDbMigrationEngine class is the actual engine that can do all the
* migrations related functionality.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngine {
// The migration adapter to use
private $adapter;
// The name of the table and column for the schema information
const SCHEMA_TABLE = 'schema_version';
const SCHEMA_FIELD = 'id';
const SCHEMA_EXT = 'php';
// Run the specified command
public function run($args) {
// Catch errors
try {
// Initialize the engine
$this->init();
// Check if we need to create a migration
if (isset($args[0]) && ($args[0] == 'create')) {
$this->create($args[0]);
} else {
$this->applyMigrations();
}
} catch (Exception $e) {
- $this->log('ERROR: ' . $e->getMessage());
+ echo('ERROR: ' . $e->getMessage() . PHP_EOL);
}
}
// Initialize the schema version table
protected function init() {
// Add the migrations directory to the search path
Yii::import('application.migrations.*');
// Check if a database connection was configured
try {
Yii::app()->db;
} catch (Exception $e) {
throw new CDbMigrationEngineException(
'Database configuration is missing in your configuration file.'
);
}
// Load the migration adapter
switch (Yii::app()->db->driverName) {
case 'mysql':
$this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
break;
case 'sqlite':
$this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
break;
default:
throw new CDbMigrationEngineException(
'Database of type ' . Yii::app()->db->driverName
. ' does not support migrations (yet).'
);
}
// Check if the schema version table exists
if (Yii::app()->db->schema->getTable('schema_version') == null) {
// Create the table
- $this->log('Creating initial schema_version table');
+ echo('Creating initial schema_version table' . PHP_EOL);
// Use the adapter to create the table
$this->adapter->createTable(
self::SCHEMA_TABLE,
array(
array(self::SCHEMA_FIELD, 'string'),
)
);
// Create an index on the column
$this->adapter->addIndex(
self::SCHEMA_TABLE,
'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
array(self::SCHEMA_FIELD),
true
);
}
}
// Get the list of migrations that are applied to the database
protected function getAppliedMigrations() {
// Get the field and table name
$field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
$table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
// Construct the SQL statement
$sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
// Get the list
return Yii::app()->db->createCommand($sql)->queryColumn(
self::SCHEMA_FIELD
);
}
// Get the list of possible migrations
protected function getPossibleMigrations() {
$migrations = CFileHelper::findFiles(
Yii::app()->basePath . '/migrations',
array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
);
foreach ($migrations as $key=>$migration) {
$migrations[$key] = basename($migration, '.' . self::SCHEMA_EXT);
}
return $migrations;
}
// Apply the migrations
protected function applyMigrations() {
$applied = $this->getAppliedMigrations();
$possible = $this->getPossibleMigrations();
foreach ($possible as $migration) {
$migration = new $migration($this->adapter);
if (!in_array($migration->getId(), $applied)) {
$this->applyMigration($migration);
} else {
- $this->log(
- 'Skipping applied migration: ' . get_class($migration)
+ echo(
+ 'Skipping applied migration: ' . get_class($migration) . PHP_EOL
);
}
}
}
// Apply a specific migration
protected function applyMigration($migration) {
// Apply the migration
- $this->log('Applying migration: ' . get_class($migration));
+ echo('Applying migration: ' . get_class($migration) . PHP_EOL);
// Create the migration instance
$migration->up();
// Commit the migration
- $this->log('Marking migration as applied: ' . get_class($migration));
+ echo('Marking migration as applied: ' . get_class($migration) . PHP_EOL);
$cmd = Yii::app()->db->commandBuilder->createInsertCommand(
self::SCHEMA_TABLE,
array(self::SCHEMA_FIELD => $migration->getId())
)->execute();
}
- // Helper for logging a message
- protected function log($msg) {
- echo($msg . PHP_EOL);
- }
-
}
\ No newline at end of file
|
elchingon/yii-dbmigrations | ea74fb64c5fe1be40587e034dd4faab3aad5e1e9 | Removed the timestamps from the logs. | diff --git a/CDbMigrationEngine.php b/CDbMigrationEngine.php
index 6157be6..e6575be 100644
--- a/CDbMigrationEngine.php
+++ b/CDbMigrationEngine.php
@@ -1,186 +1,186 @@
<?php
/**
* CDbMigrationEngine class file.
*
* @author Pieter Claerhout <[email protected]>
* @link http://github.com/pieterclaerhout/yii-dbmigrations/
* @copyright Copyright © 2009 Pieter Claerhout
*/
/**
* Import the adapters we are going to use for the migrations.
*/
Yii::import('application.extensions.yii-dbmigrations.adapters.*');
/**
* A database migration engine exception
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngineException extends Exception {}
/**
* The CDbMigrationEngine class is the actual engine that can do all the
* migrations related functionality.
*
* @package extensions.yii-dbmigrations
*/
class CDbMigrationEngine {
// The migration adapter to use
private $adapter;
// The name of the table and column for the schema information
const SCHEMA_TABLE = 'schema_version';
const SCHEMA_FIELD = 'id';
const SCHEMA_EXT = 'php';
// Run the specified command
public function run($args) {
// Catch errors
try {
// Initialize the engine
$this->init();
// Check if we need to create a migration
if (isset($args[0]) && ($args[0] == 'create')) {
$this->create($args[0]);
} else {
$this->applyMigrations();
}
} catch (Exception $e) {
$this->log('ERROR: ' . $e->getMessage());
}
}
// Initialize the schema version table
protected function init() {
// Add the migrations directory to the search path
Yii::import('application.migrations.*');
// Check if a database connection was configured
try {
Yii::app()->db;
} catch (Exception $e) {
throw new CDbMigrationEngineException(
'Database configuration is missing in your configuration file.'
);
}
// Load the migration adapter
switch (Yii::app()->db->driverName) {
case 'mysql':
$this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
break;
case 'sqlite':
$this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
break;
default:
throw new CDbMigrationEngineException(
'Database of type ' . Yii::app()->db->driverName
. ' does not support migrations (yet).'
);
}
// Check if the schema version table exists
if (Yii::app()->db->schema->getTable('schema_version') == null) {
// Create the table
$this->log('Creating initial schema_version table');
// Use the adapter to create the table
$this->adapter->createTable(
self::SCHEMA_TABLE,
array(
array(self::SCHEMA_FIELD, 'string'),
)
);
// Create an index on the column
$this->adapter->addIndex(
self::SCHEMA_TABLE,
'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
array(self::SCHEMA_FIELD),
true
);
}
}
// Get the list of migrations that are applied to the database
protected function getAppliedMigrations() {
// Get the field and table name
$field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
$table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
// Construct the SQL statement
$sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
// Get the list
return Yii::app()->db->createCommand($sql)->queryColumn(
self::SCHEMA_FIELD
);
}
// Get the list of possible migrations
protected function getPossibleMigrations() {
$migrations = CFileHelper::findFiles(
Yii::app()->basePath . '/migrations',
array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
);
foreach ($migrations as $key=>$migration) {
$migrations[$key] = basename($migration, '.' . self::SCHEMA_EXT);
}
return $migrations;
}
// Apply the migrations
protected function applyMigrations() {
$applied = $this->getAppliedMigrations();
$possible = $this->getPossibleMigrations();
foreach ($possible as $migration) {
$migration = new $migration($this->adapter);
if (!in_array($migration->getId(), $applied)) {
$this->applyMigration($migration);
} else {
$this->log(
'Skipping applied migration: ' . get_class($migration)
);
}
}
}
// Apply a specific migration
protected function applyMigration($migration) {
// Apply the migration
$this->log('Applying migration: ' . get_class($migration));
// Create the migration instance
$migration->up();
// Commit the migration
$this->log('Marking migration as applied: ' . get_class($migration));
$cmd = Yii::app()->db->commandBuilder->createInsertCommand(
self::SCHEMA_TABLE,
array(self::SCHEMA_FIELD => $migration->getId())
)->execute();
}
// Helper for logging a message
protected function log($msg) {
- echo(strftime('%Y-%m-%d %H:%M:%S') . ' ' . $msg . PHP_EOL);
+ echo($msg . PHP_EOL);
}
}
\ No newline at end of file
diff --git a/README.textile b/README.textile
index acb3d86..2a81357 100644
--- a/README.textile
+++ b/README.textile
@@ -1,191 +1,191 @@
h1. Yii DB Migrations
A database migrations engine for the Yii framework. It comes in the form of an
extension which can be dropped into any existing Yii framework application.
It relies on the database abstraction layer of the Yii framework to talk to the
database engine.
It's largely inspired on the migrations functionality of the Ruby on Rails
framework.
h2. Current limitations
Be aware that the current version is still very alpha.
There are only two database engines supported:
* MySQL
* SQLite
In the current version, it's only possible to migrate up, it cannot (yet) remove
already installed migrations.
h2. Installing the extension
h3. Putting the files in the right location
Installing the extension is quite easy. Once you downloaded the files from
github, you need to put all the files in a folder called "yii-dbmigrations" and
put it in the <code>protected/extensions</code> folder from your project.
h3. Configuring the database connection
You need to make sure you configure database access properly in the
configuration file of your project. As the console applications in the Yii
framework look at the <code>protected/config/console.php</code> file, you need
to make sure you configure the <code>db</code> settings under the
<code>components</code> key in the configuration array. For MySQL, the
configuration will look as follows:
<pre>
'components' => array(
'db'=>array(
'class' => 'CDbConnection',
'connectionString'=>'mysql:host=localhost;dbname=my_db',
'charset' => 'UTF8',
'username'=>'root',
'password'=>'root',
),
),
</pre>
For SQLite, the configuration looks as follows:
<pre>
'components' => array(
'db'=>array(
'connectionString'=>'sqlite:'.dirname(__FILE__).'/../data/my_db.db',
),
),
</pre>
h3. Configuring the command map
To make the <code>yiic</code> tool know about the <code>migrate</code> command,
you need to add a <code>commandMap</code> key to the application configuration.
In there, you need to put the following configuration:
<pre>
'commandMap' => array(
'migrate' => array(
'class'=>'application.extensions.yii-dbmigrations.CDbMigrationCommand',
),
),
</pre>
h3. Testing your installation
To test if the installation was succesfull, you can run the yiic command and
should see the following output:
<pre>
Yii command runner (based on Yii v1.0.6)
Usage: protected/yiic <command-name> [parameters...]
The following commands are available:
- migrate
- message
- shell
- webapp
To see individual command help, use the following:
protected/yiic help <command-name>
</pre>
It should mention that the <code>migrate</code> command is available.
h2. Creating migrations
You can create migrations by creating files in the
<code>protected/migrations</code> folder. The file names for the migrations
should follow a specific naming convention:
<pre>
m20090614213453_MigrationName.php
</pre>
The migration file names always start with the letter m followed by 14 digit
timestamp and an underscore. After that, you can give a name to the migration so
that you can easily identify the migration.
In the migration file, you need to create a class that extends the parent class
<code>CDbMigration</code>. The <code>CDbMigration</code> class needs to have the
<code>up</code> and <code>down</code> methods as you can see in the following
sample migration:
<pre>
class m20090611153243_CreateTables extends CDbMigration {
public function up() {
$this->createTable(
'posts',
array(
array('id', 'primary_key'),
array('title', 'string'),
array('body', 'text'),
)
);
$this->addIndex(
'posts', 'posts_title', array('title')
);
}
public function down() {
$this->removeTable('posts');
}
}
</pre>
h2. Applying migrations
Once you created the migrations, you can apply them to your database by running
the <code>migrate</code> command:
<pre>
protected/yiic migrate
</pre>
You will see the following output:
<pre>
-2009-06-14 21:42:04 Creating initial schema_version table
-2009-06-14 21:42:04 Applying migration: m20090611153243_CreateTables
-2009-06-14 21:42:04 >> Creating table: posts
-2009-06-14 21:42:04 >> Adding index posts_title to table: posts
-2009-06-14 21:42:04 Marking migration as applied: m20090611153243_CreateTables
-2009-06-14 21:42:04 Applying migration: m20090612162832_CreateTags
-2009-06-14 21:42:04 >> Creating table: tags
-2009-06-14 21:42:04 >> Creating table: post_tags
-2009-06-14 21:42:04 >> Adding index post_tags_post_tag to table: post_tags
-2009-06-14 21:42:04 Marking migration as applied: m20090612162832_CreateTags
-2009-06-14 21:42:04 Applying migration: m20090612163144_RenameTagsTable
-2009-06-14 21:42:04 >> Renaming table: post_tags to: post_tags_link_table
-2009-06-14 21:42:04 Marking migration as applied: m20090612163144_RenameTagsTable
+Creating initial schema_version table
+Applying migration: m20090611153243_CreateTables
+ >> Creating table: posts
+ >> Adding index posts_title to table: posts
+Marking migration as applied: m20090611153243_CreateTables
+Applying migration: m20090612162832_CreateTags
+ >> Creating table: tags
+ >> Creating table: post_tags
+ >> Adding index post_tags_post_tag to table: post_tags
+Marking migration as applied: m20090612162832_CreateTags
+Applying migration: m20090612163144_RenameTagsTable
+ >> Renaming table: post_tags to: post_tags_link_table
+Marking migration as applied: m20090612163144_RenameTagsTable
</pre>
It will apply all the migrations found in the
<code>protected/migrations</code> directory provided they were not applied to
the database yet.
If you run the <code>migrate</code> command again, it will show that the
migrations were applied already:
<pre>
-2009-06-14 21:44:09 Skipping applied migration: m20090611153243_CreateTables
-2009-06-14 21:44:09 Skipping applied migration: m20090612162832_CreateTags
-2009-06-14 21:44:09 Skipping applied migration: m20090612163144_RenameTagsTable
+Skipping applied migration: m20090611153243_CreateTables
+Skipping applied migration: m20090612162832_CreateTags
+Skipping applied migration: m20090612163144_RenameTagsTable
</pre>
h3. Author information
This extension is created and maintained by Pieter Claerhout. You can contact
the author on:
* Website: http://www.yellowduck.be
* Twitter: http://twitter.com/pieterclaerhout
* Github: http://github.com/pieterclaerhout/yii-dbmigrations/tree/master
|
elchingon/yii-dbmigrations | 5c130a057fb84d96726ffddf3badead7b3378e90 | Started adding docstrings. Added the CDbMigration class. Moved the adapters to a subdirectory. | diff --git a/CDbMigration.php b/CDbMigration.php
index f1bad11..1bf555b 100644
--- a/CDbMigration.php
+++ b/CDbMigration.php
@@ -1,113 +1,122 @@
<?php
+/**
+ * CDbMigration class file.
+ *
+ * @author Pieter Claerhout <[email protected]>
+ * @link http://github.com/pieterclaerhout/yii-dbmigrations/
+ * @copyright Copyright © 2009 Pieter Claerhout
+ * @package dbmigrations
+ */
+
class CDbMigrationException extends Exception {}
// Class implementing a migration
abstract class CDbMigration {
// The adapter to use
private $adapter;
// Constructor
public function __construct(CDbMigrationAdapter $adapter) {
$this->adapter = $adapter;
}
// Migrate up
public function up() {
}
// Migrate down
public function down() {
}
// Helper for logging a message
protected function log($msg) {
echo(strftime('%Y-%m-%d %H:%M:%S') . ' ' . $msg . PHP_EOL);
}
// Get the id of the migration
public function getId() {
$id = split('_', get_class($this));
return substr($id[0], 1);
}
// Get the name of the migration
public function getName() {
$name = split('_', get_class($this));
return $name[1];
}
// Execute a raw SQL statement
protected function execute($query, $params=array()) {
return $this->adapter->execute($query, $params);
}
// Execute a raw SQL statement
protected function query($query, $params=array()) {
return $this->adapter->query($query, $params);
}
// Create a table
protected function createTable($name, $columns=array(), $options=null) {
$this->log(' >> Creating table: ' . $name);
return $this->adapter->createTable($name, $columns, $options);
}
// Rename a table
protected function renameTable($name, $new_name) {
$this->log(' >> Renaming table: ' . $name . ' to: ' . $new_name);
return $this->adapter->renameTable($name, $new_name);
}
// Drop a table
protected function removeTable($name) {
$this->log(' >> Removing table: ' . $name);
return $this->adapter->removeTable($name);
}
// Add a database column
protected function addColumn($table, $column, $type, $options=null) {
$this->log(' >> Adding column ' . $column . ' to table: ' . $table);
return $this->adapter->addColumn($table, $column, $type, $options);
}
// Rename a database column
protected function renameColumn($table, $name, $new_name) {
$this->log(
' >> Renaming column ' . $name . ' to: ' . $new_name
. ' in table: ' . $table
);
return $this->adapter->renameColumn($table, $name, $new_name);
}
// Change a database column
protected function changeColumn($table, $column, $type, $options=null) {
$this->log(
' >> Chaning column ' . $name . ' to: ' . $type
. ' in table: ' . $table
);
return $this->adapter->changeColumn($table, $column, $type, $options);
}
// Remove a column
protected function removeColumn($table, $column) {
$this->log(
' >> Removing column ' . $column . ' from table: ' . $table
);
return $this->adapter->removeColumn($table, $column);
}
// Add an index
public function addIndex($table, $name, $columns, $unique=false) {
$this->log(' >> Adding index ' . $name . ' to table: ' . $table);
return $this->adapter->addIndex($table, $name, $columns, $unique);
}
// Remove an index
protected function removeIndex($table, $column) {
$this->log(' >> Removing index ' . $name . ' from table: ' . $table);
return $this->adapter->removeIndex($table, $column);
}
}
\ No newline at end of file
diff --git a/CDbMigrationAdapter.php b/CDbMigrationAdapter.php
index 8ce5275..6546400 100644
--- a/CDbMigrationAdapter.php
+++ b/CDbMigrationAdapter.php
@@ -1,135 +1,144 @@
<?php
+/**
+ * CDbMigrationAdapter class file.
+ *
+ * @author Pieter Claerhout <[email protected]>
+ * @link http://github.com/pieterclaerhout/yii-dbmigrations/
+ * @copyright Copyright © 2009 Pieter Claerhout
+ * @package dbmigrations
+ */
+
// A database specific version of a migration adapter
abstract class CDbMigrationAdapter {
// The database connection
public $db;
// Constructor
public function __construct(CDbConnection $db) {
$this->db = $db;
}
// Convert a type to a native database type
protected function convertToNativeType($theType) {
if (isset($this->nativeDatabaseTypes[$theType])) {
return $this->nativeDatabaseTypes[$theType];
} else {
return $theType;
}
}
// Convert the field information to native types
protected function convertFields($fields) {
$result = array();
foreach ($fields as $field) {
if (is_array($field)) {
if (isset($field[0])) {
$field[0] = $this->db->quoteColumnName($field[0]);
}
if (isset($field[1])) {
$field[1] = $this->convertToNativeType($field[1]);
}
$result[] = join(' ', $field);
} else {
$result[] = $this->db->quoteColumnName($field);
}
}
return join(', ', $result);
}
// Execute a raw SQL statement
public function execute($query, $params=array()) {
//echo('SQL: ' . $query . PHP_EOL);
return $this->db->createCommand($query)->execute();
}
// Execute a raw SQL statement
public function query($query, $params=array()) {
//echo('SQL: ' . $query . PHP_EOL);
return $this->db->createCommand($query)->queryAll();
}
// Get the column info
public function columnInfo($name) {
}
// Create a table
public function createTable($name, $columns=array(), $options=null) {
$sql = 'CREATE TABLE ' . $this->db->quoteTableName($name) . ' ('
. $this->convertFields($columns)
. ') ' . $options;
return $this->execute($sql);
}
// Rename a table
public function renameTable($name, $new_name) {
$sql = 'RENAME TABLE ' . $this->db->quoteTableName($name) . ' TO '
. $this->db->quoteTableName($new_name);
return $this->execute($sql);
}
// Drop a table
public function removeTable($name) {
$sql = 'DROP TABLE ' . $this->db->quoteTableName($name);
return $this->execute($sql);
}
// Add a database column
public function addColumn($table, $column, $type, $options=null) {
$type = $this->convertToNativeType($type);
if (empty($options)) {
$options = 'NOT NULL';
}
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD '
. $this->db->quoteColumnName($column) . ' ' . $type . ' '
. $options;
return $this->execute($sql);
}
// Change a database column
public function changeColumn($table, $column, $type, $options=null) {
$type = $this->convertToNativeType($type);
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
. $this->db->quoteColumnName($column) . ' '
. $this->db->quoteColumnName($column) . ' ' . $type . ' '
. $options;
return $this->execute($sql);
}
// Rename a database column
public function renameColumn($table, $name, $new_name) {
$type = $this->columnInfo($name);
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
. $this->db->quoteColumnName($name) . ' '
. $this->db->quoteColumnName($new_name) . ' ' . $type;
return $this->execute($sql);
}
// Remove a column
public function removeColumn($table, $column) {
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' DROP '
. $this->db->quoteColumnName($column);
return $this->execute($sql);
}
// Add an index
public function addIndex($table, $name, $columns, $unique=false) {
$sql = 'CREATE ';
$sql .= ($unique) ? 'UNIQUE ' : '';
$sql .= 'INDEX ' . $this->db->quoteColumnName($name) . ' ON '
. $this->db->quoteTableName($table) . ' ('
. $this->convertFields($columns)
. ')';
return $this->execute($sql);
}
// Remove an index
public function removeIndex($table, $name) {
$sql = 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON '
. $this->db->quoteTableName($table);
return $this->execute($sql);
}
}
diff --git a/CDbMigrationCommand.php b/CDbMigrationCommand.php
index e5feee0..31932d5 100644
--- a/CDbMigrationCommand.php
+++ b/CDbMigrationCommand.php
@@ -1,169 +1,42 @@
<?php
-// Import the main classes
+/**
+ * CDbMigrationCommand class file.
+ *
+ * @author Pieter Claerhout <[email protected]>
+ * @link http://github.com/pieterclaerhout/yii-dbmigrations/
+ * @copyright Copyright © 2009 Pieter Claerhout
+ */
+
+/**
+ * Import the different extension components.
+ */
Yii::import('application.extensions.yii-dbmigrations.*');
+Yii::import('application.extensions.yii-dbmigrations.adapters.*');
-// The migration command
+/**
+ * This class creates the migrate console command so that you can use it with
+ * the yiic tool inside your project.
+ *
+ * @package extensions.yii-dbmigrations
+ */
class CDbMigrationCommand extends CConsoleCommand {
- // The migration adapter to use
- private $adapter;
-
- // The name of the table and column for the schema information
- const SCHEMA_TABLE = 'schema_version';
- const SCHEMA_FIELD = 'id';
- const SCHEMA_EXT = 'php';
-
- // Get the command help
+ /**
+ * Return the help for the migrate command.
+ */
public function getHelp() {
return 'Used to run database migrations';
}
- // Run the command
+ /**
+ * Runs the actual command passing along the command line parameters.
+ *
+ * @param $args The command line parameters
+ */
public function run($args) {
-
- // Catch errors
- try {
-
- // Initialize
- $this->init();
-
- // Check if we need to create a migration
- if (isset($args[0]) && ($args[0] == 'create')) {
- $this->create($args[0]);
- } else {
- $this->applyMigrations();
- }
-
- } catch (Exception $e) {
-
- // Log the error
- $this->log('-----');
- $this->log('SOMETHING WENT TERRIBLY WRONG:');
- $this->log($e->getMessage());
-
- }
-
- }
-
- // Create a migration
- protected function create($migration) {
- }
-
- // Initialize the schema version table
- protected function init() {
-
- // Add the migrations directory to the search path
- Yii::import('application.migrations.*');
-
- // Load the migration adapter
- switch (Yii::app()->db->driverName) {
- case 'mysql':
- $this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
- break;
- case 'sqlite':
- $this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
- break;
- default:
- throw new CDbMigrationException(
- 'Database of type ' . Yii::app()->db->driverName
- . ' does not support migrations (yet).'
- );
- }
-
- // Check if the schema version table exists
- if (Yii::app()->db->schema->getTable('schema_version') == null) {
-
- // Create the table
- $this->log('Creating initial schema_version table');
-
- // Use the adapter to create the table
- $this->adapter->createTable(
- self::SCHEMA_TABLE,
- array(
- array(self::SCHEMA_FIELD, 'string'),
- )
- );
-
- // Create an index on the column
- $this->adapter->addIndex(
- self::SCHEMA_TABLE,
- 'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
- array(self::SCHEMA_FIELD),
- true
- );
-
- }
-
- }
-
- // Get the list of migrations that are applied to the database
- protected function getAppliedMigrations() {
-
- // Get the field and table name
- $field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
- $table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
-
- // Construct the SQL statement
- $sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
-
- // Get the list
- return Yii::app()->db->createCommand($sql)->queryColumn(
- self::SCHEMA_FIELD
- );
-
- }
-
- // Get the list of possible migrations
- protected function getPossibleMigrations() {
- $migrations = CFileHelper::findFiles(
- Yii::app()->basePath . '/migrations',
- array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
- );
- foreach ($migrations as $key=>$migration) {
- $migrations[$key] = basename($migration, '.' . self::SCHEMA_EXT);
- }
- return $migrations;
- }
-
- // Apply the migrations
- protected function applyMigrations() {
- $applied = $this->getAppliedMigrations();
- $possible = $this->getPossibleMigrations();
-
- foreach ($possible as $migration) {
- $migration = new $migration($this->adapter);
- if (!in_array($migration->getId(), $applied)) {
- $this->applyMigration($migration);
- } else {
- $this->log(
- 'Skipping applied migration: ' . get_class($migration)
- );
- }
- }
- }
-
- // Apply a specific migration
- protected function applyMigration($migration) {
-
- // Apply the migration
- $this->log('Applying migration: ' . get_class($migration));
-
- // Create the migration instance
- $migration->up();
-
- // Commit the migration
- $this->log('Marking migration as applied: ' . get_class($migration));
- $cmd = Yii::app()->db->commandBuilder->createInsertCommand(
- self::SCHEMA_TABLE,
- array(self::SCHEMA_FIELD => $migration->getId())
- )->execute();
-
- }
-
- // Helper for logging a message
- protected function log($msg) {
- echo(strftime('%Y-%m-%d %H:%M:%S') . ' ' . $msg . PHP_EOL);
+ $engine = new CDbMigrationEngine();
+ $engine->run($args);
}
}
\ No newline at end of file
diff --git a/CDbMigrationEngine.php b/CDbMigrationEngine.php
new file mode 100644
index 0000000..2f35930
--- /dev/null
+++ b/CDbMigrationEngine.php
@@ -0,0 +1,174 @@
+<?php
+
+/**
+ * CDbMigrationEngine class file.
+ *
+ * @author Pieter Claerhout <[email protected]>
+ * @link http://github.com/pieterclaerhout/yii-dbmigrations/
+ * @copyright Copyright © 2009 Pieter Claerhout
+ * @package dbmigrations
+ */
+
+/**
+ * Import the adapters we are going to use for the migrations.
+ */
+Yii::import('application.extensions.yii-dbmigrations.adapters.*');
+
+/**
+ * The CDbMigrationEngine class is the actual engine that can do all the
+ * migrations related functionality.
+ */
+class CDbMigrationEngine {
+
+ // The migration adapter to use
+ private $adapter;
+
+ // The name of the table and column for the schema information
+ const SCHEMA_TABLE = 'schema_version';
+ const SCHEMA_FIELD = 'id';
+ const SCHEMA_EXT = 'php';
+
+ // Run the specified command
+ public function run($args) {
+
+ // Catch errors
+ try {
+
+ // Initialize the engine
+ $this->init();
+
+ // Check if we need to create a migration
+ if (isset($args[0]) && ($args[0] == 'create')) {
+ $this->create($args[0]);
+ } else {
+ $this->applyMigrations();
+ }
+
+ } catch (Exception $e) {
+
+ // Log the error
+ $this->log('-----');
+ $this->log('SOMETHING WENT TERRIBLY WRONG:');
+ $this->log($e->getMessage());
+
+ }
+
+ }
+
+ // Initialize the schema version table
+ protected function init() {
+
+ // Add the migrations directory to the search path
+ Yii::import('application.migrations.*');
+
+ // Load the migration adapter
+ switch (Yii::app()->db->driverName) {
+ case 'mysql':
+ $this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
+ break;
+ case 'sqlite':
+ $this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
+ break;
+ default:
+ throw new CDbMigrationException(
+ 'Database of type ' . Yii::app()->db->driverName
+ . ' does not support migrations (yet).'
+ );
+ }
+
+ // Check if the schema version table exists
+ if (Yii::app()->db->schema->getTable('schema_version') == null) {
+
+ // Create the table
+ $this->log('Creating initial schema_version table');
+
+ // Use the adapter to create the table
+ $this->adapter->createTable(
+ self::SCHEMA_TABLE,
+ array(
+ array(self::SCHEMA_FIELD, 'string'),
+ )
+ );
+
+ // Create an index on the column
+ $this->adapter->addIndex(
+ self::SCHEMA_TABLE,
+ 'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
+ array(self::SCHEMA_FIELD),
+ true
+ );
+
+ }
+
+ }
+
+ // Get the list of migrations that are applied to the database
+ protected function getAppliedMigrations() {
+
+ // Get the field and table name
+ $field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
+ $table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
+
+ // Construct the SQL statement
+ $sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
+
+ // Get the list
+ return Yii::app()->db->createCommand($sql)->queryColumn(
+ self::SCHEMA_FIELD
+ );
+
+ }
+
+ // Get the list of possible migrations
+ protected function getPossibleMigrations() {
+ $migrations = CFileHelper::findFiles(
+ Yii::app()->basePath . '/migrations',
+ array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
+ );
+ foreach ($migrations as $key=>$migration) {
+ $migrations[$key] = basename($migration, '.' . self::SCHEMA_EXT);
+ }
+ return $migrations;
+ }
+
+ // Apply the migrations
+ protected function applyMigrations() {
+ $applied = $this->getAppliedMigrations();
+ $possible = $this->getPossibleMigrations();
+
+ foreach ($possible as $migration) {
+ $migration = new $migration($this->adapter);
+ if (!in_array($migration->getId(), $applied)) {
+ $this->applyMigration($migration);
+ } else {
+ $this->log(
+ 'Skipping applied migration: ' . get_class($migration)
+ );
+ }
+ }
+ }
+
+ // Apply a specific migration
+ protected function applyMigration($migration) {
+
+ // Apply the migration
+ $this->log('Applying migration: ' . get_class($migration));
+
+ // Create the migration instance
+ $migration->up();
+
+ // Commit the migration
+ $this->log('Marking migration as applied: ' . get_class($migration));
+ $cmd = Yii::app()->db->commandBuilder->createInsertCommand(
+ self::SCHEMA_TABLE,
+ array(self::SCHEMA_FIELD => $migration->getId())
+ )->execute();
+
+ }
+
+ // Helper for logging a message
+ protected function log($msg) {
+ echo(strftime('%Y-%m-%d %H:%M:%S') . ' ' . $msg . PHP_EOL);
+ }
+
+}
\ No newline at end of file
diff --git a/CDbMigrationAdapterMysql.php b/adapters/CDbMigrationAdapterMysql.php
similarity index 72%
rename from CDbMigrationAdapterMysql.php
rename to adapters/CDbMigrationAdapterMysql.php
index ea55d29..ccb036a 100644
--- a/CDbMigrationAdapterMysql.php
+++ b/adapters/CDbMigrationAdapterMysql.php
@@ -1,22 +1,31 @@
<?php
+/**
+ * CDbMigrationAdapterMysql class file.
+ *
+ * @author Pieter Claerhout <[email protected]>
+ * @link http://github.com/pieterclaerhout/yii-dbmigrations/
+ * @copyright Copyright © 2009 Pieter Claerhout
+ * @package dbmigrations
+ */
+
class CDbMigrationAdapterMysql extends CDbMigrationAdapter {
// Return a map of the native database types
protected $nativeDatabaseTypes = array(
'primary_key' => 'int(11) DEFAULT NULL auto_increment PRIMARY KEY',
'string' => 'varchar(255)',
'text' => 'text',
'integer' => 'int(4)',
'float' => 'float',
'decimal' => 'decimal',
'datetime' => 'datetime',
'timestamp' => 'datetime',
'time' => 'time',
'date' => 'date',
'binary' => 'blob',
'boolean' => 'tinyint(1)',
'bool' => 'tinyint(1)',
);
}
diff --git a/CDbMigrationAdapterSqlite.php b/adapters/CDbMigrationAdapterSqlite.php
similarity index 86%
rename from CDbMigrationAdapterSqlite.php
rename to adapters/CDbMigrationAdapterSqlite.php
index a76979b..200ed7e 100644
--- a/CDbMigrationAdapterSqlite.php
+++ b/adapters/CDbMigrationAdapterSqlite.php
@@ -1,50 +1,59 @@
<?php
+/**
+ * CDbMigrationAdapterSqlite class file.
+ *
+ * @author Pieter Claerhout <[email protected]>
+ * @link http://github.com/pieterclaerhout/yii-dbmigrations/
+ * @copyright Copyright © 2009 Pieter Claerhout
+ * @package dbmigrations
+ */
+
class CDbMigrationAdapterSqlite extends CDbMigrationAdapter {
// Return a map of the native database types
protected $nativeDatabaseTypes = array(
'primary_key' => 'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL',
'string' => 'varchar(255)',
'text' => 'text',
'integer' => 'integer',
'float' => 'float',
'decimal' => 'decimal',
'datetime' => 'datetime',
'timestamp' => 'datetime',
'time' => 'time',
'date' => 'date',
'binary' => 'blob',
'boolean' => 'tinyint(1)',
'bool' => 'tinyint(1)',
);
// Rename a table
public function renameTable($name, $new_name) {
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($name) . ' RENAME TO '
. $this->db->quoteTableName($new_name);
return $this->execute($sql);
}
// Change a database column
public function changeColumn($table, $column, $type, $options=null) {
throw new CDbMigrationException(
'changeColumn is not supported for SQLite'
);
}
// Change a database column
public function renameColumn($table, $name, $new_name) {
throw new CDbMigrationException(
'renameColumn is not supported for SQLite'
);
}
// Remove a column
public function removeColumn($table, $column) {
throw new CDbMigrationException(
'removeColumn is not supported for SQLite'
);
}
}
|
elchingon/yii-dbmigrations | 61846ef298c2730e098c09e2a2336bc954506e03 | Added a link to the github page. | diff --git a/README.textile b/README.textile
index b68ebe9..acb3d86 100644
--- a/README.textile
+++ b/README.textile
@@ -1,191 +1,191 @@
h1. Yii DB Migrations
A database migrations engine for the Yii framework. It comes in the form of an
extension which can be dropped into any existing Yii framework application.
It relies on the database abstraction layer of the Yii framework to talk to the
database engine.
It's largely inspired on the migrations functionality of the Ruby on Rails
framework.
h2. Current limitations
Be aware that the current version is still very alpha.
There are only two database engines supported:
* MySQL
* SQLite
In the current version, it's only possible to migrate up, it cannot (yet) remove
already installed migrations.
h2. Installing the extension
h3. Putting the files in the right location
Installing the extension is quite easy. Once you downloaded the files from
github, you need to put all the files in a folder called "yii-dbmigrations" and
put it in the <code>protected/extensions</code> folder from your project.
h3. Configuring the database connection
You need to make sure you configure database access properly in the
configuration file of your project. As the console applications in the Yii
framework look at the <code>protected/config/console.php</code> file, you need
to make sure you configure the <code>db</code> settings under the
<code>components</code> key in the configuration array. For MySQL, the
configuration will look as follows:
<pre>
'components' => array(
'db'=>array(
'class' => 'CDbConnection',
'connectionString'=>'mysql:host=localhost;dbname=my_db',
'charset' => 'UTF8',
'username'=>'root',
'password'=>'root',
),
),
</pre>
For SQLite, the configuration looks as follows:
<pre>
'components' => array(
'db'=>array(
'connectionString'=>'sqlite:'.dirname(__FILE__).'/../data/my_db.db',
),
),
</pre>
h3. Configuring the command map
To make the <code>yiic</code> tool know about the <code>migrate</code> command,
you need to add a <code>commandMap</code> key to the application configuration.
In there, you need to put the following configuration:
<pre>
'commandMap' => array(
'migrate' => array(
'class'=>'application.extensions.yii-dbmigrations.CDbMigrationCommand',
),
),
</pre>
h3. Testing your installation
To test if the installation was succesfull, you can run the yiic command and
should see the following output:
<pre>
Yii command runner (based on Yii v1.0.6)
Usage: protected/yiic <command-name> [parameters...]
The following commands are available:
- migrate
- message
- shell
- webapp
To see individual command help, use the following:
protected/yiic help <command-name>
</pre>
It should mention that the <code>migrate</code> command is available.
h2. Creating migrations
You can create migrations by creating files in the
<code>protected/migrations</code> folder. The file names for the migrations
should follow a specific naming convention:
<pre>
m20090614213453_MigrationName.php
</pre>
The migration file names always start with the letter m followed by 14 digit
timestamp and an underscore. After that, you can give a name to the migration so
that you can easily identify the migration.
In the migration file, you need to create a class that extends the parent class
<code>CDbMigration</code>. The <code>CDbMigration</code> class needs to have the
<code>up</code> and <code>down</code> methods as you can see in the following
sample migration:
<pre>
class m20090611153243_CreateTables extends CDbMigration {
public function up() {
$this->createTable(
'posts',
array(
array('id', 'primary_key'),
array('title', 'string'),
array('body', 'text'),
)
);
$this->addIndex(
'posts', 'posts_title', array('title')
);
}
public function down() {
$this->removeTable('posts');
}
}
</pre>
h2. Applying migrations
Once you created the migrations, you can apply them to your database by running
the <code>migrate</code> command:
<pre>
protected/yiic migrate
</pre>
You will see the following output:
<pre>
2009-06-14 21:42:04 Creating initial schema_version table
2009-06-14 21:42:04 Applying migration: m20090611153243_CreateTables
2009-06-14 21:42:04 >> Creating table: posts
2009-06-14 21:42:04 >> Adding index posts_title to table: posts
2009-06-14 21:42:04 Marking migration as applied: m20090611153243_CreateTables
2009-06-14 21:42:04 Applying migration: m20090612162832_CreateTags
2009-06-14 21:42:04 >> Creating table: tags
2009-06-14 21:42:04 >> Creating table: post_tags
2009-06-14 21:42:04 >> Adding index post_tags_post_tag to table: post_tags
2009-06-14 21:42:04 Marking migration as applied: m20090612162832_CreateTags
2009-06-14 21:42:04 Applying migration: m20090612163144_RenameTagsTable
2009-06-14 21:42:04 >> Renaming table: post_tags to: post_tags_link_table
2009-06-14 21:42:04 Marking migration as applied: m20090612163144_RenameTagsTable
</pre>
It will apply all the migrations found in the
<code>protected/migrations</code> directory provided they were not applied to
the database yet.
If you run the <code>migrate</code> command again, it will show that the
migrations were applied already:
<pre>
2009-06-14 21:44:09 Skipping applied migration: m20090611153243_CreateTables
2009-06-14 21:44:09 Skipping applied migration: m20090612162832_CreateTags
2009-06-14 21:44:09 Skipping applied migration: m20090612163144_RenameTagsTable
</pre>
h3. Author information
This extension is created and maintained by Pieter Claerhout. You can contact
the author on:
* Website: http://www.yellowduck.be
* Twitter: http://twitter.com/pieterclaerhout
-
+* Github: http://github.com/pieterclaerhout/yii-dbmigrations/tree/master
|
elchingon/yii-dbmigrations | e0a3267195a0d90ef1132dacf23d5ab9573ad560 | Added demo files. Updated the readme file. | diff --git a/CDbMigrationCommand.php b/CDbMigrationCommand.php
index 6e44544..e5feee0 100644
--- a/CDbMigrationCommand.php
+++ b/CDbMigrationCommand.php
@@ -1,169 +1,169 @@
<?php
// Import the main classes
-Yii::import('application.extensions.DbMigrations.*');
+Yii::import('application.extensions.yii-dbmigrations.*');
// The migration command
class CDbMigrationCommand extends CConsoleCommand {
// The migration adapter to use
private $adapter;
// The name of the table and column for the schema information
const SCHEMA_TABLE = 'schema_version';
const SCHEMA_FIELD = 'id';
const SCHEMA_EXT = 'php';
// Get the command help
public function getHelp() {
return 'Used to run database migrations';
}
// Run the command
public function run($args) {
// Catch errors
try {
// Initialize
$this->init();
// Check if we need to create a migration
if (isset($args[0]) && ($args[0] == 'create')) {
$this->create($args[0]);
} else {
$this->applyMigrations();
}
} catch (Exception $e) {
// Log the error
$this->log('-----');
$this->log('SOMETHING WENT TERRIBLY WRONG:');
$this->log($e->getMessage());
}
}
// Create a migration
protected function create($migration) {
}
// Initialize the schema version table
protected function init() {
// Add the migrations directory to the search path
Yii::import('application.migrations.*');
// Load the migration adapter
switch (Yii::app()->db->driverName) {
case 'mysql':
$this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
break;
case 'sqlite':
$this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
break;
default:
throw new CDbMigrationException(
'Database of type ' . Yii::app()->db->driverName
. ' does not support migrations (yet).'
);
}
// Check if the schema version table exists
if (Yii::app()->db->schema->getTable('schema_version') == null) {
// Create the table
$this->log('Creating initial schema_version table');
// Use the adapter to create the table
$this->adapter->createTable(
self::SCHEMA_TABLE,
array(
array(self::SCHEMA_FIELD, 'string'),
)
);
// Create an index on the column
$this->adapter->addIndex(
self::SCHEMA_TABLE,
'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
array(self::SCHEMA_FIELD),
true
);
}
}
// Get the list of migrations that are applied to the database
protected function getAppliedMigrations() {
// Get the field and table name
$field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
$table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
// Construct the SQL statement
$sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
// Get the list
return Yii::app()->db->createCommand($sql)->queryColumn(
self::SCHEMA_FIELD
);
}
// Get the list of possible migrations
protected function getPossibleMigrations() {
$migrations = CFileHelper::findFiles(
Yii::app()->basePath . '/migrations',
array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
);
foreach ($migrations as $key=>$migration) {
$migrations[$key] = basename($migration, '.' . self::SCHEMA_EXT);
}
return $migrations;
}
// Apply the migrations
protected function applyMigrations() {
$applied = $this->getAppliedMigrations();
$possible = $this->getPossibleMigrations();
foreach ($possible as $migration) {
$migration = new $migration($this->adapter);
if (!in_array($migration->getId(), $applied)) {
$this->applyMigration($migration);
} else {
$this->log(
'Skipping applied migration: ' . get_class($migration)
);
}
}
}
// Apply a specific migration
protected function applyMigration($migration) {
// Apply the migration
$this->log('Applying migration: ' . get_class($migration));
// Create the migration instance
$migration->up();
// Commit the migration
$this->log('Marking migration as applied: ' . get_class($migration));
$cmd = Yii::app()->db->commandBuilder->createInsertCommand(
self::SCHEMA_TABLE,
array(self::SCHEMA_FIELD => $migration->getId())
)->execute();
}
// Helper for logging a message
protected function log($msg) {
echo(strftime('%Y-%m-%d %H:%M:%S') . ' ' . $msg . PHP_EOL);
}
}
\ No newline at end of file
diff --git a/README b/README
index 4b48a8e..61ef796 100644
--- a/README
+++ b/README
@@ -1,3 +1,22 @@
Yii DB Migrations
-A database migrations engine for the Yii framework.
\ No newline at end of file
+A database migrations engine for the Yii framework.
+
+
+INSTALLATION
+
+You need to add the following to your configuration file:
+
+'commandMap' => array(
+ 'migrate' => array(
+ 'class'=>'application.extensions.yii-dbmigrations.CDbMigrationCommand',
+ ),
+),
+
+RUNNING
+
+You can execute
+
+protected/yiic migrate
+
+It will apply all the migrations found in the protected/migrations directory.
\ No newline at end of file
diff --git a/samples/m20090611153243_CreateTables.php b/samples/m20090611153243_CreateTables.php
new file mode 100644
index 0000000..8c75809
--- /dev/null
+++ b/samples/m20090611153243_CreateTables.php
@@ -0,0 +1,37 @@
+<?php
+
+class m20090611153243_CreateTables extends CDbMigration {
+
+ public function up() {
+
+ /*
+ $tables = $this->query("show tables");
+ $this->renameTable('test_table', 'posts');
+ $this->removeIndex('test_table', 'idx_pk');
+ $this->removeColumn('test_table', 'comment_id');
+ $this->changeColumn('test_table', 'comment_id', 'boolean');
+ $this->addColumn('test_table', 'title', 'string');
+ $this->addIndex('posts', 'posts_sort', array('field1', 'field2'), true);
+ $this->removeTable('test_table');
+ */
+
+ $this->createTable(
+ 'posts',
+ array(
+ array('id', 'primary_key'),
+ array('title', 'string'),
+ array('body', 'text'),
+ )
+ );
+
+ $this->addIndex(
+ 'posts', 'posts_title', array('title')
+ );
+
+ }
+
+ public function down() {
+ $this->removeTable('posts');
+ }
+
+}
\ No newline at end of file
diff --git a/samples/m20090612162832_CreateTags.php b/samples/m20090612162832_CreateTags.php
new file mode 100644
index 0000000..2a27cc8
--- /dev/null
+++ b/samples/m20090612162832_CreateTags.php
@@ -0,0 +1,35 @@
+<?php
+
+class m20090612162832_CreateTags extends CDbMigration {
+
+ public function up() {
+
+ $this->createTable(
+ 'tags',
+ array(
+ array('id', 'primary_key'),
+ array('name', 'string'),
+ )
+ );
+
+ $this->createTable(
+ 'post_tags',
+ array(
+ array('id', 'primary_key'),
+ array('post_id', 'int'),
+ array('tag_id', 'int'),
+ )
+ );
+
+ $this->addIndex(
+ 'post_tags', 'post_tags_post_tag', array('post_id', 'tag_id'), true
+ );
+
+ }
+
+ public function down() {
+ $this->removeTable('post_tags');
+ $this->removeTable('tags');
+ }
+
+}
\ No newline at end of file
diff --git a/samples/m20090612163144_RenameTagsTable.php b/samples/m20090612163144_RenameTagsTable.php
new file mode 100644
index 0000000..69a2bc2
--- /dev/null
+++ b/samples/m20090612163144_RenameTagsTable.php
@@ -0,0 +1,17 @@
+<?php
+
+class m20090612163144_RenameTagsTable extends CDbMigration {
+
+ public function up() {
+ $this->renameTable(
+ 'post_tags', 'post_tags_link_table'
+ );
+ }
+
+ public function down() {
+ $this->renameTable(
+ 'post_tags_link_table', 'post_tags'
+ );
+ }
+
+}
\ No newline at end of file
|
elchingon/yii-dbmigrations | 334f8836f49a54709a37a489593972392b8b6e33 | Added the source files | diff --git a/CDbMigration.php b/CDbMigration.php
new file mode 100644
index 0000000..f1bad11
--- /dev/null
+++ b/CDbMigration.php
@@ -0,0 +1,113 @@
+<?php
+
+class CDbMigrationException extends Exception {}
+
+// Class implementing a migration
+abstract class CDbMigration {
+
+ // The adapter to use
+ private $adapter;
+
+ // Constructor
+ public function __construct(CDbMigrationAdapter $adapter) {
+ $this->adapter = $adapter;
+ }
+
+ // Migrate up
+ public function up() {
+ }
+
+ // Migrate down
+ public function down() {
+ }
+
+ // Helper for logging a message
+ protected function log($msg) {
+ echo(strftime('%Y-%m-%d %H:%M:%S') . ' ' . $msg . PHP_EOL);
+ }
+
+ // Get the id of the migration
+ public function getId() {
+ $id = split('_', get_class($this));
+ return substr($id[0], 1);
+ }
+
+ // Get the name of the migration
+ public function getName() {
+ $name = split('_', get_class($this));
+ return $name[1];
+ }
+
+ // Execute a raw SQL statement
+ protected function execute($query, $params=array()) {
+ return $this->adapter->execute($query, $params);
+ }
+
+ // Execute a raw SQL statement
+ protected function query($query, $params=array()) {
+ return $this->adapter->query($query, $params);
+ }
+
+ // Create a table
+ protected function createTable($name, $columns=array(), $options=null) {
+ $this->log(' >> Creating table: ' . $name);
+ return $this->adapter->createTable($name, $columns, $options);
+ }
+
+ // Rename a table
+ protected function renameTable($name, $new_name) {
+ $this->log(' >> Renaming table: ' . $name . ' to: ' . $new_name);
+ return $this->adapter->renameTable($name, $new_name);
+ }
+
+ // Drop a table
+ protected function removeTable($name) {
+ $this->log(' >> Removing table: ' . $name);
+ return $this->adapter->removeTable($name);
+ }
+
+ // Add a database column
+ protected function addColumn($table, $column, $type, $options=null) {
+ $this->log(' >> Adding column ' . $column . ' to table: ' . $table);
+ return $this->adapter->addColumn($table, $column, $type, $options);
+ }
+
+ // Rename a database column
+ protected function renameColumn($table, $name, $new_name) {
+ $this->log(
+ ' >> Renaming column ' . $name . ' to: ' . $new_name
+ . ' in table: ' . $table
+ );
+ return $this->adapter->renameColumn($table, $name, $new_name);
+ }
+
+ // Change a database column
+ protected function changeColumn($table, $column, $type, $options=null) {
+ $this->log(
+ ' >> Chaning column ' . $name . ' to: ' . $type
+ . ' in table: ' . $table
+ );
+ return $this->adapter->changeColumn($table, $column, $type, $options);
+ }
+
+ // Remove a column
+ protected function removeColumn($table, $column) {
+ $this->log(
+ ' >> Removing column ' . $column . ' from table: ' . $table
+ );
+ return $this->adapter->removeColumn($table, $column);
+ }
+
+ // Add an index
+ public function addIndex($table, $name, $columns, $unique=false) {
+ $this->log(' >> Adding index ' . $name . ' to table: ' . $table);
+ return $this->adapter->addIndex($table, $name, $columns, $unique);
+ }
+
+ // Remove an index
+ protected function removeIndex($table, $column) {
+ $this->log(' >> Removing index ' . $name . ' from table: ' . $table);
+ return $this->adapter->removeIndex($table, $column);
+ }
+
+}
\ No newline at end of file
diff --git a/CDbMigrationAdapter.php b/CDbMigrationAdapter.php
new file mode 100644
index 0000000..8ce5275
--- /dev/null
+++ b/CDbMigrationAdapter.php
@@ -0,0 +1,135 @@
+<?php
+
+// A database specific version of a migration adapter
+abstract class CDbMigrationAdapter {
+
+ // The database connection
+ public $db;
+
+ // Constructor
+ public function __construct(CDbConnection $db) {
+ $this->db = $db;
+ }
+
+ // Convert a type to a native database type
+ protected function convertToNativeType($theType) {
+ if (isset($this->nativeDatabaseTypes[$theType])) {
+ return $this->nativeDatabaseTypes[$theType];
+ } else {
+ return $theType;
+ }
+ }
+
+ // Convert the field information to native types
+ protected function convertFields($fields) {
+ $result = array();
+ foreach ($fields as $field) {
+ if (is_array($field)) {
+ if (isset($field[0])) {
+ $field[0] = $this->db->quoteColumnName($field[0]);
+ }
+ if (isset($field[1])) {
+ $field[1] = $this->convertToNativeType($field[1]);
+ }
+ $result[] = join(' ', $field);
+ } else {
+ $result[] = $this->db->quoteColumnName($field);
+ }
+ }
+ return join(', ', $result);
+ }
+
+ // Execute a raw SQL statement
+ public function execute($query, $params=array()) {
+ //echo('SQL: ' . $query . PHP_EOL);
+ return $this->db->createCommand($query)->execute();
+ }
+
+ // Execute a raw SQL statement
+ public function query($query, $params=array()) {
+ //echo('SQL: ' . $query . PHP_EOL);
+ return $this->db->createCommand($query)->queryAll();
+ }
+
+ // Get the column info
+ public function columnInfo($name) {
+ }
+
+ // Create a table
+ public function createTable($name, $columns=array(), $options=null) {
+ $sql = 'CREATE TABLE ' . $this->db->quoteTableName($name) . ' ('
+ . $this->convertFields($columns)
+ . ') ' . $options;
+ return $this->execute($sql);
+ }
+
+ // Rename a table
+ public function renameTable($name, $new_name) {
+ $sql = 'RENAME TABLE ' . $this->db->quoteTableName($name) . ' TO '
+ . $this->db->quoteTableName($new_name);
+ return $this->execute($sql);
+ }
+
+ // Drop a table
+ public function removeTable($name) {
+ $sql = 'DROP TABLE ' . $this->db->quoteTableName($name);
+ return $this->execute($sql);
+ }
+
+ // Add a database column
+ public function addColumn($table, $column, $type, $options=null) {
+ $type = $this->convertToNativeType($type);
+ if (empty($options)) {
+ $options = 'NOT NULL';
+ }
+ $sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD '
+ . $this->db->quoteColumnName($column) . ' ' . $type . ' '
+ . $options;
+ return $this->execute($sql);
+ }
+
+ // Change a database column
+ public function changeColumn($table, $column, $type, $options=null) {
+ $type = $this->convertToNativeType($type);
+ $sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
+ . $this->db->quoteColumnName($column) . ' '
+ . $this->db->quoteColumnName($column) . ' ' . $type . ' '
+ . $options;
+ return $this->execute($sql);
+ }
+
+ // Rename a database column
+ public function renameColumn($table, $name, $new_name) {
+ $type = $this->columnInfo($name);
+ $sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
+ . $this->db->quoteColumnName($name) . ' '
+ . $this->db->quoteColumnName($new_name) . ' ' . $type;
+ return $this->execute($sql);
+ }
+
+ // Remove a column
+ public function removeColumn($table, $column) {
+ $sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' DROP '
+ . $this->db->quoteColumnName($column);
+ return $this->execute($sql);
+ }
+
+ // Add an index
+ public function addIndex($table, $name, $columns, $unique=false) {
+ $sql = 'CREATE ';
+ $sql .= ($unique) ? 'UNIQUE ' : '';
+ $sql .= 'INDEX ' . $this->db->quoteColumnName($name) . ' ON '
+ . $this->db->quoteTableName($table) . ' ('
+ . $this->convertFields($columns)
+ . ')';
+ return $this->execute($sql);
+ }
+
+ // Remove an index
+ public function removeIndex($table, $name) {
+ $sql = 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON '
+ . $this->db->quoteTableName($table);
+ return $this->execute($sql);
+ }
+
+}
diff --git a/CDbMigrationAdapterMysql.php b/CDbMigrationAdapterMysql.php
new file mode 100644
index 0000000..ea55d29
--- /dev/null
+++ b/CDbMigrationAdapterMysql.php
@@ -0,0 +1,22 @@
+<?php
+
+class CDbMigrationAdapterMysql extends CDbMigrationAdapter {
+
+ // Return a map of the native database types
+ protected $nativeDatabaseTypes = array(
+ 'primary_key' => 'int(11) DEFAULT NULL auto_increment PRIMARY KEY',
+ 'string' => 'varchar(255)',
+ 'text' => 'text',
+ 'integer' => 'int(4)',
+ 'float' => 'float',
+ 'decimal' => 'decimal',
+ 'datetime' => 'datetime',
+ 'timestamp' => 'datetime',
+ 'time' => 'time',
+ 'date' => 'date',
+ 'binary' => 'blob',
+ 'boolean' => 'tinyint(1)',
+ 'bool' => 'tinyint(1)',
+ );
+
+}
diff --git a/CDbMigrationAdapterSqlite.php b/CDbMigrationAdapterSqlite.php
new file mode 100644
index 0000000..a76979b
--- /dev/null
+++ b/CDbMigrationAdapterSqlite.php
@@ -0,0 +1,50 @@
+<?php
+
+class CDbMigrationAdapterSqlite extends CDbMigrationAdapter {
+
+ // Return a map of the native database types
+ protected $nativeDatabaseTypes = array(
+ 'primary_key' => 'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL',
+ 'string' => 'varchar(255)',
+ 'text' => 'text',
+ 'integer' => 'integer',
+ 'float' => 'float',
+ 'decimal' => 'decimal',
+ 'datetime' => 'datetime',
+ 'timestamp' => 'datetime',
+ 'time' => 'time',
+ 'date' => 'date',
+ 'binary' => 'blob',
+ 'boolean' => 'tinyint(1)',
+ 'bool' => 'tinyint(1)',
+ );
+
+ // Rename a table
+ public function renameTable($name, $new_name) {
+ $sql = 'ALTER TABLE ' . $this->db->quoteTableName($name) . ' RENAME TO '
+ . $this->db->quoteTableName($new_name);
+ return $this->execute($sql);
+ }
+
+ // Change a database column
+ public function changeColumn($table, $column, $type, $options=null) {
+ throw new CDbMigrationException(
+ 'changeColumn is not supported for SQLite'
+ );
+ }
+
+ // Change a database column
+ public function renameColumn($table, $name, $new_name) {
+ throw new CDbMigrationException(
+ 'renameColumn is not supported for SQLite'
+ );
+ }
+
+ // Remove a column
+ public function removeColumn($table, $column) {
+ throw new CDbMigrationException(
+ 'removeColumn is not supported for SQLite'
+ );
+ }
+
+}
diff --git a/CDbMigrationCommand.php b/CDbMigrationCommand.php
new file mode 100644
index 0000000..6e44544
--- /dev/null
+++ b/CDbMigrationCommand.php
@@ -0,0 +1,169 @@
+<?php
+
+// Import the main classes
+Yii::import('application.extensions.DbMigrations.*');
+
+// The migration command
+class CDbMigrationCommand extends CConsoleCommand {
+
+ // The migration adapter to use
+ private $adapter;
+
+ // The name of the table and column for the schema information
+ const SCHEMA_TABLE = 'schema_version';
+ const SCHEMA_FIELD = 'id';
+ const SCHEMA_EXT = 'php';
+
+ // Get the command help
+ public function getHelp() {
+ return 'Used to run database migrations';
+ }
+
+ // Run the command
+ public function run($args) {
+
+ // Catch errors
+ try {
+
+ // Initialize
+ $this->init();
+
+ // Check if we need to create a migration
+ if (isset($args[0]) && ($args[0] == 'create')) {
+ $this->create($args[0]);
+ } else {
+ $this->applyMigrations();
+ }
+
+ } catch (Exception $e) {
+
+ // Log the error
+ $this->log('-----');
+ $this->log('SOMETHING WENT TERRIBLY WRONG:');
+ $this->log($e->getMessage());
+
+ }
+
+ }
+
+ // Create a migration
+ protected function create($migration) {
+ }
+
+ // Initialize the schema version table
+ protected function init() {
+
+ // Add the migrations directory to the search path
+ Yii::import('application.migrations.*');
+
+ // Load the migration adapter
+ switch (Yii::app()->db->driverName) {
+ case 'mysql':
+ $this->adapter = new CDbMigrationAdapterMysql(Yii::app()->db);
+ break;
+ case 'sqlite':
+ $this->adapter = new CDbMigrationAdapterSqlite(Yii::app()->db);
+ break;
+ default:
+ throw new CDbMigrationException(
+ 'Database of type ' . Yii::app()->db->driverName
+ . ' does not support migrations (yet).'
+ );
+ }
+
+ // Check if the schema version table exists
+ if (Yii::app()->db->schema->getTable('schema_version') == null) {
+
+ // Create the table
+ $this->log('Creating initial schema_version table');
+
+ // Use the adapter to create the table
+ $this->adapter->createTable(
+ self::SCHEMA_TABLE,
+ array(
+ array(self::SCHEMA_FIELD, 'string'),
+ )
+ );
+
+ // Create an index on the column
+ $this->adapter->addIndex(
+ self::SCHEMA_TABLE,
+ 'idx_' . self::SCHEMA_TABLE . '_' . self::SCHEMA_FIELD,
+ array(self::SCHEMA_FIELD),
+ true
+ );
+
+ }
+
+ }
+
+ // Get the list of migrations that are applied to the database
+ protected function getAppliedMigrations() {
+
+ // Get the field and table name
+ $field = Yii::app()->db->quoteColumnName(self::SCHEMA_FIELD);
+ $table = Yii::app()->db->quoteTableName(self::SCHEMA_TABLE);
+
+ // Construct the SQL statement
+ $sql = 'SELECT ' . $field . ' FROM ' . $table . ' ORDER BY ' . $field;
+
+ // Get the list
+ return Yii::app()->db->createCommand($sql)->queryColumn(
+ self::SCHEMA_FIELD
+ );
+
+ }
+
+ // Get the list of possible migrations
+ protected function getPossibleMigrations() {
+ $migrations = CFileHelper::findFiles(
+ Yii::app()->basePath . '/migrations',
+ array('fileTypes' => array(self::SCHEMA_EXT), 'level' => 0)
+ );
+ foreach ($migrations as $key=>$migration) {
+ $migrations[$key] = basename($migration, '.' . self::SCHEMA_EXT);
+ }
+ return $migrations;
+ }
+
+ // Apply the migrations
+ protected function applyMigrations() {
+ $applied = $this->getAppliedMigrations();
+ $possible = $this->getPossibleMigrations();
+
+ foreach ($possible as $migration) {
+ $migration = new $migration($this->adapter);
+ if (!in_array($migration->getId(), $applied)) {
+ $this->applyMigration($migration);
+ } else {
+ $this->log(
+ 'Skipping applied migration: ' . get_class($migration)
+ );
+ }
+ }
+ }
+
+ // Apply a specific migration
+ protected function applyMigration($migration) {
+
+ // Apply the migration
+ $this->log('Applying migration: ' . get_class($migration));
+
+ // Create the migration instance
+ $migration->up();
+
+ // Commit the migration
+ $this->log('Marking migration as applied: ' . get_class($migration));
+ $cmd = Yii::app()->db->commandBuilder->createInsertCommand(
+ self::SCHEMA_TABLE,
+ array(self::SCHEMA_FIELD => $migration->getId())
+ )->execute();
+
+ }
+
+ // Helper for logging a message
+ protected function log($msg) {
+ echo(strftime('%Y-%m-%d %H:%M:%S') . ' ' . $msg . PHP_EOL);
+ }
+
+}
\ No newline at end of file
|
elchingon/yii-dbmigrations | 0448a45d473d958e81a146df17eaded71300c0e4 | Added a readme file | diff --git a/README b/README
new file mode 100644
index 0000000..4b48a8e
--- /dev/null
+++ b/README
@@ -0,0 +1,3 @@
+Yii DB Migrations
+
+A database migrations engine for the Yii framework.
\ No newline at end of file
|
tatewake/dokuwiki-plugin-googleanalytics | d3d40d986b151a94538764257547b48ad50c4999 | DPG-21 - Added support for optionally using "Global Site Tag ID" / `gtag.js` * In `action.php`, we now look for `GTAGID` and pass it through to `$JSINFO['ga']` * In `script.js`, introduced a code path for using `gtag.js` and making it the default if `GTAGID` is set * In `default.php`, `metadata.php`, and `settings.php`, added support for setting `GTAGID` as well as defaults and description * Removed `settings.php` for other languages as they were completely out of date * Rewrote `intro.txt` as it was completely out of date, but also added info for `gtag.js` support * Updated CHANGELOG, README, and plugin.info.txt | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 29802e6..d834b69 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,42 +1,50 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Added
### Changed
### Removed
### Fixed
+## [1.1.0] - 2020-11-03
+
+### Added
+
+- [DPG-21] - Added support for "Global Site Tag ID" (`gtag.js`), and rewrote documentation as some was out of date.
+
## [1.0.1] - 2020-09-14
### Added
-- [DPG-20] - Added admin page, icon, and menu text for DokuWiki's administration page;
+- [DPG-20] - Added admin page, icon, and menu text for DokuWiki's administration page
## [1.0.0] - 2020-06-25
### Added
- [DPG-19] - Added this CHANGELOG.md, rewrote README.md and first official version number 1.0.0 and release date to 2020-06-25
### Changed
- [DPG-17] - Auto-reformatted PHP and JS files with [php-cs-fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer) and [js-beautify](https://www.npmjs.com/package/js-beautify)
### Fixed
- [DPG-15] - Fixed an issue where "blank target" was not respected when clicking on a new link
##
+[1.1.0]: https://github.com/tatewake/dokuwiki-plugin-googleanalytics/releases/tag/1.1.0
[1.0.1]: https://github.com/tatewake/dokuwiki-plugin-googleanalytics/releases/tag/1.0.1
[1.0.0]: https://github.com/tatewake/dokuwiki-plugin-googleanalytics/releases/tag/1.0.0
+[DPG-21]: http://192.168.1.150/open-source/dokuwiki/googleanalytics/-/issues/21
[DPG-20]: http://192.168.1.150/open-source/dokuwiki/googleanalytics/-/issues/20
[DPG-19]: https://github.com/tatewake/dokuwiki-plugin-googleanalytics/issues/19
[DPG-17]: https://github.com/tatewake/dokuwiki-plugin-googleanalytics/issues/17
[DPG-15]: https://github.com/tatewake/dokuwiki-plugin-googleanalytics/issues/15
diff --git a/README.md b/README.md
index 84b02a6..3601283 100644
--- a/README.md
+++ b/README.md
@@ -1,48 +1,60 @@
# Google Analytics for DokuWiki
## License
* **Author**: [Terence J. Grant](mailto:[email protected])
* **License**: [GNU GPL v2](http://opensource.org/licenses/GPL-2.0)
-* **Latest Release**: v1.0.1 on Sep 14th, 2020
+* **Latest Release**: v1.1.0 on Nov 3rd, 2020
* **Changes**: See [CHANGELOG.md](CHANGELOG.md) for full details.
* **Donate**: [Donations](http://tjgrant.com/wiki/donate) and [Sponsorships](https://github.com/sponsors/tatewake) are appreciated!
## About
This tool allows you to set a code for use with [Google Analytics](https://en.wikipedia.org/wiki/Google_Analytics), which allows you to track your visitors.
-The plugin also exports a function for use with your template, so you will have to insert the following code into your template (**main.php**), somewhere inside of the `<head></head>` tags.
+This plugin generates JavaScript code that is automatically included into your site via the `lib/exe/js.php` file. (Which you can inspect via your browser's "developer tools.")
- <?php
- if (file_exists(DOKU_PLUGIN.'googleanalytics/code.php')) include_once(DOKU_PLUGIN.'googleanalytics/code.php');
- if (function_exists('ga_google_analytics_code')) ga_google_analytics_code();
- ?>
+Set the options for this plugin via the **Configuration Settings** menu from the DokuWiki admin menu. (It will be near the bottom of the page.)
-**Note**: Inserting the code above is **required**, not optional.
+You may use one of two tracking options:
-**Template Authors Note**: You can insert the above code and make your template "Google Analytics Ready", even if your users do not use Google Analytics (or have this plugin.)
+ * **Basic** "Google Analytics ID" (also known as "[analytics.js](https://developers.google.com/analytics/devguides/collection/analyticsjs)") using a **UA-XXXXXX-XX** code
+ * **Newer** "Global Site Tag ID" (also known as "[gtag.js](https://developers.google.com/analytics/devguides/collection/gtagjs)") using a **G-XXXXXXXXXX** code
+
+If you set a "Global Site Tag ID", then this method will be used and any "Google Analytics ID" / **UA-XXXXXXX-XX** specific settings will be ignored.
+
+## Advanced Usage
+
+To use the advanced "tagging" features of `analytics.js` or `gtag.js`, you will need to be able to embed JavaScript within your DokuWiki pages. You can accomplish this in one of three ways:
+
+ * [Enabling embedded HTML](https://www.dokuwiki.org/wiki:syntax#embedding_html_and_php) in your local DokuWiki instance (Look for `htmlok` in Configuration Settings)
+ * Allow embedded JavaScript via a plugin like the [InlineJS Plugin](https://www.dokuwiki.org/plugin:inlinejs)
+ * Edit your site's template to add "tagging" directly
+
+Allowing embedded HTML / JavaScript will give you the most flexibility for per-page tagging, but it can open your site to [Cross-site Scripting](https://en.wikipedia.org/wiki/Cross-site_scripting) attacks if you're not careful. If you lock down who can edit your wiki pages and trust your users, you should be fine though.
+
+If you edit your template (the third option), make sure to make notes of what you change, as "upgrading" your template will revert any changes you've made.
## Install / Upgrade
Search and install the plugin using the [Extension Manager](https://www.dokuwiki.org/plugin:extension). Refer to [Plugins](https://www.dokuwiki.org/plugins) on how to install plugins manually.
## Setup
All further documentation for this plugin can be found at:
* [https://www.dokuwiki.org/plugin:googleanalytics](https://www.dokuwiki.org/plugin:googleanalytics)
## Contributing
The official repository for this plugin is available on GitHub:
* [https://github.com/tatewake/dokuwiki-plugin-googleanalytics](https://github.com/tatewake/dokuwiki-plugin-googleanalytics)
The plugin thrives from community contributions. If you're able to provide useful code changes or bug fixes, they will likely be accepted to future versions of the plugin.
If you find my work helpful and would like to give back, [consider joining me as a GitHub sponsor](https://github.com/sponsors/tatewake).
Thanks!
--Terence
diff --git a/action.php b/action.php
index b9d722e..78bda74 100644
--- a/action.php
+++ b/action.php
@@ -1,127 +1,131 @@
<?php
if (!defined('DOKU_INC')) {
die();
}
if (!defined('DOKU_PLUGIN')) {
define('DOKU_PLUGIN', DOKU_INC . 'lib/plugins/');
}
/**
* Google Analytics for DokuWiki
*
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
* @author Terence J. Grant<[email protected]>
*/
class action_plugin_googleanalytics extends DokuWiki_Action_Plugin
{
private $gaEnabled = true;
/**
* Register its handlers with the DokuWiki's event controller
*
* @param Doku_Event_Handler $controller
*/
public function register(Doku_Event_Handler $controller)
{
$controller->register_hook('DOKUWIKI_STARTED', 'AFTER', $this, 'gaConfig');
}
/**
* Initialize the Google Analytics config
*
* @param Doku_Event $event
* @param array $param
*/
public function gaConfig(Doku_Event $event, $param)
{
global $JSINFO;
global $INFO;
global $ACT;
if (!$this->gaEnabled) {
return;
}
$trackingId = $this->getConf('GAID');
- if (!$trackingId) {
+ $gtagId = $this->getConf('GTAGID');
+
+ if (!$trackingId && !$gtagId) {
return;
}
+
if ($this->getConf('dont_count_admin') && $INFO['isadmin']) {
return;
}
if ($this->getConf('dont_count_users') && $_SERVER['REMOTE_USER']) {
return;
}
act_clean($ACT);
$options = array();
if ($this->getConf('track_users') && $_SERVER['REMOTE_USER']) {
$options['userId'] = md5(auth_cookiesalt() . 'googleanalytics' . $_SERVER['REMOTE_USER']);
}
if ($this->getConf('domainName')) {
$options['cookieDomain'] = $this->getConf('domainName');
$options['legacyCookieDomain'] = $this->getConf('domainName');
}
global $conf;
$JSINFO['ga'] = array(
'trackingId' => $trackingId,
+ 'gtagId' => $gtagId,
'anonymizeIp' => (bool) $this->getConf('anonymize'),
'action' => $ACT,
'trackOutboundLinks' => (bool) $this->getConf('track_links'),
'options' => $options,
'pageview' => $this->getPageView(),
'debug' => (bool) $conf['allowdebug']
);
}
/**
* normalize the pageview
*
* @return string
*/
protected function getPageView()
{
global $QUERY;
global $ID;
global $INPUT;
global $ACT;
// clean up parameters to log
$params = $_GET;
if (isset($params['do'])) {
unset($params['do']);
}
if (isset($params['id'])) {
unset($params['id']);
}
// decide on virtual views
if ($ACT == 'search') {
$view = '~search/';
$params['q'] = $QUERY;
} elseif ($ACT == 'admin') {
$page = $INPUT->str('page');
$view = '~admin';
if ($page) {
$view .= '/' . $page;
}
if (isset($params['page'])) {
unset($params['page']);
}
} else {
$view = str_replace(':', '/', $ID); // slashes needed for Content Drilldown
}
// prepend basedir, allows logging multiple dir based animals in one tracker
$view = DOKU_REL . $view;
// append query parameters
$query = http_build_query($params, '', '&');
if ($query) {
$view .= '?' . $query;
}
return $view;
}
}
diff --git a/conf/default.php b/conf/default.php
index 32682a9..352004b 100644
--- a/conf/default.php
+++ b/conf/default.php
@@ -1,9 +1,10 @@
<?php
$conf['GAID'] = '';
+$conf['GTAGID'] = '';
$conf['dont_count_admin'] = 0;
$conf['dont_count_users'] = 0;
$conf['anonymize'] = 1;
$conf['track_users'] = 0;
$conf['track_links'] = 0;
$conf['domainName'] = '';
diff --git a/conf/metadata.php b/conf/metadata.php
index 1a70c43..fc11dea 100644
--- a/conf/metadata.php
+++ b/conf/metadata.php
@@ -1,9 +1,10 @@
<?php
$meta['GAID'] = array('string');
+$meta['GTAGID'] = array('string');
$meta['dont_count_admin'] = array('onoff');
$meta['dont_count_users'] = array('onoff');
$meta['anonymize'] = array('onoff');
$meta['track_users'] = array('onoff');
$meta['track_links'] = array('onoff');
$meta['domainName'] = array('string');
diff --git a/lang/en/intro.txt b/lang/en/intro.txt
index dc3c725..e22c0fa 100755
--- a/lang/en/intro.txt
+++ b/lang/en/intro.txt
@@ -1,28 +1,36 @@
====== Google Analytics for DokuWiki ======
===== About =====
This tool allows you to set a code for use with [[https://en.wikipedia.org/wiki/Google_Analytics|Google Analytics]], which allows you to track your visitors.
===== Setup =====
-The plugin also exports a function for use with your template, so you will have to insert the following code into your template's **main.php**, somewhere inside of the ''<head></head>'' tags.
+This plugin generates JavaScript code that is automatically included into your site via the ''lib/exe/js.php'' file. (Which you can inspect via your browser's "developer tools.")
-<code php><?php
-if (file_exists(DOKU_PLUGIN.'googleanalytics/code.php')) include_once(DOKU_PLUGIN.'googleanalytics/code.php');
-if (function_exists('ga_google_analytics_code')) ga_google_analytics_code();
-?></code>
+Set the options for this plugin via the **Configuration Settings** menu from the DokuWiki admin menu. (It will be near the bottom of the page.)
-**Note**: Inserting the code above is **required**, not optional.
+You may use one of two tracking options:
-Set the options for this plugin via the **Configuration Settings** menu from the DokuWiki admin menu. (It will be near the bottom of the page.)
+ * **Basic** "Google Analytics ID" (also known as "[[https://developers.google.com/analytics/devguides/collection/analyticsjs|analytics.js]]") using a **UA-XXXXXX-XX** code
+ * **Newer** "Global Site Tag ID" (also known as "[[https://developers.google.com/analytics/devguides/collection/gtagjs|gtag.js]]") using a **G-XXXXXXXXXX** code
+
+If you set a "Global Site Tag ID", then this method will be used and any "Google Analytics ID" / **UA-XXXXXXX-XX** specific settings will be ignored.
+
+===== Advanced Usage =====
+
+To use the advanced "tagging" features of ''analytics.js'' or ''gtag.js'', you will need to be able to embed JavaScript within your DokuWiki pages. You can accomplish this in one of three ways:
+
+ * [[:wiki:syntax#embedding_html_and_php|Enabling embedded HTML]] in your local DokuWiki instance (Look for ''htmlok'' in Configuration Settings)
+ * Allow embedded JavaScript via a plugin like the [[doku>plugin:inlinejs|InlineJS Plugin]]
+ * Edit your site's template to add "tagging" directly
-===== For template developers =====
+Allowing embedded HTML / JavaScript will give you the most flexibility for per-page tagging, but it can open your site to [[https://en.wikipedia.org/wiki/Cross-site_scripting|Cross-site Scripting]] attacks if you're not careful. If you lock down who can edit your wiki pages and trust your users, you should be fine though.
-You can insert the above code and make your template "Google Analytics Ready", even if your users do not use Google Analytics (or have this plugin.)
+If you edit your template (the third option), make sure to make notes of what you change, as "upgrading" your template will revert any changes you've made.
===== Support =====
For further support or discussion, please see the official plugin page [[doku>plugin:googleanalytics|here]].
If you find this plugin useful, please consider supporting the project via [[http://tjgrant.com/wiki/donate|Donations]] or [[https://github.com/sponsors/tatewake|Sponsorships]]; thank you!
diff --git a/lang/en/settings.php b/lang/en/settings.php
index ac0480a..0df8778 100644
--- a/lang/en/settings.php
+++ b/lang/en/settings.php
@@ -1,8 +1,9 @@
<?php
$lang['GAID'] = 'Your Google Analytics ID (UA-XXXXXX-XX)';
+$lang['GTAGID'] = 'Your Global Site Tag ID (G-XXXXXXXXXX)';
$lang['dont_count_admin'] = 'Don\'t count admin/superuser';
$lang['dont_count_users'] = 'Don\'t count logged in users';
-$lang['anonymize'] = 'Send anonymized IP addresses to Google.';
-$lang['track_users'] = 'Track logged in users across different devices. Needs <a href="https://support.google.com/analytics/answer/3123662?hl=en">user tracking</a> enabled. Users will not be identifable in Google Analytics!';
-$lang['track_links'] = 'Track outgoing links.';
-$lang['domainName'] = 'Configure the cookie domain. Should usually be left empty';
+$lang['anonymize'] = 'Send anonymized IP addresses to Google. (UA-XXXXXX-XX only)';
+$lang['track_users'] = 'Track logged in users across different devices. Needs <a href="https://support.google.com/analytics/answer/3123662?hl=en">user tracking</a> enabled. Users will not be identifable in Google Analytics! (UA-XXXXXX-XX only)';
+$lang['track_links'] = 'Track outgoing links. (UA-XXXXXX-XX only)';
+$lang['domainName'] = 'Configure the cookie domain. Should usually be left empty. (UA-XXXXXX-XX only)';
diff --git a/lang/ja/settings.php b/lang/ja/settings.php
deleted file mode 100644
index e9e29fd..0000000
--- a/lang/ja/settings.php
+++ /dev/null
@@ -1,4 +0,0 @@
-<?php
-$lang['GAID'] = 'Google Analitycs ID';
-$lang['dont_count_admin'] = '管çè
ãè§£æå¯¾è±¡å¤ã«ãã';
-$lang['dont_count_users'] = 'ãã°ã¤ã³ã¦ã¼ã¶ã¼ãè§£æå¯¾è±¡å¤ã«ãã';
diff --git a/lang/pl/settings.php b/lang/pl/settings.php
deleted file mode 100644
index a691071..0000000
--- a/lang/pl/settings.php
+++ /dev/null
@@ -1,4 +0,0 @@
-<?php
-$lang['GAID'] = 'Google Analitycs ID';
-$lang['dont_count_admin'] = 'Nie zliczaj: admin/superuser';
-$lang['dont_count_users'] = 'Nie zliczaj zalogownych użytkowników';
diff --git a/lang/se/settings.php b/lang/se/settings.php
deleted file mode 100644
index 5a2b9a1..0000000
--- a/lang/se/settings.php
+++ /dev/null
@@ -1,4 +0,0 @@
-<?php
-$lang['GAID'] = 'Google Analitycs ID';
-$lang['dont_count_admin'] = 'Räkna inte admin/superuser';
-$lang['dont_count_users'] = 'Räkna inte inloggade användare';
diff --git a/lang/zh/settings.php b/lang/zh/settings.php
deleted file mode 100644
index 24586bc..0000000
--- a/lang/zh/settings.php
+++ /dev/null
@@ -1,4 +0,0 @@
-<?php
-$lang['GAID'] = 'Google Analitycs è·è¸ª ID';
-$lang['dont_count_admin'] = 'ä¸ç»è®¡ç®¡çååè¶
级管çå';
-$lang['dont_count_users'] = 'ä¸ç»è®¡å·²ç»å½ç¨æ·';
diff --git a/plugin.info.txt b/plugin.info.txt
index 26f9dc8..20f14ac 100644
--- a/plugin.info.txt
+++ b/plugin.info.txt
@@ -1,7 +1,7 @@
base googleanalytics
author Terence J. Grant
email [email protected]
-date 2020-09-14
-name Google Analytics Plugin 1.0.1
+date 2020-11-03
+name Google Analytics Plugin 1.1.0
desc Plugin to embed your Google Analytics code for your site, which allows you to track your visitors.
url https://www.dokuwiki.org/plugin:googleanalytics
diff --git a/script.js b/script.js
index 76ebb8d..fb1619a 100644
--- a/script.js
+++ b/script.js
@@ -1,71 +1,90 @@
/**
* Set up Google analytics
*
* All configuration is done in the JSINFO.ga object initialized in
* action.php
*/
if (JSINFO.ga) {
- /* default google tracking initialization */
- (function(i, s, o, g, r, a, m) {
- i['GoogleAnalyticsObject'] = r;
- //noinspection CommaExpressionJS
- i[r] = i[r] || function() {
- (i[r].q = i[r].q || []).push(arguments)
- }, i[r].l = 1 * new Date();
- //noinspection CommaExpressionJS
- a = s.createElement(o),
- m = s.getElementsByTagName(o)[0];
- a.async = 1;
- a.src = g;
- m.parentNode.insertBefore(a, m)
- })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
-
- // initalize and set options
- ga('create', JSINFO.ga.trackingId, 'auto', JSINFO.ga.options);
- ga('set', 'forceSSL', true);
- ga('set', 'anonymizeIp', JSINFO.ga.anonymizeIp);
-
- // track pageview and action
- ga('set', 'dimension1', JSINFO.ga.action);
- ga('set', 'dimension2', JSINFO.ga.id);
- ga('send', 'pageview', JSINFO.ga.pageview);
- ga('send', 'event', 'wiki-action', JSINFO.ga.action, JSINFO.id, {
- nonInteraction: true // this is an automatic event with the page load
- });
-
- // The hit payload is also send to the console
- // https://developers.google.com/analytics/devguides/collection/analyticsjs/tasks#overriding_a_task
- if (JSINFO.ga.debug) {
-
- ga(function(tracker) {
-
- // Grab a reference to the default sendHitTask function.
- var originalSendHitTask = tracker.get('sendHitTask');
-
- // Overwrite and add an output to the console
- tracker.set('sendHitTask', function(model) {
- originalSendHitTask(model);
- console.log("Doku Google Analytics Plugin Debug: Hit Payload: " + model.get('hitPayload'));
- });
+ if (JSINFO.ga.gtagId) {
+ /* Global site tag (gtag.js) - Google Analytics */
+
+ var script = document.createElement('script');
+ script.type = 'text/javascript';
+ script.src = 'https://www.googletagmanager.com/gtag/js?id=' + JSINFO.ga.gtagId;
+
+ document.body.appendChild(script);
+
+ window.dataLayer = window.dataLayer || [];
+ function gtag() {
+ dataLayer.push(arguments);
+ }
+
+ gtag('js', new Date());
+ gtag('config', JSINFO.ga.gtagId);
+ } else {
+ /* default google tracking initialization */
+ (function(i, s, o, g, r, a, m) {
+ i['GoogleAnalyticsObject'] = r;
+ //noinspection CommaExpressionJS
+ i[r] = i[r] || function() {
+ (i[r].q = i[r].q || []).push(arguments)
+ }, i[r].l = 1 * new Date();
+ //noinspection CommaExpressionJS
+ a = s.createElement(o),
+ m = s.getElementsByTagName(o)[0];
+ a.async = 1;
+ a.src = g;
+ m.parentNode.insertBefore(a, m)
+ })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
+
+ // initalize and set options
+ ga('create', JSINFO.ga.trackingId, 'auto', JSINFO.ga.options);
+ ga('set', 'forceSSL', true);
+ ga('set', 'anonymizeIp', JSINFO.ga.anonymizeIp);
+
+ // track pageview and action
+ ga('set', 'dimension1', JSINFO.ga.action);
+ ga('set', 'dimension2', JSINFO.ga.id);
+ ga('send', 'pageview', JSINFO.ga.pageview);
+ ga('send', 'event', 'wiki-action', JSINFO.ga.action, JSINFO.id, {
+ nonInteraction: true // this is an automatic event with the page load
});
- }
+ // The hit payload is also send to the console
+ // https://developers.google.com/analytics/devguides/collection/analyticsjs/tasks#overriding_a_task
+ if (JSINFO.ga.debug) {
+
+ ga(function(tracker) {
+
+ // Grab a reference to the default sendHitTask function.
+ var originalSendHitTask = tracker.get('sendHitTask');
+
+ // Overwrite and add an output to the console
+ tracker.set('sendHitTask', function(model) {
+ originalSendHitTask(model);
+ console.log("Doku Google Analytics Plugin Debug: Hit Payload: " + model.get('hitPayload'));
+ });
- // track outgoing links, once the document was loaded
- if (JSINFO.ga.trackOutboundLinks) {
-
- jQuery(function() {
- // https://support.google.com/analytics/answer/1136920?hl=en
- jQuery('a.urlextern, a.interwiki').click(function() {
- var url = this.href;
- if (ga && ga.loaded) {
- ga('send', 'event', 'outbound', 'click', url, {
- 'transport': 'beacon'
- });
- }
});
- });
+ }
+
+ // track outgoing links, once the document was loaded
+ if (JSINFO.ga.trackOutboundLinks) {
+
+ jQuery(function() {
+ // https://support.google.com/analytics/answer/1136920?hl=en
+ jQuery('a.urlextern, a.interwiki').click(function() {
+ var url = this.href;
+ if (ga && ga.loaded) {
+ ga('send', 'event', 'outbound', 'click', url, {
+ 'transport': 'beacon'
+ });
+ }
+ });
+ });
+
+ }
}
}
\ No newline at end of file
|
tatewake/dokuwiki-plugin-googleanalytics | a871ce47ba843d5236fad374c0e0df476543d6df | DPG-20 - Bumped version number and updated changelog | diff --git a/CHANGELOG.md b/CHANGELOG.md
index fca8d18..29802e6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,34 +1,42 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Added
### Changed
### Removed
### Fixed
+## [1.0.1] - 2020-09-14
+
+### Added
+
+- [DPG-20] - Added admin page, icon, and menu text for DokuWiki's administration page;
+
## [1.0.0] - 2020-06-25
### Added
- [DPG-19] - Added this CHANGELOG.md, rewrote README.md and first official version number 1.0.0 and release date to 2020-06-25
### Changed
- [DPG-17] - Auto-reformatted PHP and JS files with [php-cs-fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer) and [js-beautify](https://www.npmjs.com/package/js-beautify)
### Fixed
- [DPG-15] - Fixed an issue where "blank target" was not respected when clicking on a new link
##
+[1.0.1]: https://github.com/tatewake/dokuwiki-plugin-googleanalytics/releases/tag/1.0.1
[1.0.0]: https://github.com/tatewake/dokuwiki-plugin-googleanalytics/releases/tag/1.0.0
+[DPG-20]: http://192.168.1.150/open-source/dokuwiki/googleanalytics/-/issues/20
[DPG-19]: https://github.com/tatewake/dokuwiki-plugin-googleanalytics/issues/19
[DPG-17]: https://github.com/tatewake/dokuwiki-plugin-googleanalytics/issues/17
[DPG-15]: https://github.com/tatewake/dokuwiki-plugin-googleanalytics/issues/15
diff --git a/README.md b/README.md
index 51f7fd6..84b02a6 100644
--- a/README.md
+++ b/README.md
@@ -1,48 +1,48 @@
# Google Analytics for DokuWiki
## License
* **Author**: [Terence J. Grant](mailto:[email protected])
* **License**: [GNU GPL v2](http://opensource.org/licenses/GPL-2.0)
-* **Latest Release**: v1.0.0 on June 25th, 2020
+* **Latest Release**: v1.0.1 on Sep 14th, 2020
* **Changes**: See [CHANGELOG.md](CHANGELOG.md) for full details.
* **Donate**: [Donations](http://tjgrant.com/wiki/donate) and [Sponsorships](https://github.com/sponsors/tatewake) are appreciated!
## About
This tool allows you to set a code for use with [Google Analytics](https://en.wikipedia.org/wiki/Google_Analytics), which allows you to track your visitors.
The plugin also exports a function for use with your template, so you will have to insert the following code into your template (**main.php**), somewhere inside of the `<head></head>` tags.
<?php
if (file_exists(DOKU_PLUGIN.'googleanalytics/code.php')) include_once(DOKU_PLUGIN.'googleanalytics/code.php');
if (function_exists('ga_google_analytics_code')) ga_google_analytics_code();
?>
**Note**: Inserting the code above is **required**, not optional.
**Template Authors Note**: You can insert the above code and make your template "Google Analytics Ready", even if your users do not use Google Analytics (or have this plugin.)
## Install / Upgrade
Search and install the plugin using the [Extension Manager](https://www.dokuwiki.org/plugin:extension). Refer to [Plugins](https://www.dokuwiki.org/plugins) on how to install plugins manually.
## Setup
All further documentation for this plugin can be found at:
* [https://www.dokuwiki.org/plugin:googleanalytics](https://www.dokuwiki.org/plugin:googleanalytics)
## Contributing
The official repository for this plugin is available on GitHub:
* [https://github.com/tatewake/dokuwiki-plugin-googleanalytics](https://github.com/tatewake/dokuwiki-plugin-googleanalytics)
The plugin thrives from community contributions. If you're able to provide useful code changes or bug fixes, they will likely be accepted to future versions of the plugin.
If you find my work helpful and would like to give back, [consider joining me as a GitHub sponsor](https://github.com/sponsors/tatewake).
Thanks!
--Terence
diff --git a/plugin.info.txt b/plugin.info.txt
index 4993115..26f9dc8 100644
--- a/plugin.info.txt
+++ b/plugin.info.txt
@@ -1,7 +1,7 @@
base googleanalytics
author Terence J. Grant
email [email protected]
-date 2020-06-25
-name Google Analytics Plugin 1.0.0
+date 2020-09-14
+name Google Analytics Plugin 1.0.1
desc Plugin to embed your Google Analytics code for your site, which allows you to track your visitors.
url https://www.dokuwiki.org/plugin:googleanalytics
|
tatewake/dokuwiki-plugin-googleanalytics | 3a995d387497c29a2b33c49d6b9191c67baa7e4f | DPG-20 - Added admin page, icon, and menu text for DokuWiki's administration page | diff --git a/action.php b/action.php
index 58355fc..b9d722e 100644
--- a/action.php
+++ b/action.php
@@ -1,123 +1,127 @@
<?php
if (!defined('DOKU_INC')) {
die();
}
if (!defined('DOKU_PLUGIN')) {
define('DOKU_PLUGIN', DOKU_INC . 'lib/plugins/');
}
/**
- * Class action_plugin_googleanalytics
+ * Google Analytics for DokuWiki
+ *
+ * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
+ * @author Terence J. Grant<[email protected]>
*/
+
class action_plugin_googleanalytics extends DokuWiki_Action_Plugin
{
private $gaEnabled = true;
/**
* Register its handlers with the DokuWiki's event controller
*
* @param Doku_Event_Handler $controller
*/
public function register(Doku_Event_Handler $controller)
{
$controller->register_hook('DOKUWIKI_STARTED', 'AFTER', $this, 'gaConfig');
}
/**
* Initialize the Google Analytics config
*
* @param Doku_Event $event
* @param array $param
*/
public function gaConfig(Doku_Event $event, $param)
{
global $JSINFO;
global $INFO;
global $ACT;
if (!$this->gaEnabled) {
return;
}
$trackingId = $this->getConf('GAID');
if (!$trackingId) {
return;
}
if ($this->getConf('dont_count_admin') && $INFO['isadmin']) {
return;
}
if ($this->getConf('dont_count_users') && $_SERVER['REMOTE_USER']) {
return;
}
act_clean($ACT);
$options = array();
if ($this->getConf('track_users') && $_SERVER['REMOTE_USER']) {
$options['userId'] = md5(auth_cookiesalt() . 'googleanalytics' . $_SERVER['REMOTE_USER']);
}
if ($this->getConf('domainName')) {
$options['cookieDomain'] = $this->getConf('domainName');
$options['legacyCookieDomain'] = $this->getConf('domainName');
}
global $conf;
$JSINFO['ga'] = array(
'trackingId' => $trackingId,
'anonymizeIp' => (bool) $this->getConf('anonymize'),
'action' => $ACT,
'trackOutboundLinks' => (bool) $this->getConf('track_links'),
'options' => $options,
'pageview' => $this->getPageView(),
'debug' => (bool) $conf['allowdebug']
);
}
/**
* normalize the pageview
*
* @return string
*/
protected function getPageView()
{
global $QUERY;
global $ID;
global $INPUT;
global $ACT;
// clean up parameters to log
$params = $_GET;
if (isset($params['do'])) {
unset($params['do']);
}
if (isset($params['id'])) {
unset($params['id']);
}
// decide on virtual views
if ($ACT == 'search') {
$view = '~search/';
$params['q'] = $QUERY;
} elseif ($ACT == 'admin') {
$page = $INPUT->str('page');
$view = '~admin';
if ($page) {
$view .= '/' . $page;
}
if (isset($params['page'])) {
unset($params['page']);
}
} else {
$view = str_replace(':', '/', $ID); // slashes needed for Content Drilldown
}
// prepend basedir, allows logging multiple dir based animals in one tracker
$view = DOKU_REL . $view;
// append query parameters
$query = http_build_query($params, '', '&');
if ($query) {
$view .= '?' . $query;
}
return $view;
}
}
diff --git a/admin.php b/admin.php
new file mode 100755
index 0000000..42d66a3
--- /dev/null
+++ b/admin.php
@@ -0,0 +1,34 @@
+<?php
+
+/**
+ * Google Analytics for DokuWiki
+ *
+ * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
+ * @author Terence J. Grant<[email protected]>
+ */
+
+class admin_plugin_googleanalytics extends DokuWiki_Admin_Plugin
+{
+ /** @inheritdoc */
+ public function handle()
+ {
+ global $INPUT;
+ if ($INPUT->post->has('pref') && checkSecurityToken()) {
+ $this->savePreferences($INPUT->post->arr('pref'));
+ }
+ }
+
+ /**
+ * output appropriate html
+ */
+ public function html()
+ {
+ global $INPUT;
+
+ echo '<div class="plugin_cite">';
+
+ echo $this->locale_xhtml('intro');
+
+ echo '</div>';
+ }
+}
diff --git a/admin.svg b/admin.svg
new file mode 100644
index 0000000..5a7f280
--- /dev/null
+++ b/admin.svg
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24" version="1.1">
+<g id="surface1">
+<path style=" stroke:none;fill-rule:nonzero;fill-opacity:1;" d="M 16.5 2.863281 L 16.5 20.863281 C 16.5 22.878906 17.890625 24 19.363281 24 C 20.726562 24 22.226562 23.046875 22.226562 20.863281 L 22.226562 3 C 22.226562 1.152344 20.863281 0 19.363281 0 C 17.863281 0 16.5 1.273438 16.5 2.863281 Z M 16.5 2.863281 "/>
+<path style=" stroke:none;fill-rule:nonzero;fill-opacity:1;" d="M 9 12 L 9 20.863281 C 9 22.878906 10.390625 24 11.863281 24 C 13.226562 24 14.726562 23.046875 14.726562 20.863281 L 14.726562 12.136719 C 14.726562 10.289062 13.363281 9.136719 11.863281 9.136719 C 10.363281 9.136719 9 10.410156 9 12 Z M 9 12 "/>
+<path style=" stroke:none;fill-rule:nonzero;fill-opacity:1;" d="M 7.226562 21.136719 C 7.226562 22.71875 5.945312 24 4.363281 24 C 2.78125 24 1.5 22.71875 1.5 21.136719 C 1.5 19.554688 2.78125 18.273438 4.363281 18.273438 C 5.945312 18.273438 7.226562 19.554688 7.226562 21.136719 Z M 7.226562 21.136719 "/>
+</g>
+</svg>
diff --git a/lang/en/intro.txt b/lang/en/intro.txt
new file mode 100755
index 0000000..dc3c725
--- /dev/null
+++ b/lang/en/intro.txt
@@ -0,0 +1,28 @@
+====== Google Analytics for DokuWiki ======
+
+===== About =====
+
+This tool allows you to set a code for use with [[https://en.wikipedia.org/wiki/Google_Analytics|Google Analytics]], which allows you to track your visitors.
+
+===== Setup =====
+
+The plugin also exports a function for use with your template, so you will have to insert the following code into your template's **main.php**, somewhere inside of the ''<head></head>'' tags.
+
+<code php><?php
+if (file_exists(DOKU_PLUGIN.'googleanalytics/code.php')) include_once(DOKU_PLUGIN.'googleanalytics/code.php');
+if (function_exists('ga_google_analytics_code')) ga_google_analytics_code();
+?></code>
+
+**Note**: Inserting the code above is **required**, not optional.
+
+Set the options for this plugin via the **Configuration Settings** menu from the DokuWiki admin menu. (It will be near the bottom of the page.)
+
+===== For template developers =====
+
+You can insert the above code and make your template "Google Analytics Ready", even if your users do not use Google Analytics (or have this plugin.)
+
+===== Support =====
+
+For further support or discussion, please see the official plugin page [[doku>plugin:googleanalytics|here]].
+
+If you find this plugin useful, please consider supporting the project via [[http://tjgrant.com/wiki/donate|Donations]] or [[https://github.com/sponsors/tatewake|Sponsorships]]; thank you!
diff --git a/lang/en/lang.php b/lang/en/lang.php
new file mode 100755
index 0000000..6c2d239
--- /dev/null
+++ b/lang/en/lang.php
@@ -0,0 +1,5 @@
+<?php
+
+// for admin plugins, the menu prompt to be displayed in the admin menu
+// if set here, the plugin doesn't need to override the getMenuText() method
+$lang['menu'] = 'Google Analytics';
|
tatewake/dokuwiki-plugin-googleanalytics | 81f269bdfba8f378318f08b44b2414285c7054bb | DPG-19 - Added CHANGELOG.md file | diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..fca8d18
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,34 @@
+# Changelog
+All notable changes to this project will be documented in this file.
+
+The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+
+## [Unreleased]
+
+### Added
+### Changed
+### Removed
+### Fixed
+
+## [1.0.0] - 2020-06-25
+
+### Added
+
+- [DPG-19] - Added this CHANGELOG.md, rewrote README.md and first official version number 1.0.0 and release date to 2020-06-25
+
+### Changed
+
+- [DPG-17] - Auto-reformatted PHP and JS files with [php-cs-fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer) and [js-beautify](https://www.npmjs.com/package/js-beautify)
+
+### Fixed
+
+- [DPG-15] - Fixed an issue where "blank target" was not respected when clicking on a new link
+
+##
+
+[1.0.0]: https://github.com/tatewake/dokuwiki-plugin-googleanalytics/releases/tag/1.0.0
+
+[DPG-19]: https://github.com/tatewake/dokuwiki-plugin-googleanalytics/issues/19
+[DPG-17]: https://github.com/tatewake/dokuwiki-plugin-googleanalytics/issues/17
+[DPG-15]: https://github.com/tatewake/dokuwiki-plugin-googleanalytics/issues/15
|
tatewake/dokuwiki-plugin-googleanalytics | f2f4559d80971e5e448d5eb6f80df784a5796acc | DPG-19 - In `plugin.info.txt`, bumped release date and added version number to plugin name | diff --git a/plugin.info.txt b/plugin.info.txt
index 435f8e9..4993115 100644
--- a/plugin.info.txt
+++ b/plugin.info.txt
@@ -1,7 +1,7 @@
base googleanalytics
author Terence J. Grant
email [email protected]
-date 2019-05-21
-name Google Analytics Plugin
+date 2020-06-25
+name Google Analytics Plugin 1.0.0
desc Plugin to embed your Google Analytics code for your site, which allows you to track your visitors.
url https://www.dokuwiki.org/plugin:googleanalytics
|
tatewake/dokuwiki-plugin-googleanalytics | 48732fdba8a09f45f2d2267146edfc859ead83ad | DPG-19 - Rewrote README.md | diff --git a/README b/README
deleted file mode 100644
index 03bbc47..0000000
--- a/README
+++ /dev/null
@@ -1,28 +0,0 @@
-googleanalytics Plugin for DokuWiki
-
-Plugin to embed your Google Analytics code for your site, which
-allows you to track your visitors.
-
-All documentation for this plugin can be found at
-https://www.dokuwiki.org/plugin:googleanalytics
-
-If you install this plugin manually, make sure it is installed in
-lib/plugins/googleanalytics/ - if the folder is called different it
-will not work!
-
-Please refer to http://www.dokuwiki.org/plugins for additional info
-on how to install plugins in DokuWiki.
-
-----
-Copyright (C) Terence J. Grant <[email protected]> et al.
-
-This program is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; version 2 of the License
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU General Public License for more details.
-
-See the COPYING file in your DokuWiki folder for details
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..51f7fd6
--- /dev/null
+++ b/README.md
@@ -0,0 +1,48 @@
+# Google Analytics for DokuWiki
+
+## License
+
+* **Author**: [Terence J. Grant](mailto:[email protected])
+* **License**: [GNU GPL v2](http://opensource.org/licenses/GPL-2.0)
+* **Latest Release**: v1.0.0 on June 25th, 2020
+* **Changes**: See [CHANGELOG.md](CHANGELOG.md) for full details.
+* **Donate**: [Donations](http://tjgrant.com/wiki/donate) and [Sponsorships](https://github.com/sponsors/tatewake) are appreciated!
+
+## About
+
+This tool allows you to set a code for use with [Google Analytics](https://en.wikipedia.org/wiki/Google_Analytics), which allows you to track your visitors.
+
+The plugin also exports a function for use with your template, so you will have to insert the following code into your template (**main.php**), somewhere inside of the `<head></head>` tags.
+
+ <?php
+ if (file_exists(DOKU_PLUGIN.'googleanalytics/code.php')) include_once(DOKU_PLUGIN.'googleanalytics/code.php');
+ if (function_exists('ga_google_analytics_code')) ga_google_analytics_code();
+ ?>
+
+**Note**: Inserting the code above is **required**, not optional.
+
+**Template Authors Note**: You can insert the above code and make your template "Google Analytics Ready", even if your users do not use Google Analytics (or have this plugin.)
+
+## Install / Upgrade
+
+Search and install the plugin using the [Extension Manager](https://www.dokuwiki.org/plugin:extension). Refer to [Plugins](https://www.dokuwiki.org/plugins) on how to install plugins manually.
+
+## Setup
+
+All further documentation for this plugin can be found at:
+
+ * [https://www.dokuwiki.org/plugin:googleanalytics](https://www.dokuwiki.org/plugin:googleanalytics)
+
+## Contributing
+
+The official repository for this plugin is available on GitHub:
+
+* [https://github.com/tatewake/dokuwiki-plugin-googleanalytics](https://github.com/tatewake/dokuwiki-plugin-googleanalytics)
+
+The plugin thrives from community contributions. If you're able to provide useful code changes or bug fixes, they will likely be accepted to future versions of the plugin.
+
+If you find my work helpful and would like to give back, [consider joining me as a GitHub sponsor](https://github.com/sponsors/tatewake).
+
+Thanks!
+
+--Terence
|
tatewake/dokuwiki-plugin-googleanalytics | dc61ac0d1f4d9168155113fc7bed0c67f221a8e3 | DPG-19 - Added LICENSE file | diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..d159169
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,339 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along
+ with this program; if not, write to the Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
|
tatewake/dokuwiki-plugin-googleanalytics | 3632672059796fe1628d1cba05c7bfe73eaf5b67 | DPG-17 - Ran `js-beautify -r` against `script.js` | diff --git a/script.js b/script.js
index afeb6af..76ebb8d 100644
--- a/script.js
+++ b/script.js
@@ -1,71 +1,71 @@
/**
* Set up Google analytics
*
* All configuration is done in the JSINFO.ga object initialized in
* action.php
*/
if (JSINFO.ga) {
/* default google tracking initialization */
- (function (i, s, o, g, r, a, m) {
+ (function(i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
//noinspection CommaExpressionJS
- i[r] = i[r] || function () {
+ i[r] = i[r] || function() {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date();
//noinspection CommaExpressionJS
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
// initalize and set options
ga('create', JSINFO.ga.trackingId, 'auto', JSINFO.ga.options);
ga('set', 'forceSSL', true);
ga('set', 'anonymizeIp', JSINFO.ga.anonymizeIp);
// track pageview and action
ga('set', 'dimension1', JSINFO.ga.action);
ga('set', 'dimension2', JSINFO.ga.id);
ga('send', 'pageview', JSINFO.ga.pageview);
ga('send', 'event', 'wiki-action', JSINFO.ga.action, JSINFO.id, {
nonInteraction: true // this is an automatic event with the page load
});
// The hit payload is also send to the console
// https://developers.google.com/analytics/devguides/collection/analyticsjs/tasks#overriding_a_task
if (JSINFO.ga.debug) {
ga(function(tracker) {
// Grab a reference to the default sendHitTask function.
var originalSendHitTask = tracker.get('sendHitTask');
// Overwrite and add an output to the console
- tracker.set( 'sendHitTask', function (model) {
+ tracker.set('sendHitTask', function(model) {
originalSendHitTask(model);
console.log("Doku Google Analytics Plugin Debug: Hit Payload: " + model.get('hitPayload'));
});
});
}
// track outgoing links, once the document was loaded
if (JSINFO.ga.trackOutboundLinks) {
- jQuery(function () {
+ jQuery(function() {
// https://support.google.com/analytics/answer/1136920?hl=en
- jQuery('a.urlextern, a.interwiki').click(function () {
+ jQuery('a.urlextern, a.interwiki').click(function() {
var url = this.href;
if (ga && ga.loaded) {
ga('send', 'event', 'outbound', 'click', url, {
'transport': 'beacon'
});
}
});
});
}
-}
+}
\ No newline at end of file
|
tatewake/dokuwiki-plugin-googleanalytics | 62cfa419d46a8272ac8adbb5617bd4492fe87920 | DPG-17 - Ran `php-cs-fixer fix . ` to auto-format PHP files to match coding standards, and added `.php_cs.cache` to the `.gitignore` | diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..3d0b430
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+.php_cs.cache
diff --git a/action.php b/action.php
index 0966d14..58355fc 100644
--- a/action.php
+++ b/action.php
@@ -1,98 +1,123 @@
<?php
-if(!defined('DOKU_INC')) die();
-if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN', DOKU_INC . 'lib/plugins/');
+if (!defined('DOKU_INC')) {
+ die();
+}
+if (!defined('DOKU_PLUGIN')) {
+ define('DOKU_PLUGIN', DOKU_INC . 'lib/plugins/');
+}
/**
* Class action_plugin_googleanalytics
*/
-class action_plugin_googleanalytics extends DokuWiki_Action_Plugin {
-
+class action_plugin_googleanalytics extends DokuWiki_Action_Plugin
+{
private $gaEnabled = true;
/**
* Register its handlers with the DokuWiki's event controller
*
* @param Doku_Event_Handler $controller
*/
- function register(Doku_Event_Handler $controller) {
+ public function register(Doku_Event_Handler $controller)
+ {
$controller->register_hook('DOKUWIKI_STARTED', 'AFTER', $this, 'gaConfig');
}
/**
* Initialize the Google Analytics config
*
* @param Doku_Event $event
* @param array $param
*/
- public function gaConfig(Doku_Event $event, $param) {
+ public function gaConfig(Doku_Event $event, $param)
+ {
global $JSINFO;
global $INFO;
global $ACT;
- if(!$this->gaEnabled) return;
+ if (!$this->gaEnabled) {
+ return;
+ }
$trackingId = $this->getConf('GAID');
- if(!$trackingId) return;
- if($this->getConf('dont_count_admin') && $INFO['isadmin']) return;
- if($this->getConf('dont_count_users') && $_SERVER['REMOTE_USER']) return;
+ if (!$trackingId) {
+ return;
+ }
+ if ($this->getConf('dont_count_admin') && $INFO['isadmin']) {
+ return;
+ }
+ if ($this->getConf('dont_count_users') && $_SERVER['REMOTE_USER']) {
+ return;
+ }
act_clean($ACT);
$options = array();
- if($this->getConf('track_users') && $_SERVER['REMOTE_USER']) {
+ if ($this->getConf('track_users') && $_SERVER['REMOTE_USER']) {
$options['userId'] = md5(auth_cookiesalt() . 'googleanalytics' . $_SERVER['REMOTE_USER']);
}
- if($this->getConf('domainName')) {
+ if ($this->getConf('domainName')) {
$options['cookieDomain'] = $this->getConf('domainName');
$options['legacyCookieDomain'] = $this->getConf('domainName');
}
global $conf;
$JSINFO['ga'] = array(
'trackingId' => $trackingId,
'anonymizeIp' => (bool) $this->getConf('anonymize'),
'action' => $ACT,
'trackOutboundLinks' => (bool) $this->getConf('track_links'),
'options' => $options,
'pageview' => $this->getPageView(),
'debug' => (bool) $conf['allowdebug']
);
}
/**
* normalize the pageview
*
* @return string
*/
- protected function getPageView() {
+ protected function getPageView()
+ {
global $QUERY;
global $ID;
global $INPUT;
global $ACT;
// clean up parameters to log
$params = $_GET;
- if(isset($params['do'])) unset($params['do']);
- if(isset($params['id'])) unset($params['id']);
+ if (isset($params['do'])) {
+ unset($params['do']);
+ }
+ if (isset($params['id'])) {
+ unset($params['id']);
+ }
// decide on virtual views
- if($ACT == 'search') {
+ if ($ACT == 'search') {
$view = '~search/';
$params['q'] = $QUERY;
- } elseif($ACT == 'admin') {
+ } elseif ($ACT == 'admin') {
$page = $INPUT->str('page');
$view = '~admin';
- if($page) $view .= '/' . $page;
- if(isset($params['page'])) unset($params['page']);
+ if ($page) {
+ $view .= '/' . $page;
+ }
+ if (isset($params['page'])) {
+ unset($params['page']);
+ }
} else {
$view = str_replace(':', '/', $ID); // slashes needed for Content Drilldown
}
// prepend basedir, allows logging multiple dir based animals in one tracker
$view = DOKU_REL . $view;
// append query parameters
$query = http_build_query($params, '', '&');
- if($query) $view .= '?' . $query;
+ if ($query) {
+ $view .= '?' . $query;
+ }
return $view;
}
}
diff --git a/conf/default.php b/conf/default.php
index ee3f4c7..32682a9 100644
--- a/conf/default.php
+++ b/conf/default.php
@@ -1,9 +1,9 @@
<?php
$conf['GAID'] = '';
$conf['dont_count_admin'] = 0;
$conf['dont_count_users'] = 0;
$conf['anonymize'] = 1;
$conf['track_users'] = 0;
$conf['track_links'] = 0;
-$conf['domainName'] = '';
\ No newline at end of file
+$conf['domainName'] = '';
diff --git a/conf/metadata.php b/conf/metadata.php
index 6a2ea0c..1a70c43 100644
--- a/conf/metadata.php
+++ b/conf/metadata.php
@@ -1,9 +1,9 @@
<?php
$meta['GAID'] = array('string');
$meta['dont_count_admin'] = array('onoff');
$meta['dont_count_users'] = array('onoff');
$meta['anonymize'] = array('onoff');
$meta['track_users'] = array('onoff');
$meta['track_links'] = array('onoff');
-$meta['domainName'] = array('string');
\ No newline at end of file
+$meta['domainName'] = array('string');
diff --git a/lang/pl/settings.php b/lang/pl/settings.php
index d1211bd..a691071 100644
--- a/lang/pl/settings.php
+++ b/lang/pl/settings.php
@@ -1,4 +1,4 @@
<?php
$lang['GAID'] = 'Google Analitycs ID';
$lang['dont_count_admin'] = 'Nie zliczaj: admin/superuser';
-$lang['dont_count_users'] = 'Nie zliczaj zalogownych użytkowników';
\ No newline at end of file
+$lang['dont_count_users'] = 'Nie zliczaj zalogownych użytkowników';
|
tatewake/dokuwiki-plugin-googleanalytics | 39ba546f8a266ba735031f8eea1c414e35df8596 | DPG-17 - Moved `test.html` -> `test/index.html` and ran `js-beautify -r` against it | diff --git a/test.html b/test.html
deleted file mode 100644
index 60e5a40..0000000
--- a/test.html
+++ /dev/null
@@ -1,68 +0,0 @@
-<html lang="ën">
-<head>
- <title>Test page</title>
- <script>
- let JSINFO = {};
- JSINFO.ga = {};
- JSINFO.ga.trackingId = 'UA-XXXXXXX-1';
- JSINFO.ga.trackOutboundLinks = true;
- JSINFO.ga.debug = true;
- </script>
- <script charset="utf-8" src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
- <script src="script.js"></script>
-</head>
-<body>
-<h1>Test Page</h1>
-<p>This is a page that supports testing purpose</p>
-
-<h2>Prerequisites</h2>
-
-Start a web server to serve this page.
-
-Example with browser-sync
-<pre>
-browser-sync start --server --port 3000 --startPath test.html
-</pre>
-
-
-<h2>Test</h2>
-<h3>New tab test</h3>
-
-<ul>
- <li>Test Description: A click on <a href="https://dokuwiki.org" class="urlextern" target="_blank">this Dokuwiki
- link</a> should
- navigate to another tab because of the <a
- href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-target">target value of blank</a>
- </li>
- <li>Check steps:
- <ul>
- <li>Open the devtool console</li>
- <li>Click the link</li>
- <li>Check that a new tab was opened</li>
- <li>Check that the hit payload is shown in the console</li>
- </ul>
- </li>
-</ul>
-<h3>Same tab test</h3>
-<ul>
- <li>Test: A click on <a href="https://dokuwiki.org" class="urlextern">this Dokuwiki link</a> should
- navigate in the same tab.
- </li>
- <li>Check steps:
- <ul>
- <li>Open the browser devtool</li>
- <li>Go to the network tab</li>
- <li>Check `Preserve log` to preserve the log between pages reload</li>
- <li>Clear the network log</li>
- <li>While clicking the link, check the console, you should see briefly the hit</li>
- <li>Check the first item of the network log</li>
- <li>Grab the hit (ie</li>
- <li>Go to <a href="https://ga-dev-tools.appspot.com/hit-builder/">hit builder</a> and validate the hit</li>
- <li>The hit should not be valid because of the tid. The `ec` parameter should show a `outbound` value</li>
- </ul>
- </li>
-
-</ul>
-
-</body>
-</html>
\ No newline at end of file
diff --git a/test/index.html b/test/index.html
new file mode 100644
index 0000000..a67b568
--- /dev/null
+++ b/test/index.html
@@ -0,0 +1,70 @@
+<html lang="en">
+
+<head>
+ <title>Test page</title>
+ <script>
+ let JSINFO = {};
+ JSINFO.ga = {};
+ JSINFO.ga.trackingId = 'UA-XXXXXXX-1';
+ JSINFO.ga.trackOutboundLinks = true;
+ JSINFO.ga.debug = true;
+ </script>
+ <script charset="utf-8" src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
+ <script src="script.js"></script>
+</head>
+
+<body>
+ <h1>Test Page</h1>
+ <p>This is a page that supports testing purpose</p>
+
+ <h2>Prerequisites</h2>
+
+ Start a web server to serve this page.
+
+ Example with browser-sync
+ <pre>
+browser-sync start --server --port 3000 --startPath test.html
+</pre>
+
+
+ <h2>Test</h2>
+ <h3>New tab test</h3>
+
+ <ul>
+ <li>Test Description: A click on <a href="https://dokuwiki.org" class="urlextern" target="_blank">this Dokuwiki
+ link</a> should
+ navigate to another tab because of the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-target">target value of blank</a>
+ </li>
+ <li>Check steps:
+ <ul>
+ <li>Open the devtool console</li>
+ <li>Click the link</li>
+ <li>Check that a new tab was opened</li>
+ <li>Check that the hit payload is shown in the console</li>
+ </ul>
+ </li>
+ </ul>
+ <h3>Same tab test</h3>
+ <ul>
+ <li>Test: A click on <a href="https://dokuwiki.org" class="urlextern">this Dokuwiki link</a> should
+ navigate in the same tab.
+ </li>
+ <li>Check steps:
+ <ul>
+ <li>Open the browser devtool</li>
+ <li>Go to the network tab</li>
+ <li>Check `Preserve log` to preserve the log between pages reload</li>
+ <li>Clear the network log</li>
+ <li>While clicking the link, check the console, you should see briefly the hit</li>
+ <li>Check the first item of the network log</li>
+ <li>Grab the hit (ie</li>
+ <li>Go to <a href="https://ga-dev-tools.appspot.com/hit-builder/">hit builder</a> and validate the hit</li>
+ <li>The hit should not be valid because of the tid. The `ec` parameter should show a `outbound` value</li>
+ </ul>
+ </li>
+
+ </ul>
+
+</body>
+
+</html>
\ No newline at end of file
|
tatewake/dokuwiki-plugin-googleanalytics | 9f686c8661f8765baa28b16745651841e1e43998 | Remove `$lang['debug']` as it's not needed locally | diff --git a/lang/en/settings.php b/lang/en/settings.php
index 1746d46..ac0480a 100644
--- a/lang/en/settings.php
+++ b/lang/en/settings.php
@@ -1,10 +1,8 @@
<?php
$lang['GAID'] = 'Your Google Analytics ID (UA-XXXXXX-XX)';
$lang['dont_count_admin'] = 'Don\'t count admin/superuser';
$lang['dont_count_users'] = 'Don\'t count logged in users';
$lang['anonymize'] = 'Send anonymized IP addresses to Google.';
$lang['track_users'] = 'Track logged in users across different devices. Needs <a href="https://support.google.com/analytics/answer/3123662?hl=en">user tracking</a> enabled. Users will not be identifable in Google Analytics!';
$lang['track_links'] = 'Track outgoing links.';
$lang['domainName'] = 'Configure the cookie domain. Should usually be left empty';
-$lang['debug'] = 'Debug mode: Send the hits to the console';
-
|
tatewake/dokuwiki-plugin-googleanalytics | 0321452a5908aeb308de7ec72db85c84e4ef9d0d | Replaced debug by $conf['allowdebug'] | diff --git a/action.php b/action.php
index a5d4622..0966d14 100644
--- a/action.php
+++ b/action.php
@@ -1,97 +1,98 @@
<?php
if(!defined('DOKU_INC')) die();
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN', DOKU_INC . 'lib/plugins/');
/**
* Class action_plugin_googleanalytics
*/
class action_plugin_googleanalytics extends DokuWiki_Action_Plugin {
private $gaEnabled = true;
/**
* Register its handlers with the DokuWiki's event controller
*
* @param Doku_Event_Handler $controller
*/
function register(Doku_Event_Handler $controller) {
$controller->register_hook('DOKUWIKI_STARTED', 'AFTER', $this, 'gaConfig');
}
/**
* Initialize the Google Analytics config
*
* @param Doku_Event $event
* @param array $param
*/
public function gaConfig(Doku_Event $event, $param) {
global $JSINFO;
global $INFO;
global $ACT;
if(!$this->gaEnabled) return;
$trackingId = $this->getConf('GAID');
if(!$trackingId) return;
if($this->getConf('dont_count_admin') && $INFO['isadmin']) return;
if($this->getConf('dont_count_users') && $_SERVER['REMOTE_USER']) return;
act_clean($ACT);
$options = array();
if($this->getConf('track_users') && $_SERVER['REMOTE_USER']) {
$options['userId'] = md5(auth_cookiesalt() . 'googleanalytics' . $_SERVER['REMOTE_USER']);
}
if($this->getConf('domainName')) {
$options['cookieDomain'] = $this->getConf('domainName');
$options['legacyCookieDomain'] = $this->getConf('domainName');
}
+ global $conf;
$JSINFO['ga'] = array(
'trackingId' => $trackingId,
'anonymizeIp' => (bool) $this->getConf('anonymize'),
'action' => $ACT,
'trackOutboundLinks' => (bool) $this->getConf('track_links'),
'options' => $options,
'pageview' => $this->getPageView(),
- 'debug' => (bool) $this->getConf('debug')
+ 'debug' => (bool) $conf['allowdebug']
);
}
/**
* normalize the pageview
*
* @return string
*/
protected function getPageView() {
global $QUERY;
global $ID;
global $INPUT;
global $ACT;
// clean up parameters to log
$params = $_GET;
if(isset($params['do'])) unset($params['do']);
if(isset($params['id'])) unset($params['id']);
// decide on virtual views
if($ACT == 'search') {
$view = '~search/';
$params['q'] = $QUERY;
} elseif($ACT == 'admin') {
$page = $INPUT->str('page');
$view = '~admin';
if($page) $view .= '/' . $page;
if(isset($params['page'])) unset($params['page']);
} else {
$view = str_replace(':', '/', $ID); // slashes needed for Content Drilldown
}
// prepend basedir, allows logging multiple dir based animals in one tracker
$view = DOKU_REL . $view;
// append query parameters
$query = http_build_query($params, '', '&');
if($query) $view .= '?' . $query;
return $view;
}
}
diff --git a/conf/default.php b/conf/default.php
index bca11a6..ee3f4c7 100644
--- a/conf/default.php
+++ b/conf/default.php
@@ -1,10 +1,9 @@
<?php
$conf['GAID'] = '';
$conf['dont_count_admin'] = 0;
$conf['dont_count_users'] = 0;
$conf['anonymize'] = 1;
$conf['track_users'] = 0;
$conf['track_links'] = 0;
-$conf['domainName'] = '';
-$conf['debug'] = 1;
\ No newline at end of file
+$conf['domainName'] = '';
\ No newline at end of file
diff --git a/conf/metadata.php b/conf/metadata.php
index 7b9f2ad..6a2ea0c 100644
--- a/conf/metadata.php
+++ b/conf/metadata.php
@@ -1,10 +1,9 @@
<?php
$meta['GAID'] = array('string');
$meta['dont_count_admin'] = array('onoff');
$meta['dont_count_users'] = array('onoff');
$meta['anonymize'] = array('onoff');
$meta['track_users'] = array('onoff');
$meta['track_links'] = array('onoff');
-$meta['domainName'] = array('string');
-$meta['debug'] = array('onoff');
\ No newline at end of file
+$meta['domainName'] = array('string');
\ No newline at end of file
|
tatewake/dokuwiki-plugin-googleanalytics | 2b86c1a8f4d8e28a1ae42e40da69cc4f44434195 | Added a debug mode that prints the hit payload Enhanced the test page with check steps Deleted the callback on outbound as it's not needed | diff --git a/action.php b/action.php
index f255dc5..a5d4622 100644
--- a/action.php
+++ b/action.php
@@ -1,96 +1,97 @@
<?php
if(!defined('DOKU_INC')) die();
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN', DOKU_INC . 'lib/plugins/');
/**
* Class action_plugin_googleanalytics
*/
class action_plugin_googleanalytics extends DokuWiki_Action_Plugin {
private $gaEnabled = true;
/**
* Register its handlers with the DokuWiki's event controller
*
* @param Doku_Event_Handler $controller
*/
function register(Doku_Event_Handler $controller) {
$controller->register_hook('DOKUWIKI_STARTED', 'AFTER', $this, 'gaConfig');
}
/**
* Initialize the Google Analytics config
*
* @param Doku_Event $event
* @param array $param
*/
public function gaConfig(Doku_Event $event, $param) {
global $JSINFO;
global $INFO;
global $ACT;
if(!$this->gaEnabled) return;
$trackingId = $this->getConf('GAID');
if(!$trackingId) return;
if($this->getConf('dont_count_admin') && $INFO['isadmin']) return;
if($this->getConf('dont_count_users') && $_SERVER['REMOTE_USER']) return;
act_clean($ACT);
$options = array();
if($this->getConf('track_users') && $_SERVER['REMOTE_USER']) {
$options['userId'] = md5(auth_cookiesalt() . 'googleanalytics' . $_SERVER['REMOTE_USER']);
}
if($this->getConf('domainName')) {
$options['cookieDomain'] = $this->getConf('domainName');
$options['legacyCookieDomain'] = $this->getConf('domainName');
}
$JSINFO['ga'] = array(
'trackingId' => $trackingId,
'anonymizeIp' => (bool) $this->getConf('anonymize'),
'action' => $ACT,
'trackOutboundLinks' => (bool) $this->getConf('track_links'),
'options' => $options,
'pageview' => $this->getPageView(),
+ 'debug' => (bool) $this->getConf('debug')
);
}
/**
* normalize the pageview
*
* @return string
*/
protected function getPageView() {
global $QUERY;
global $ID;
global $INPUT;
global $ACT;
// clean up parameters to log
$params = $_GET;
if(isset($params['do'])) unset($params['do']);
if(isset($params['id'])) unset($params['id']);
// decide on virtual views
if($ACT == 'search') {
$view = '~search/';
$params['q'] = $QUERY;
} elseif($ACT == 'admin') {
$page = $INPUT->str('page');
$view = '~admin';
if($page) $view .= '/' . $page;
if(isset($params['page'])) unset($params['page']);
} else {
$view = str_replace(':', '/', $ID); // slashes needed for Content Drilldown
}
// prepend basedir, allows logging multiple dir based animals in one tracker
$view = DOKU_REL . $view;
// append query parameters
$query = http_build_query($params, '', '&');
if($query) $view .= '?' . $query;
return $view;
}
}
diff --git a/conf/default.php b/conf/default.php
index 32682a9..bca11a6 100644
--- a/conf/default.php
+++ b/conf/default.php
@@ -1,9 +1,10 @@
<?php
$conf['GAID'] = '';
$conf['dont_count_admin'] = 0;
$conf['dont_count_users'] = 0;
$conf['anonymize'] = 1;
$conf['track_users'] = 0;
$conf['track_links'] = 0;
$conf['domainName'] = '';
+$conf['debug'] = 1;
\ No newline at end of file
diff --git a/conf/metadata.php b/conf/metadata.php
index 1a70c43..7b9f2ad 100644
--- a/conf/metadata.php
+++ b/conf/metadata.php
@@ -1,9 +1,10 @@
<?php
$meta['GAID'] = array('string');
$meta['dont_count_admin'] = array('onoff');
$meta['dont_count_users'] = array('onoff');
$meta['anonymize'] = array('onoff');
$meta['track_users'] = array('onoff');
$meta['track_links'] = array('onoff');
$meta['domainName'] = array('string');
+$meta['debug'] = array('onoff');
\ No newline at end of file
diff --git a/lang/en/settings.php b/lang/en/settings.php
index 198ab30..1746d46 100644
--- a/lang/en/settings.php
+++ b/lang/en/settings.php
@@ -1,9 +1,10 @@
<?php
$lang['GAID'] = 'Your Google Analytics ID (UA-XXXXXX-XX)';
$lang['dont_count_admin'] = 'Don\'t count admin/superuser';
$lang['dont_count_users'] = 'Don\'t count logged in users';
$lang['anonymize'] = 'Send anonymized IP addresses to Google.';
$lang['track_users'] = 'Track logged in users across different devices. Needs <a href="https://support.google.com/analytics/answer/3123662?hl=en">user tracking</a> enabled. Users will not be identifable in Google Analytics!';
$lang['track_links'] = 'Track outgoing links.';
$lang['domainName'] = 'Configure the cookie domain. Should usually be left empty';
+$lang['debug'] = 'Debug mode: Send the hits to the console';
diff --git a/script.js b/script.js
index 9078631..afeb6af 100644
--- a/script.js
+++ b/script.js
@@ -1,53 +1,71 @@
/**
* Set up Google analytics
*
* All configuration is done in the JSINFO.ga object initialized in
* action.php
*/
if (JSINFO.ga) {
/* default google tracking initialization */
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
//noinspection CommaExpressionJS
i[r] = i[r] || function () {
- (i[r].q = i[r].q || []).push(arguments)
- }, i[r].l = 1 * new Date();
+ (i[r].q = i[r].q || []).push(arguments)
+ }, i[r].l = 1 * new Date();
//noinspection CommaExpressionJS
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
// initalize and set options
ga('create', JSINFO.ga.trackingId, 'auto', JSINFO.ga.options);
ga('set', 'forceSSL', true);
ga('set', 'anonymizeIp', JSINFO.ga.anonymizeIp);
// track pageview and action
ga('set', 'dimension1', JSINFO.ga.action);
ga('set', 'dimension2', JSINFO.ga.id);
ga('send', 'pageview', JSINFO.ga.pageview);
ga('send', 'event', 'wiki-action', JSINFO.ga.action, JSINFO.id, {
nonInteraction: true // this is an automatic event with the page load
});
+ // The hit payload is also send to the console
+ // https://developers.google.com/analytics/devguides/collection/analyticsjs/tasks#overriding_a_task
+ if (JSINFO.ga.debug) {
+
+ ga(function(tracker) {
+
+ // Grab a reference to the default sendHitTask function.
+ var originalSendHitTask = tracker.get('sendHitTask');
+
+ // Overwrite and add an output to the console
+ tracker.set( 'sendHitTask', function (model) {
+ originalSendHitTask(model);
+ console.log("Doku Google Analytics Plugin Debug: Hit Payload: " + model.get('hitPayload'));
+ });
+
+ });
+
+ }
+
// track outgoing links, once the document was loaded
if (JSINFO.ga.trackOutboundLinks) {
+
jQuery(function () {
// https://support.google.com/analytics/answer/1136920?hl=en
- jQuery('a.urlextern, a.interwiki').click(function (e) {
+ jQuery('a.urlextern, a.interwiki').click(function () {
var url = this.href;
- var hitCallback = function(){document.location = url;};
- if(ga && ga.loaded){
- // e.preventDefault(); // Prevent a target=_blank on the link to work
+ if (ga && ga.loaded) {
ga('send', 'event', 'outbound', 'click', url, {
- 'transport': 'beacon',
- 'hitCallback': hitCallback
+ 'transport': 'beacon'
});
}
});
});
+
}
}
diff --git a/test.html b/test.html
index 3f1c0a7..60e5a40 100644
--- a/test.html
+++ b/test.html
@@ -1,24 +1,68 @@
-<html>
+<html lang="ën">
<head>
+ <title>Test page</title>
<script>
- let JSINFO = {};
- JSINFO.ga= {};
- JSINFO.ga.trackOutboundLinks = true;
+ let JSINFO = {};
+ JSINFO.ga = {};
+ JSINFO.ga.trackingId = 'UA-XXXXXXX-1';
+ JSINFO.ga.trackOutboundLinks = true;
+ JSINFO.ga.debug = true;
</script>
<script charset="utf-8" src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>Test Page</h1>
-<p>This is a page that support testing purpose</p>
+<p>This is a page that supports testing purpose</p>
-<h2>A link with a target _blank </h2>
-A link <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-target">target value of blank</a> should navigate by opening a new tab.
+<h2>Prerequisites</h2>
+
+Start a web server to serve this page.
+
+Example with browser-sync
+<pre>
+browser-sync start --server --port 3000 --startPath test.html
+</pre>
+
+
+<h2>Test</h2>
+<h3>New tab test</h3>
<ul>
- <li>Click on on <a href="https://dokuwiki.org" class="urlextern" target="_blank" rel="noopener">this Dokuwiki link</a></li>
- <li>If a new tab was opened: the test result is pass</li>
+ <li>Test Description: A click on <a href="https://dokuwiki.org" class="urlextern" target="_blank">this Dokuwiki
+ link</a> should
+ navigate to another tab because of the <a
+ href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-target">target value of blank</a>
+ </li>
+ <li>Check steps:
+ <ul>
+ <li>Open the devtool console</li>
+ <li>Click the link</li>
+ <li>Check that a new tab was opened</li>
+ <li>Check that the hit payload is shown in the console</li>
+ </ul>
+ </li>
+</ul>
+<h3>Same tab test</h3>
+<ul>
+ <li>Test: A click on <a href="https://dokuwiki.org" class="urlextern">this Dokuwiki link</a> should
+ navigate in the same tab.
+ </li>
+ <li>Check steps:
+ <ul>
+ <li>Open the browser devtool</li>
+ <li>Go to the network tab</li>
+ <li>Check `Preserve log` to preserve the log between pages reload</li>
+ <li>Clear the network log</li>
+ <li>While clicking the link, check the console, you should see briefly the hit</li>
+ <li>Check the first item of the network log</li>
+ <li>Grab the hit (ie</li>
+ <li>Go to <a href="https://ga-dev-tools.appspot.com/hit-builder/">hit builder</a> and validate the hit</li>
+ <li>The hit should not be valid because of the tid. The `ec` parameter should show a `outbound` value</li>
+ </ul>
+ </li>
+
</ul>
</body>
</html>
\ No newline at end of file
|
tatewake/dokuwiki-plugin-googleanalytics | 0cc3641d9c21998b2eb3af2465e6707a4849eba8 | Target blank was not respectged when clicking on a new link | diff --git a/script.js b/script.js
index 69714bc..9078631 100644
--- a/script.js
+++ b/script.js
@@ -1,53 +1,53 @@
/**
* Set up Google analytics
*
* All configuration is done in the JSINFO.ga object initialized in
* action.php
*/
if (JSINFO.ga) {
/* default google tracking initialization */
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
//noinspection CommaExpressionJS
i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date();
//noinspection CommaExpressionJS
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
// initalize and set options
ga('create', JSINFO.ga.trackingId, 'auto', JSINFO.ga.options);
ga('set', 'forceSSL', true);
ga('set', 'anonymizeIp', JSINFO.ga.anonymizeIp);
// track pageview and action
ga('set', 'dimension1', JSINFO.ga.action);
ga('set', 'dimension2', JSINFO.ga.id);
ga('send', 'pageview', JSINFO.ga.pageview);
ga('send', 'event', 'wiki-action', JSINFO.ga.action, JSINFO.id, {
nonInteraction: true // this is an automatic event with the page load
});
// track outgoing links, once the document was loaded
if (JSINFO.ga.trackOutboundLinks) {
jQuery(function () {
// https://support.google.com/analytics/answer/1136920?hl=en
jQuery('a.urlextern, a.interwiki').click(function (e) {
var url = this.href;
var hitCallback = function(){document.location = url;};
if(ga && ga.loaded){
- e.preventDefault();
+ // e.preventDefault(); // Prevent a target=_blank on the link to work
ga('send', 'event', 'outbound', 'click', url, {
'transport': 'beacon',
'hitCallback': hitCallback
});
}
});
});
}
}
diff --git a/test.html b/test.html
new file mode 100644
index 0000000..3f1c0a7
--- /dev/null
+++ b/test.html
@@ -0,0 +1,24 @@
+<html>
+<head>
+ <script>
+ let JSINFO = {};
+ JSINFO.ga= {};
+ JSINFO.ga.trackOutboundLinks = true;
+ </script>
+ <script charset="utf-8" src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
+ <script src="script.js"></script>
+</head>
+<body>
+<h1>Test Page</h1>
+<p>This is a page that support testing purpose</p>
+
+<h2>A link with a target _blank </h2>
+A link <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-target">target value of blank</a> should navigate by opening a new tab.
+
+<ul>
+ <li>Click on on <a href="https://dokuwiki.org" class="urlextern" target="_blank" rel="noopener">this Dokuwiki link</a></li>
+ <li>If a new tab was opened: the test result is pass</li>
+</ul>
+
+</body>
+</html>
\ No newline at end of file
|
tatewake/dokuwiki-plugin-googleanalytics | 5b460905b50c89c84f441c7f19882fbdc0df5d63 | fix-track-link - Updated `plugin.info.txt` to reflect a new release date (for DW's plugin manager) | diff --git a/plugin.info.txt b/plugin.info.txt
index ab22a9d..435f8e9 100644
--- a/plugin.info.txt
+++ b/plugin.info.txt
@@ -1,7 +1,7 @@
base googleanalytics
author Terence J. Grant
email [email protected]
-date 2017-02-07
+date 2019-05-21
name Google Analytics Plugin
desc Plugin to embed your Google Analytics code for your site, which allows you to track your visitors.
url https://www.dokuwiki.org/plugin:googleanalytics
|
tatewake/dokuwiki-plugin-googleanalytics | 63befc3674f8b92cf31c1808ed93623bd1dbdbb3 | Check ga existence before tracking links | diff --git a/script.js b/script.js
index 0c82406..69714bc 100644
--- a/script.js
+++ b/script.js
@@ -1,52 +1,53 @@
/**
* Set up Google analytics
*
* All configuration is done in the JSINFO.ga object initialized in
* action.php
*/
if (JSINFO.ga) {
/* default google tracking initialization */
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
//noinspection CommaExpressionJS
i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date();
//noinspection CommaExpressionJS
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
// initalize and set options
ga('create', JSINFO.ga.trackingId, 'auto', JSINFO.ga.options);
ga('set', 'forceSSL', true);
ga('set', 'anonymizeIp', JSINFO.ga.anonymizeIp);
// track pageview and action
ga('set', 'dimension1', JSINFO.ga.action);
ga('set', 'dimension2', JSINFO.ga.id);
ga('send', 'pageview', JSINFO.ga.pageview);
ga('send', 'event', 'wiki-action', JSINFO.ga.action, JSINFO.id, {
nonInteraction: true // this is an automatic event with the page load
});
// track outgoing links, once the document was loaded
if (JSINFO.ga.trackOutboundLinks) {
jQuery(function () {
// https://support.google.com/analytics/answer/1136920?hl=en
jQuery('a.urlextern, a.interwiki').click(function (e) {
- e.preventDefault();
var url = this.href;
- ga('send', 'event', 'outbound', 'click', url, {
- 'transport': 'beacon',
- 'hitCallback': function () {
- document.location = url;
- }
- });
+ var hitCallback = function(){document.location = url;};
+ if(ga && ga.loaded){
+ e.preventDefault();
+ ga('send', 'event', 'outbound', 'click', url, {
+ 'transport': 'beacon',
+ 'hitCallback': hitCallback
+ });
+ }
});
});
}
}
|
tatewake/dokuwiki-plugin-googleanalytics | 99eac117481ab13c627725603378ec3302f056b1 | added readme | diff --git a/README b/README
new file mode 100644
index 0000000..03bbc47
--- /dev/null
+++ b/README
@@ -0,0 +1,28 @@
+googleanalytics Plugin for DokuWiki
+
+Plugin to embed your Google Analytics code for your site, which
+allows you to track your visitors.
+
+All documentation for this plugin can be found at
+https://www.dokuwiki.org/plugin:googleanalytics
+
+If you install this plugin manually, make sure it is installed in
+lib/plugins/googleanalytics/ - if the folder is called different it
+will not work!
+
+Please refer to http://www.dokuwiki.org/plugins for additional info
+on how to install plugins in DokuWiki.
+
+----
+Copyright (C) Terence J. Grant <[email protected]> et al.
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; version 2 of the License
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+See the COPYING file in your DokuWiki folder for details
|
tatewake/dokuwiki-plugin-googleanalytics | 8ea4e30b5d09861f9af6449da671420519573128 | clarified setting descriptions | diff --git a/lang/en/settings.php b/lang/en/settings.php
index 0a1b1ec..198ab30 100644
--- a/lang/en/settings.php
+++ b/lang/en/settings.php
@@ -1,9 +1,9 @@
<?php
-$lang['GAID'] = 'Your Google Analytics ID (UA-XXXXX)';
+$lang['GAID'] = 'Your Google Analytics ID (UA-XXXXXX-XX)';
$lang['dont_count_admin'] = 'Don\'t count admin/superuser';
$lang['dont_count_users'] = 'Don\'t count logged in users';
-$lang['anonymize'] = 'Send anonymized IP addresses to google.';
-$lang['track_users'] = 'Track logged in users. Needs <a href="https://support.google.com/analytics/answer/3123662?hl=en">user tracking</a> enabled. Users will not be identifable in Google Analytics.';
+$lang['anonymize'] = 'Send anonymized IP addresses to Google.';
+$lang['track_users'] = 'Track logged in users across different devices. Needs <a href="https://support.google.com/analytics/answer/3123662?hl=en">user tracking</a> enabled. Users will not be identifable in Google Analytics!';
$lang['track_links'] = 'Track outgoing links.';
-$lang['domainName'] = 'Configure the cookie domain - useful if the tracker is shared over multiple sub domains. Leave empty for automatic detection';
+$lang['domainName'] = 'Configure the cookie domain. Should usually be left empty';
|
tatewake/dokuwiki-plugin-googleanalytics | 354d3118fa2d088e1cb71bdef2d7a2c771fd55c8 | log action and id as dimensions | diff --git a/script.js b/script.js
index 3765f3a..0c82406 100644
--- a/script.js
+++ b/script.js
@@ -1,50 +1,52 @@
/**
* Set up Google analytics
*
* All configuration is done in the JSINFO.ga object initialized in
* action.php
*/
if (JSINFO.ga) {
/* default google tracking initialization */
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
//noinspection CommaExpressionJS
i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date();
//noinspection CommaExpressionJS
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
// initalize and set options
ga('create', JSINFO.ga.trackingId, 'auto', JSINFO.ga.options);
ga('set', 'forceSSL', true);
ga('set', 'anonymizeIp', JSINFO.ga.anonymizeIp);
// track pageview and action
+ ga('set', 'dimension1', JSINFO.ga.action);
+ ga('set', 'dimension2', JSINFO.ga.id);
ga('send', 'pageview', JSINFO.ga.pageview);
ga('send', 'event', 'wiki-action', JSINFO.ga.action, JSINFO.id, {
nonInteraction: true // this is an automatic event with the page load
});
// track outgoing links, once the document was loaded
if (JSINFO.ga.trackOutboundLinks) {
jQuery(function () {
// https://support.google.com/analytics/answer/1136920?hl=en
jQuery('a.urlextern, a.interwiki').click(function (e) {
e.preventDefault();
var url = this.href;
ga('send', 'event', 'outbound', 'click', url, {
'transport': 'beacon',
'hitCallback': function () {
document.location = url;
}
});
});
});
}
}
|
tatewake/dokuwiki-plugin-googleanalytics | 8d83c8a07d0d00b0acf3a4ffb74b141d78ac2379 | keep the query string (after some cleanup) | diff --git a/action.php b/action.php
index 12e0394..f255dc5 100644
--- a/action.php
+++ b/action.php
@@ -1,71 +1,96 @@
<?php
if(!defined('DOKU_INC')) die();
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN', DOKU_INC . 'lib/plugins/');
/**
* Class action_plugin_googleanalytics
*/
class action_plugin_googleanalytics extends DokuWiki_Action_Plugin {
private $gaEnabled = true;
/**
* Register its handlers with the DokuWiki's event controller
*
* @param Doku_Event_Handler $controller
*/
function register(Doku_Event_Handler $controller) {
$controller->register_hook('DOKUWIKI_STARTED', 'AFTER', $this, 'gaConfig');
}
/**
* Initialize the Google Analytics config
*
* @param Doku_Event $event
* @param array $param
*/
public function gaConfig(Doku_Event $event, $param) {
global $JSINFO;
global $INFO;
global $ACT;
- global $QUERY;
- global $ID;
- global $INPUT;
if(!$this->gaEnabled) return;
$trackingId = $this->getConf('GAID');
if(!$trackingId) return;
if($this->getConf('dont_count_admin') && $INFO['isadmin']) return;
if($this->getConf('dont_count_users') && $_SERVER['REMOTE_USER']) return;
+ act_clean($ACT);
$options = array();
if($this->getConf('track_users') && $_SERVER['REMOTE_USER']) {
$options['userId'] = md5(auth_cookiesalt() . 'googleanalytics' . $_SERVER['REMOTE_USER']);
}
if($this->getConf('domainName')) {
$options['cookieDomain'] = $this->getConf('domainName');
$options['legacyCookieDomain'] = $this->getConf('domainName');
}
- // normalize the pageview
+ $JSINFO['ga'] = array(
+ 'trackingId' => $trackingId,
+ 'anonymizeIp' => (bool) $this->getConf('anonymize'),
+ 'action' => $ACT,
+ 'trackOutboundLinks' => (bool) $this->getConf('track_links'),
+ 'options' => $options,
+ 'pageview' => $this->getPageView(),
+ );
+ }
+
+ /**
+ * normalize the pageview
+ *
+ * @return string
+ */
+ protected function getPageView() {
+ global $QUERY;
+ global $ID;
+ global $INPUT;
+ global $ACT;
+
+ // clean up parameters to log
+ $params = $_GET;
+ if(isset($params['do'])) unset($params['do']);
+ if(isset($params['id'])) unset($params['id']);
+
+ // decide on virtual views
if($ACT == 'search') {
- $view = '~search/?' . rawurlencode($QUERY);
+ $view = '~search/';
+ $params['q'] = $QUERY;
} elseif($ACT == 'admin') {
$page = $INPUT->str('page');
$view = '~admin';
if($page) $view .= '/' . $page;
+ if(isset($params['page'])) unset($params['page']);
} else {
$view = str_replace(':', '/', $ID); // slashes needed for Content Drilldown
}
- $view = DOKU_REL . $view; // prepend basedir, allows logging multiple dir based animals in one tracker
- $JSINFO['ga'] = array(
- 'trackingId' => $trackingId,
- 'anonymizeIp' => (bool) $this->getConf('anonymize'),
- 'action' => act_clean($ACT),
- 'trackOutboundLinks' => (bool) $this->getConf('track_links'),
- 'options' => $options,
- 'pageview' => $view
- );
+ // prepend basedir, allows logging multiple dir based animals in one tracker
+ $view = DOKU_REL . $view;
+
+ // append query parameters
+ $query = http_build_query($params, '', '&');
+ if($query) $view .= '?' . $query;
+
+ return $view;
}
}
|
tatewake/dokuwiki-plugin-googleanalytics | d77839759731649e25fdb719eaa9d512caddee2b | normalize page views | diff --git a/action.php b/action.php
index a0c243f..12e0394 100644
--- a/action.php
+++ b/action.php
@@ -1,55 +1,71 @@
<?php
if(!defined('DOKU_INC')) die();
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN', DOKU_INC . 'lib/plugins/');
/**
* Class action_plugin_googleanalytics
*/
class action_plugin_googleanalytics extends DokuWiki_Action_Plugin {
private $gaEnabled = true;
/**
* Register its handlers with the DokuWiki's event controller
*
* @param Doku_Event_Handler $controller
*/
function register(Doku_Event_Handler $controller) {
$controller->register_hook('DOKUWIKI_STARTED', 'AFTER', $this, 'gaConfig');
}
/**
* Initialize the Google Analytics config
*
* @param Doku_Event $event
* @param array $param
*/
public function gaConfig(Doku_Event $event, $param) {
global $JSINFO;
global $INFO;
global $ACT;
+ global $QUERY;
+ global $ID;
+ global $INPUT;
if(!$this->gaEnabled) return;
$trackingId = $this->getConf('GAID');
if(!$trackingId) return;
if($this->getConf('dont_count_admin') && $INFO['isadmin']) return;
if($this->getConf('dont_count_users') && $_SERVER['REMOTE_USER']) return;
$options = array();
if($this->getConf('track_users') && $_SERVER['REMOTE_USER']) {
$options['userId'] = md5(auth_cookiesalt() . 'googleanalytics' . $_SERVER['REMOTE_USER']);
}
if($this->getConf('domainName')) {
$options['cookieDomain'] = $this->getConf('domainName');
$options['legacyCookieDomain'] = $this->getConf('domainName');
}
+ // normalize the pageview
+ if($ACT == 'search') {
+ $view = '~search/?' . rawurlencode($QUERY);
+ } elseif($ACT == 'admin') {
+ $page = $INPUT->str('page');
+ $view = '~admin';
+ if($page) $view .= '/' . $page;
+ } else {
+ $view = str_replace(':', '/', $ID); // slashes needed for Content Drilldown
+ }
+ $view = DOKU_REL . $view; // prepend basedir, allows logging multiple dir based animals in one tracker
+
$JSINFO['ga'] = array(
'trackingId' => $trackingId,
'anonymizeIp' => (bool) $this->getConf('anonymize'),
'action' => act_clean($ACT),
'trackOutboundLinks' => (bool) $this->getConf('track_links'),
'options' => $options,
+ 'pageview' => $view
);
}
}
diff --git a/script.js b/script.js
index 0b14024..3765f3a 100644
--- a/script.js
+++ b/script.js
@@ -1,50 +1,50 @@
/**
* Set up Google analytics
*
* All configuration is done in the JSINFO.ga object initialized in
* action.php
*/
if (JSINFO.ga) {
/* default google tracking initialization */
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
//noinspection CommaExpressionJS
i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date();
//noinspection CommaExpressionJS
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
// initalize and set options
ga('create', JSINFO.ga.trackingId, 'auto', JSINFO.ga.options);
ga('set', 'forceSSL', true);
ga('set', 'anonymizeIp', JSINFO.ga.anonymizeIp);
// track pageview and action
- ga('send', 'pageview');
+ ga('send', 'pageview', JSINFO.ga.pageview);
ga('send', 'event', 'wiki-action', JSINFO.ga.action, JSINFO.id, {
nonInteraction: true // this is an automatic event with the page load
});
// track outgoing links, once the document was loaded
if (JSINFO.ga.trackOutboundLinks) {
jQuery(function () {
// https://support.google.com/analytics/answer/1136920?hl=en
jQuery('a.urlextern, a.interwiki').click(function (e) {
e.preventDefault();
var url = this.href;
ga('send', 'event', 'outbound', 'click', url, {
'transport': 'beacon',
'hitCallback': function () {
document.location = url;
}
});
});
});
}
}
|
tatewake/dokuwiki-plugin-googleanalytics | 02cda0187b791e5ddb7f9dd6aeabf66530255ad5 | rewrite of most of the tracking code | diff --git a/action.php b/action.php
index 528dd98..a0c243f 100644
--- a/action.php
+++ b/action.php
@@ -1,92 +1,55 @@
<?php
if(!defined('DOKU_INC')) die();
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN', DOKU_INC . 'lib/plugins/');
/**
* Class action_plugin_googleanalytics
*/
class action_plugin_googleanalytics extends DokuWiki_Action_Plugin {
- private $mustNotShow = false;
+ private $gaEnabled = true;
/**
* Register its handlers with the DokuWiki's event controller
*
* @param Doku_Event_Handler $controller
*/
function register(Doku_Event_Handler $controller) {
- $controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, '_addHeaders');
- $controller->register_hook('POPUPVIEWER_DOKUWIKI_STARTED', 'BEFORE', $this, 'popupviewer_handler');
- $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'ajax_provider');
+ $controller->register_hook('DOKUWIKI_STARTED', 'AFTER', $this, 'gaConfig');
}
/**
- * Default setup of the needed javascript for tracking
+ * Initialize the Google Analytics config
*
* @param Doku_Event $event
* @param array $param
*/
- function _addHeaders(Doku_Event $event, $param) {
+ public function gaConfig(Doku_Event $event, $param) {
+ global $JSINFO;
global $INFO;
- if($this->mustNotShow || !$this->getConf('GAID')) return;
+ global $ACT;
+
+ if(!$this->gaEnabled) return;
+ $trackingId = $this->getConf('GAID');
+ if(!$trackingId) return;
if($this->getConf('dont_count_admin') && $INFO['isadmin']) return;
if($this->getConf('dont_count_users') && $_SERVER['REMOTE_USER']) return;
$options = array();
- $options[] = "_gaq.push(['_setAccount', '" . $this->getConf('GAID') . "'])";
-
- if($this->getConf('anonymize')) {
- $options[] = "_gaq.push(['_gat._anonymizeIp'])";
+ if($this->getConf('track_users') && $_SERVER['REMOTE_USER']) {
+ $options['userId'] = md5(auth_cookiesalt() . 'googleanalytics' . $_SERVER['REMOTE_USER']);
}
-
- $domainName = $this->getConf('domainName');
- if(!empty($domainName)) {
- $options[] = "_gaq.push(['_setDomainName', '" . $domainName . "'])";
+ if($this->getConf('domainName')) {
+ $options['cookieDomain'] = $this->getConf('domainName');
+ $options['legacyCookieDomain'] = $this->getConf('domainName');
}
- $options[] = "_gaq.push(['_gat._forceSSL'])";
- $options[] = "_gaq.push(['_trackPageview']);";
-
- $event->data["script"][] = array(
- "type" => "text/javascript",
- "_data" => "var _gaq = _gaq || [];" . implode(';', $options)
- );
-
- $event->data["script"][] = array(
- "type" => "text/javascript",
- "_data" => "(function() {var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();"
- );
- }
-
- /**
- * Track links in the popuviewer plugin
- *
- * @link https://www.dokuwiki.org/plugin:popupviewer
- * @param Doku_Event $event
- * @param array $param
- */
- function popupviewer_handler(Doku_Event $event, $param) {
- global $ID;
-
- // Only track self
- $event->data["popupscript"][] = array(
- "type" => "text/popupscript",
- "_data" => "googleanalytics_trackLink(typeof trackLink == 'string'?trackLink:'" . wl($ID) . "');"
+ $JSINFO['ga'] = array(
+ 'trackingId' => $trackingId,
+ 'anonymizeIp' => (bool) $this->getConf('anonymize'),
+ 'action' => act_clean($ACT),
+ 'trackOutboundLinks' => (bool) $this->getConf('track_links'),
+ 'options' => $options,
);
-
- $this->mustNotShow = true;
}
-
- /**
- * Handle page tracking when pages are loaded via AJAX
- *
- * @link https://www.dokuwiki.org/plugin:fastwiki
- * @param Doku_Event $event
- * @param array $param
- */
- function ajax_provider(Doku_Event $event, $param) {
- global $ACT;
- $this->mustNotShow = $ACT != 'show';
- }
-
}
diff --git a/conf/default.php b/conf/default.php
index 17c95a1..32682a9 100644
--- a/conf/default.php
+++ b/conf/default.php
@@ -1,3 +1,9 @@
<?php
+$conf['GAID'] = '';
+$conf['dont_count_admin'] = 0;
+$conf['dont_count_users'] = 0;
$conf['anonymize'] = 1;
+$conf['track_users'] = 0;
+$conf['track_links'] = 0;
+$conf['domainName'] = '';
diff --git a/conf/metadata.php b/conf/metadata.php
index b9eee15..1a70c43 100644
--- a/conf/metadata.php
+++ b/conf/metadata.php
@@ -1,7 +1,9 @@
<?php
+
$meta['GAID'] = array('string');
$meta['dont_count_admin'] = array('onoff');
$meta['dont_count_users'] = array('onoff');
-
$meta['anonymize'] = array('onoff');
+$meta['track_users'] = array('onoff');
+$meta['track_links'] = array('onoff');
$meta['domainName'] = array('string');
diff --git a/lang/en/settings.php b/lang/en/settings.php
index 1d06e3c..0a1b1ec 100644
--- a/lang/en/settings.php
+++ b/lang/en/settings.php
@@ -1,4 +1,9 @@
<?php
-$lang['GAID'] = 'Google Analitycs ID';
+$lang['GAID'] = 'Your Google Analytics ID (UA-XXXXX)';
$lang['dont_count_admin'] = 'Don\'t count admin/superuser';
$lang['dont_count_users'] = 'Don\'t count logged in users';
+$lang['anonymize'] = 'Send anonymized IP addresses to google.';
+$lang['track_users'] = 'Track logged in users. Needs <a href="https://support.google.com/analytics/answer/3123662?hl=en">user tracking</a> enabled. Users will not be identifable in Google Analytics.';
+$lang['track_links'] = 'Track outgoing links.';
+$lang['domainName'] = 'Configure the cookie domain - useful if the tracker is shared over multiple sub domains. Leave empty for automatic detection';
+
diff --git a/plugin.info.txt b/plugin.info.txt
index 4c76166..ab22a9d 100644
--- a/plugin.info.txt
+++ b/plugin.info.txt
@@ -1,7 +1,7 @@
base googleanalytics
author Terence J. Grant
email [email protected]
-date 2016-02-02
+date 2017-02-07
name Google Analytics Plugin
desc Plugin to embed your Google Analytics code for your site, which allows you to track your visitors.
-url http://www.dokuwiki.org/plugin:googleanalytics
+url https://www.dokuwiki.org/plugin:googleanalytics
diff --git a/script.js b/script.js
index aac9538..0b14024 100644
--- a/script.js
+++ b/script.js
@@ -1,43 +1,50 @@
-/**
- *
- * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
- * @author Gerry WeiÃbach <[email protected]>
- */
-
-var googleanalytics_trackLink = function(link, prefix) {
-
- if ( typeof _gaq != 'undefined' )
- {
- _gaq.push(['_trackPageview', (typeof prefix != 'undefined' ? prefix : '') + link]);
- }
-};
-
-var googleanalytics_trackEvent = function(category, action, label) {
-
- if ( typeof _gaq != 'undefined' )
- {
- _gaq.push(['_trackEvent', category, action, label]);
- }
-};
-
-var googleanalytics_registerTracking = function() {
-
- if ( typeof _gaq == 'undefined' ) { return; }
- _gaq.push(['_setAllowLinker', true]);
-
- var expression = new RegExp("^([^\?]*)\?[^=]*$");
- jQuery('a.media:not([tracking]), a.mediafile:not([tracking]), a.interwiki:not([tracking]), a.urlextern:not([tracking])').each(function(){
-
-
- jQuery(this).click(function(e){
-
- googleanalytics_trackLink(this.href.replace(expression, "$1"), '/outgoing?url='); // but track full URL to be sure
- return true;
- }).attr('tracking');
- });
-
-};
-
-(function($){
- $(googleanalytics_registerTracking);
-})(jQuery);
+/**
+ * Set up Google analytics
+ *
+ * All configuration is done in the JSINFO.ga object initialized in
+ * action.php
+ */
+if (JSINFO.ga) {
+ /* default google tracking initialization */
+ (function (i, s, o, g, r, a, m) {
+ i['GoogleAnalyticsObject'] = r;
+ //noinspection CommaExpressionJS
+ i[r] = i[r] || function () {
+ (i[r].q = i[r].q || []).push(arguments)
+ }, i[r].l = 1 * new Date();
+ //noinspection CommaExpressionJS
+ a = s.createElement(o),
+ m = s.getElementsByTagName(o)[0];
+ a.async = 1;
+ a.src = g;
+ m.parentNode.insertBefore(a, m)
+ })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
+
+ // initalize and set options
+ ga('create', JSINFO.ga.trackingId, 'auto', JSINFO.ga.options);
+ ga('set', 'forceSSL', true);
+ ga('set', 'anonymizeIp', JSINFO.ga.anonymizeIp);
+
+ // track pageview and action
+ ga('send', 'pageview');
+ ga('send', 'event', 'wiki-action', JSINFO.ga.action, JSINFO.id, {
+ nonInteraction: true // this is an automatic event with the page load
+ });
+
+ // track outgoing links, once the document was loaded
+ if (JSINFO.ga.trackOutboundLinks) {
+ jQuery(function () {
+ // https://support.google.com/analytics/answer/1136920?hl=en
+ jQuery('a.urlextern, a.interwiki').click(function (e) {
+ e.preventDefault();
+ var url = this.href;
+ ga('send', 'event', 'outbound', 'click', url, {
+ 'transport': 'beacon',
+ 'hitCallback': function () {
+ document.location = url;
+ }
+ });
+ });
+ });
+ }
+}
|
tatewake/dokuwiki-plugin-googleanalytics | fd0d2f7d9f30e21a194af5b8eb8d89e28ff97d1c | some cleanup for the action.php file | diff --git a/action.php b/action.php
index 294e714..528dd98 100644
--- a/action.php
+++ b/action.php
@@ -1,69 +1,92 @@
<?php
if(!defined('DOKU_INC')) die();
-if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
-require_once(DOKU_PLUGIN.'action.php');
+if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN', DOKU_INC . 'lib/plugins/');
+/**
+ * Class action_plugin_googleanalytics
+ */
class action_plugin_googleanalytics extends DokuWiki_Action_Plugin {
- private $mustNotShow = false;
+ private $mustNotShow = false;
+
+ /**
+ * Register its handlers with the DokuWiki's event controller
+ *
+ * @param Doku_Event_Handler $controller
+ */
+ function register(Doku_Event_Handler $controller) {
+ $controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, '_addHeaders');
+ $controller->register_hook('POPUPVIEWER_DOKUWIKI_STARTED', 'BEFORE', $this, 'popupviewer_handler');
+ $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'ajax_provider');
+ }
+
+ /**
+ * Default setup of the needed javascript for tracking
+ *
+ * @param Doku_Event $event
+ * @param array $param
+ */
+ function _addHeaders(Doku_Event $event, $param) {
+ global $INFO;
+ if($this->mustNotShow || !$this->getConf('GAID')) return;
+ if($this->getConf('dont_count_admin') && $INFO['isadmin']) return;
+ if($this->getConf('dont_count_users') && $_SERVER['REMOTE_USER']) return;
+
+ $options = array();
+ $options[] = "_gaq.push(['_setAccount', '" . $this->getConf('GAID') . "'])";
+
+ if($this->getConf('anonymize')) {
+ $options[] = "_gaq.push(['_gat._anonymizeIp'])";
+ }
+
+ $domainName = $this->getConf('domainName');
+ if(!empty($domainName)) {
+ $options[] = "_gaq.push(['_setDomainName', '" . $domainName . "'])";
+ }
+
+ $options[] = "_gaq.push(['_gat._forceSSL'])";
+ $options[] = "_gaq.push(['_trackPageview']);";
+
+ $event->data["script"][] = array(
+ "type" => "text/javascript",
+ "_data" => "var _gaq = _gaq || [];" . implode(';', $options)
+ );
+
+ $event->data["script"][] = array(
+ "type" => "text/javascript",
+ "_data" => "(function() {var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();"
+ );
+ }
+
+ /**
+ * Track links in the popuviewer plugin
+ *
+ * @link https://www.dokuwiki.org/plugin:popupviewer
+ * @param Doku_Event $event
+ * @param array $param
+ */
+ function popupviewer_handler(Doku_Event $event, $param) {
+ global $ID;
+
+ // Only track self
+ $event->data["popupscript"][] = array(
+ "type" => "text/popupscript",
+ "_data" => "googleanalytics_trackLink(typeof trackLink == 'string'?trackLink:'" . wl($ID) . "');"
+ );
+
+ $this->mustNotShow = true;
+ }
+
+ /**
+ * Handle page tracking when pages are loaded via AJAX
+ *
+ * @link https://www.dokuwiki.org/plugin:fastwiki
+ * @param Doku_Event $event
+ * @param array $param
+ */
+ function ajax_provider(Doku_Event $event, $param) {
+ global $ACT;
+ $this->mustNotShow = $ACT != 'show';
+ }
- /**
- * Register its handlers with the DokuWiki's event controller
- */
- function register(Doku_Event_Handler $controller) {
- $controller->register_hook('POPUPVIEWER_DOKUWIKI_STARTED', 'BEFORE', $this, 'popupviewer_handler');
- $controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, '_addHeaders');
- $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'ajax_provider');
- }
-
- function popupviewer_handler(&$event) {
-
- global $ID;
-
- // Only track self
- $event->data["popupscript"][] = array (
- "type" => "text/popupscript",
- "_data" => "googleanalytics_trackLink(typeof trackLink == 'string'?trackLink:'".wl($ID)."');"
- );
-
- $this->mustNotShow = true;
- }
-
- function ajax_provider(&$event) {
-
- global $ACT;
- $this->mustNotShow = $ACT != 'show';
- }
-
- function _addHeaders (&$event, $param) {
- global $INFO;
- if($this->mustNotShow || !$this->getConf('GAID')) return;
- if($this->getConf('dont_count_admin') && $INFO['isadmin']) return;
- if($this->getConf('dont_count_users') && $_SERVER['REMOTE_USER']) return;
-
- $options = array();
- $options[] = "_gaq.push(['_setAccount', '".$this->getConf('GAID')."'])";
-
- if ( $this->getConf('anonymize') ) {
- $options[] = "_gaq.push(['_gat._anonymizeIp'])";
- }
-
- $domainName = $this->getConf('domainName');
- if ( !empty($domainName) ) {
- $options[] = "_gaq.push(['_setDomainName', '".$domainName."'])";
- }
-
- $options[] = "_gaq.push(['_gat._forceSSL'])";
- $options[] = "_gaq.push(['_trackPageview']);";
-
- $event->data["script"][] = array (
- "type" => "text/javascript",
- "_data" => "var _gaq = _gaq || [];" . implode(';', $options)
- );
-
- $event->data["script"][] = array (
- "type" => "text/javascript",
- "_data" => "(function() {var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();"
- );
- }
}
|
tatewake/dokuwiki-plugin-googleanalytics | 094530f2c15954bfab93a9dbce120d5089680a37 | create plugin.info.txt | diff --git a/plugin.info.txt b/plugin.info.txt
new file mode 100644
index 0000000..9d24a67
--- /dev/null
+++ b/plugin.info.txt
@@ -0,0 +1,7 @@
+base googleanalytics
+author Terence J. Grant
+email [email protected]
+date 2016-02-02
+name Google Analytics for DokuWiki
+desc This tool allows you to set a code for use with Google Analytics, which allows you to track your visitors.
+url https://github.com/tatewake/dokuwiki-plugin-googleanalytics
|
tatewake/dokuwiki-plugin-googleanalytics | 280cad8278b6c83a24f59560ce13f69da06abe55 | Adjust method signatures to match parent | diff --git a/action.php b/action.php
index 0f54f66..57dd305 100644
--- a/action.php
+++ b/action.php
@@ -1,41 +1,41 @@
<?php
if(!defined('DOKU_INC')) die();
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'action.php');
class action_plugin_googleanalytics extends DokuWiki_Action_Plugin {
/**
* return some info
*/
function getInfo(){
return array(
'author' => 'Terence J. Grant',
'email' => '[email protected]',
'date' => '2014-06-14',
'name' => 'Google Analytics Plugin',
'desc' => 'Plugin to embed your google analytics code for your site. Now updated to support the new Google Universal Analytics.',
'url' => 'https://www.dokuwiki.org/plugin:googleanalytics',
);
}
/**
* Register its handlers with the DokuWiki's event controller
*/
- function register(&$controller) {
+ function register(Doku_Event_Handler $controller) {
$controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, '_addHeaders');
}
function _addHeaders (&$event, $param) {
global $INFO;
if(!$this->getConf('GAID')) return;
if($this->getConf('dont_count_admin') && $INFO['isadmin']) return;
if($this->getConf('dont_count_users') && $_SERVER['REMOTE_USER']) return;
$event->data["script"][] = array (
"type" => "text/javascript",
"_data" => "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','//www.google-analytics.com/analytics.js','ga');ga('create', '". $this->getConf('GAID') ."');ga('send', 'pageview');"
);
}
}
?>
|
tatewake/dokuwiki-plugin-googleanalytics | b0048f016599783b177ea79a775cb6dee646cbbe | API Update | diff --git a/action.php b/action.php
index f64174f..97071a3 100644
--- a/action.php
+++ b/action.php
@@ -1,69 +1,69 @@
<?php
if(!defined('DOKU_INC')) die();
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'action.php');
class action_plugin_googleanalytics extends DokuWiki_Action_Plugin {
private $mustNotShow = false;
/**
* Register its handlers with the DokuWiki's event controller
*/
- function register(&$controller) {
+ function register(Doku_Event_Handler $controller) {
$controller->register_hook('POPUPVIEWER_DOKUWIKI_STARTED', 'BEFORE', $this, 'popupviewer_handler');
$controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, '_addHeaders');
$controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'ajax_provider');
}
function popupviewer_handler(&$event) {
global $ID;
// Only track self
$event->data["popupscript"][] = array (
"type" => "text/popupscript",
"_data" => "googleanalytics_trackLink(typeof trackLink == 'string'?trackLink:'".wl($ID)."');"
);
$this->mustNotShow = true;
}
function ajax_provider(&$event) {
global $ACT;
$this->mustNotShow = $ACT != 'show';
}
function _addHeaders (&$event, $param) {
global $INFO;
if($this->mustNotShow || !$this->getConf('GAID')) return;
if($this->getConf('dont_count_admin') && $INFO['isadmin']) return;
if($this->getConf('dont_count_users') && $_SERVER['REMOTE_USER']) return;
$options = array();
$options[] = "_gaq.push(['_setAccount', '".$this->getConf('GAID')."'])";
if ( $this->getConf('anonymize') ) {
$options[] = "_gaq.push(['_gat._anonymizeIp'])";
}
$domainName = $this->getConf('domainName');
if ( !empty($domainName) ) {
$options[] = "_gaq.push(['_setDomainName', '".$domainName."'])";
}
$options[] = "_gaq.push(['_gat._forceSSL'])";
$options[] = "_gaq.push(['_trackPageview']);";
$event->data["script"][] = array (
"type" => "text/javascript",
"_data" => "var _gaq = _gaq || [];" . implode(';', $options)
);
$event->data["script"][] = array (
"type" => "text/javascript",
"_data" => "(function() {var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();"
);
}
}
|
tatewake/dokuwiki-plugin-googleanalytics | f699e419b82e5e4da2eec080b8a3ddcde7051eee | Added Polish and Swedish translations | diff --git a/lang/pl/settings.php b/lang/pl/settings.php
new file mode 100644
index 0000000..d1211bd
--- /dev/null
+++ b/lang/pl/settings.php
@@ -0,0 +1,4 @@
+<?php
+$lang['GAID'] = 'Google Analitycs ID';
+$lang['dont_count_admin'] = 'Nie zliczaj: admin/superuser';
+$lang['dont_count_users'] = 'Nie zliczaj zalogownych użytkowników';
\ No newline at end of file
diff --git a/lang/se/settings.php b/lang/se/settings.php
new file mode 100644
index 0000000..5a2b9a1
--- /dev/null
+++ b/lang/se/settings.php
@@ -0,0 +1,4 @@
+<?php
+$lang['GAID'] = 'Google Analitycs ID';
+$lang['dont_count_admin'] = 'Räkna inte admin/superuser';
+$lang['dont_count_users'] = 'Räkna inte inloggade användare';
|
tatewake/dokuwiki-plugin-googleanalytics | ada724698e681b77050a335fdc6afbb355bf347d | Added support for Universal Analytics | diff --git a/action.php b/action.php
index 93695dc..0f54f66 100644
--- a/action.php
+++ b/action.php
@@ -1,45 +1,41 @@
<?php
if(!defined('DOKU_INC')) die();
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'action.php');
class action_plugin_googleanalytics extends DokuWiki_Action_Plugin {
/**
* return some info
*/
function getInfo(){
return array(
'author' => 'Terence J. Grant',
'email' => '[email protected]',
- 'date' => '2013-02-23',
+ 'date' => '2014-06-14',
'name' => 'Google Analytics Plugin',
- 'desc' => 'Plugin to embed your google analytics code for your site.',
- 'url' => 'http://tatewake.com/wiki/projects:google_analytics_for_dokuwiki',
+ 'desc' => 'Plugin to embed your google analytics code for your site. Now updated to support the new Google Universal Analytics.',
+ 'url' => 'https://www.dokuwiki.org/plugin:googleanalytics',
);
}
/**
* Register its handlers with the DokuWiki's event controller
*/
function register(&$controller) {
$controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, '_addHeaders');
}
function _addHeaders (&$event, $param) {
global $INFO;
if(!$this->getConf('GAID')) return;
if($this->getConf('dont_count_admin') && $INFO['isadmin']) return;
if($this->getConf('dont_count_users') && $_SERVER['REMOTE_USER']) return;
$event->data["script"][] = array (
"type" => "text/javascript",
- "_data" => "var _gaq = _gaq || []; _gaq.push(['_setAccount', '".$this->getConf('GAID')."']); _gaq.push(['_trackPageview']);"
- );
- $event->data["script"][] = array (
- "type" => "text/javascript",
- "_data" => "(function(){var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + 'stats.g.doubleclick.net/dc.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();"
+ "_data" => "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','//www.google-analytics.com/analytics.js','ga');ga('create', '". $this->getConf('GAID') ."');ga('send', 'pageview');"
);
}
}
?>
|
tatewake/dokuwiki-plugin-googleanalytics | 98a5b990b0f2689f26d110f95e49ab18ab914b75 | Added event for popupviewer to track its links | diff --git a/action.php b/action.php
index b897c6d..f64174f 100644
--- a/action.php
+++ b/action.php
@@ -1,55 +1,69 @@
<?php
if(!defined('DOKU_INC')) die();
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'action.php');
class action_plugin_googleanalytics extends DokuWiki_Action_Plugin {
private $mustNotShow = false;
/**
* Register its handlers with the DokuWiki's event controller
*/
function register(&$controller) {
+ $controller->register_hook('POPUPVIEWER_DOKUWIKI_STARTED', 'BEFORE', $this, 'popupviewer_handler');
$controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, '_addHeaders');
- $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'ajax_provider');
+ $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'ajax_provider');
+ }
+
+ function popupviewer_handler(&$event) {
+
+ global $ID;
+
+ // Only track self
+ $event->data["popupscript"][] = array (
+ "type" => "text/popupscript",
+ "_data" => "googleanalytics_trackLink(typeof trackLink == 'string'?trackLink:'".wl($ID)."');"
+ );
+
+ $this->mustNotShow = true;
}
function ajax_provider(&$event) {
- global $ACT;
- $this->mustNotShow = $ACT != 'show';
+ global $ACT;
+ $this->mustNotShow = $ACT != 'show';
}
function _addHeaders (&$event, $param) {
- global $INFO;
- if($this->mustNotShow || !$this->getConf('GAID')) return;
- if($this->getConf('dont_count_admin') && $INFO['isadmin']) return;
- if($this->getConf('dont_count_users') && $_SERVER['REMOTE_USER']) return;
+ global $INFO;
+ if($this->mustNotShow || !$this->getConf('GAID')) return;
+ if($this->getConf('dont_count_admin') && $INFO['isadmin']) return;
+ if($this->getConf('dont_count_users') && $_SERVER['REMOTE_USER']) return;
- $options = array();
- $options[] = "_gaq.push(['_setAccount', '".$this->getConf('GAID')."'])";
+ $options = array();
+ $options[] = "_gaq.push(['_setAccount', '".$this->getConf('GAID')."'])";
- if ( $this->getConf('anonymize') ) {
- $options[] = "_gaq.push(['_gat._anonymizeIp'])";
- }
+ if ( $this->getConf('anonymize') ) {
+ $options[] = "_gaq.push(['_gat._anonymizeIp'])";
+ }
- $domainName = $this->getConf('domainName');
- if ( !empty($domainName) ) {
- $options[] = "_gaq.push(['_setDomainName', '".$domainName."']);";
- }
+ $domainName = $this->getConf('domainName');
+ if ( !empty($domainName) ) {
+ $options[] = "_gaq.push(['_setDomainName', '".$domainName."'])";
+ }
- $options[] = "_gaq.push(['_trackPageview'])";
+ $options[] = "_gaq.push(['_gat._forceSSL'])";
+ $options[] = "_gaq.push(['_trackPageview']);";
- $event->data["script"][] = array (
- "type" => "text/javascript",
- "_data" => "var _gaq = _gaq || [];" . implode(';', $options)
- );
+ $event->data["script"][] = array (
+ "type" => "text/javascript",
+ "_data" => "var _gaq = _gaq || [];" . implode(';', $options)
+ );
- $event->data["script"][] = array (
- "type" => "text/javascript",
- "_data" => "(function(){var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();"
- );
-
+ $event->data["script"][] = array (
+ "type" => "text/javascript",
+ "_data" => "(function() {var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();"
+ );
}
}
|
tatewake/dokuwiki-plugin-googleanalytics | da25265cfbfe582207651407510bf88e10bdc50e | Improve structure | diff --git a/script.js b/script.js
index 8300fe9..aac9538 100644
--- a/script.js
+++ b/script.js
@@ -1,42 +1,43 @@
/**
*
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
- * @author Gerry Weißbach <[email protected]>
+ * @author Gerry WeiÃbach <[email protected]>
*/
var googleanalytics_trackLink = function(link, prefix) {
if ( typeof _gaq != 'undefined' )
{
_gaq.push(['_trackPageview', (typeof prefix != 'undefined' ? prefix : '') + link]);
}
};
var googleanalytics_trackEvent = function(category, action, label) {
if ( typeof _gaq != 'undefined' )
{
_gaq.push(['_trackEvent', category, action, label]);
}
};
-(function($){
-
- $(function(){
-
+var googleanalytics_registerTracking = function() {
+
if ( typeof _gaq == 'undefined' ) { return; }
_gaq.push(['_setAllowLinker', true]);
var expression = new RegExp("^([^\?]*)\?[^=]*$");
- $('a.media, a.mediafile, a.interwiki, a.urlextern').each(function(){
+ jQuery('a.media:not([tracking]), a.mediafile:not([tracking]), a.interwiki:not([tracking]), a.urlextern:not([tracking])').each(function(){
- $(this).click(function(e){
+
+ jQuery(this).click(function(e){
googleanalytics_trackLink(this.href.replace(expression, "$1"), '/outgoing?url='); // but track full URL to be sure
return true;
- });
+ }).attr('tracking');
});
-
- });
-
+
+};
+
+(function($){
+ $(googleanalytics_registerTracking);
})(jQuery);
|
tatewake/dokuwiki-plugin-googleanalytics | cc9f5943498ef17e0f0d6cfebb9c4a6ba58cf624 | Only add Script if we don't run via AJAX. | diff --git a/action.php b/action.php
index b7fe9fb..b897c6d 100644
--- a/action.php
+++ b/action.php
@@ -1,46 +1,55 @@
<?php
if(!defined('DOKU_INC')) die();
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'action.php');
class action_plugin_googleanalytics extends DokuWiki_Action_Plugin {
+
+ private $mustNotShow = false;
/**
* Register its handlers with the DokuWiki's event controller
*/
function register(&$controller) {
$controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, '_addHeaders');
+ $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'ajax_provider');
+ }
+
+ function ajax_provider(&$event) {
+
+ global $ACT;
+ $this->mustNotShow = $ACT != 'show';
}
function _addHeaders (&$event, $param) {
global $INFO;
- if(!$this->getConf('GAID')) return;
+ if($this->mustNotShow || !$this->getConf('GAID')) return;
if($this->getConf('dont_count_admin') && $INFO['isadmin']) return;
if($this->getConf('dont_count_users') && $_SERVER['REMOTE_USER']) return;
$options = array();
$options[] = "_gaq.push(['_setAccount', '".$this->getConf('GAID')."'])";
if ( $this->getConf('anonymize') ) {
$options[] = "_gaq.push(['_gat._anonymizeIp'])";
}
$domainName = $this->getConf('domainName');
if ( !empty($domainName) ) {
$options[] = "_gaq.push(['_setDomainName', '".$domainName."']);";
}
$options[] = "_gaq.push(['_trackPageview'])";
$event->data["script"][] = array (
"type" => "text/javascript",
"_data" => "var _gaq = _gaq || [];" . implode(';', $options)
);
$event->data["script"][] = array (
"type" => "text/javascript",
"_data" => "(function(){var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();"
);
}
}
|
tatewake/dokuwiki-plugin-googleanalytics | 9b44ac7fe8eca5f903f39b11cf98369f72d6d4bd | Added empty line at end | diff --git a/conf/default.php b/conf/default.php
index b932e9e..17c95a1 100644
--- a/conf/default.php
+++ b/conf/default.php
@@ -1,3 +1,3 @@
<?php
-$conf['anonymize'] = 1;
\ No newline at end of file
+$conf['anonymize'] = 1;
|
tatewake/dokuwiki-plugin-googleanalytics | 2f3b40ee58d43024ec102b07c7d5e4c8d422add7 | Added more options (domainName and anonymize) | diff --git a/action.php b/action.php
index 116d906..368370f 100644
--- a/action.php
+++ b/action.php
@@ -1,45 +1,46 @@
<?php
if(!defined('DOKU_INC')) die();
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'action.php');
class action_plugin_googleanalytics extends DokuWiki_Action_Plugin {
-
- /**
- * return some info
- */
- function getInfo(){
- return array(
- 'author' => 'Terence J. Grant',
- 'email' => '[email protected]',
- 'date' => '2013-02-23',
- 'name' => 'Google Analytics Plugin',
- 'desc' => 'Plugin to embed your google analytics code for your site.',
- 'url' => 'http://tatewake.com/wiki/projects:google_analytics_for_dokuwiki',
- );
- }
/**
* Register its handlers with the DokuWiki's event controller
*/
function register(&$controller) {
$controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, '_addHeaders');
}
function _addHeaders (&$event, $param) {
global $INFO;
if(!$this->getConf('GAID')) return;
if($this->getConf('dont_count_admin') && $INFO['isadmin']) return;
if($this->getConf('dont_count_users') && $_SERVER['REMOTE_USER']) return;
+
+ $options = array();
+ $options[] = "_gaq.push(['_setAccount', '".$this->getConf('GAID')."'])";
+
+ if ( $this->getConf('anonymize') ) {
+ $options[] = "_gaq.push(['_gat._anonymizeIp'])";
+ }
+
+ $domainName = $this->getConf('domainName');
+ if ( !empty($domainName) ) {
+ $options[] = "_gaq.push(['_setDomainName', '".$domainName."']);";
+ }
+
+ $options[] = "_gaq.push(['_trackPageview'])";
+
$event->data["script"][] = array (
"type" => "text/javascript",
- "_data" => "var _gaq = _gaq || []; _gaq.push(['_setAccount', '".$this->getConf('GAID')."']); _gaq.push(['_trackPageview']);"
+ "_data" => "var _gaq = _gaq || [];" . implode(';', $options)
);
+
$event->data["script"][] = array (
"type" => "text/javascript",
"_data" => "(function(){var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();"
);
}
}
-?>
\ No newline at end of file
diff --git a/conf/default.php b/conf/default.php
new file mode 100644
index 0000000..b932e9e
--- /dev/null
+++ b/conf/default.php
@@ -0,0 +1,3 @@
+<?php
+
+$conf['anonymize'] = 1;
\ No newline at end of file
diff --git a/conf/metadata.php b/conf/metadata.php
index c56d4b9..b9eee15 100644
--- a/conf/metadata.php
+++ b/conf/metadata.php
@@ -1,4 +1,7 @@
<?php
$meta['GAID'] = array('string');
$meta['dont_count_admin'] = array('onoff');
$meta['dont_count_users'] = array('onoff');
+
+$meta['anonymize'] = array('onoff');
+$meta['domainName'] = array('string');
|
tatewake/dokuwiki-plugin-googleanalytics | c0801f7b6046297ad41a2eef50ab254611e1e716 | Added plugin.info.txt | diff --git a/plugin.info.txt b/plugin.info.txt
new file mode 100644
index 0000000..6a60785
--- /dev/null
+++ b/plugin.info.txt
@@ -0,0 +1,8 @@
+base googleanalytics
+author Terence J. Grant
+email [email protected]
+date 2013-02-23
+name Google Analytics Plugin
+desc Plugin to embed your google analytics code for your site.
+url http://www.dokuwiki.org/plugin:googleanalytics
+
|
tatewake/dokuwiki-plugin-googleanalytics | 384936d8a8635adaa25304045e3666aeb364ec90 | Added a Script to track external links. | diff --git a/script.js b/script.js
new file mode 100644
index 0000000..8300fe9
--- /dev/null
+++ b/script.js
@@ -0,0 +1,42 @@
+/**
+ *
+ * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
+ * @author Gerry Weißbach <[email protected]>
+ */
+
+var googleanalytics_trackLink = function(link, prefix) {
+
+ if ( typeof _gaq != 'undefined' )
+ {
+ _gaq.push(['_trackPageview', (typeof prefix != 'undefined' ? prefix : '') + link]);
+ }
+};
+
+var googleanalytics_trackEvent = function(category, action, label) {
+
+ if ( typeof _gaq != 'undefined' )
+ {
+ _gaq.push(['_trackEvent', category, action, label]);
+ }
+};
+
+(function($){
+
+ $(function(){
+
+ if ( typeof _gaq == 'undefined' ) { return; }
+ _gaq.push(['_setAllowLinker', true]);
+
+ var expression = new RegExp("^([^\?]*)\?[^=]*$");
+ $('a.media, a.mediafile, a.interwiki, a.urlextern').each(function(){
+
+ $(this).click(function(e){
+
+ googleanalytics_trackLink(this.href.replace(expression, "$1"), '/outgoing?url='); // but track full URL to be sure
+ return true;
+ });
+ });
+
+ });
+
+})(jQuery);
|
tatewake/dokuwiki-plugin-googleanalytics | 46926853afe73e0db3a452ff2ce5173f4b0adde2 | Add plugin info file | diff --git a/plugin.info.txt b/plugin.info.txt
new file mode 100644
index 0000000..b9f7069
--- /dev/null
+++ b/plugin.info.txt
@@ -0,0 +1,8 @@
+base googleanalytics
+author Terence J. Grant,
+email [email protected],
+date 2013-02-23,
+name Google Analytics Plugin,
+desc Plugin to embed your google analytics code for your site.,
+url http://tatewake.com/wiki/projects:google_analytics_for_dokuwiki,
+
|
tatewake/dokuwiki-plugin-googleanalytics | ee77cee0267595441d78a7f793512a89c903e589 | removed php close tag | diff --git a/action.php b/action.php
index 3628165..5e50c5f 100644
--- a/action.php
+++ b/action.php
@@ -1,48 +1,47 @@
<?php
if(!defined('DOKU_INC')) die();
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'action.php');
class action_plugin_googleanalytics extends DokuWiki_Action_Plugin {
/**
* return some info
*/
function getInfo() {
return array(
'author' => 'Terence J. Grant',
'email' => '[email protected]',
'date' => '2013-02-23',
'name' => 'Google Analytics Plugin',
'desc' => 'Plugin to embed your google analytics code for your site.',
'url' => 'http://tatewake.com/wiki/projects:google_analytics_for_dokuwiki',
);
}
/**
* Register its handlers with the DokuWiki's event controller
*/
function register(&$controller) {
$controller->register_hook('TPL_ACT_RENDER', 'AFTER', $this, '_addScripts');
}
function _addScripts(&$event, $param) {
global $INFO;
if(!$this->getConf('GAID')) return;
if($this->getConf('dont_count_admin') && $INFO['isadmin']) return;
if($this->getConf('dont_count_users') && $_SERVER['REMOTE_USER']) return;
echo "<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', '" . $this->getConf('GAID') . "');
ga('send', 'pageview');
</script>";
}
}
-?>
|
tatewake/dokuwiki-plugin-googleanalytics | 77ddf0166211237bf1ce754a3dbd1d43efb47982 | Add ga scripts on page bottom. | diff --git a/action.php b/action.php
index 116d906..3628165 100644
--- a/action.php
+++ b/action.php
@@ -1,45 +1,48 @@
-<?php
+<?php
if(!defined('DOKU_INC')) die();
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'action.php');
class action_plugin_googleanalytics extends DokuWiki_Action_Plugin {
- /**
- * return some info
- */
- function getInfo(){
- return array(
- 'author' => 'Terence J. Grant',
- 'email' => '[email protected]',
- 'date' => '2013-02-23',
- 'name' => 'Google Analytics Plugin',
- 'desc' => 'Plugin to embed your google analytics code for your site.',
- 'url' => 'http://tatewake.com/wiki/projects:google_analytics_for_dokuwiki',
- );
- }
-
- /**
- * Register its handlers with the DokuWiki's event controller
- */
- function register(&$controller) {
- $controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, '_addHeaders');
- }
-
- function _addHeaders (&$event, $param) {
- global $INFO;
- if(!$this->getConf('GAID')) return;
- if($this->getConf('dont_count_admin') && $INFO['isadmin']) return;
- if($this->getConf('dont_count_users') && $_SERVER['REMOTE_USER']) return;
- $event->data["script"][] = array (
- "type" => "text/javascript",
- "_data" => "var _gaq = _gaq || []; _gaq.push(['_setAccount', '".$this->getConf('GAID')."']); _gaq.push(['_trackPageview']);"
- );
- $event->data["script"][] = array (
- "type" => "text/javascript",
- "_data" => "(function(){var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();"
- );
-
- }
+ /**
+ * return some info
+ */
+ function getInfo() {
+ return array(
+ 'author' => 'Terence J. Grant',
+ 'email' => '[email protected]',
+ 'date' => '2013-02-23',
+ 'name' => 'Google Analytics Plugin',
+ 'desc' => 'Plugin to embed your google analytics code for your site.',
+ 'url' => 'http://tatewake.com/wiki/projects:google_analytics_for_dokuwiki',
+ );
+ }
+
+ /**
+ * Register its handlers with the DokuWiki's event controller
+ */
+ function register(&$controller) {
+ $controller->register_hook('TPL_ACT_RENDER', 'AFTER', $this, '_addScripts');
+ }
+
+ function _addScripts(&$event, $param) {
+ global $INFO;
+ if(!$this->getConf('GAID')) return;
+ if($this->getConf('dont_count_admin') && $INFO['isadmin']) return;
+ if($this->getConf('dont_count_users') && $_SERVER['REMOTE_USER']) return;
+
+ echo "<script>
+ (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
+ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
+ m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
+ })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
+
+ ga('create', '" . $this->getConf('GAID') . "');
+ ga('send', 'pageview');
+
+</script>";
+
+ }
}
-?>
\ No newline at end of file
+?>
|
tatewake/dokuwiki-plugin-googleanalytics | f76af2aa4ece096363bb2b1035f72aaba4ba22df | Added Japanese translation file. | diff --git a/lang/ja/settings.php b/lang/ja/settings.php
new file mode 100644
index 0000000..e9e29fd
--- /dev/null
+++ b/lang/ja/settings.php
@@ -0,0 +1,4 @@
+<?php
+$lang['GAID'] = 'Google Analitycs ID';
+$lang['dont_count_admin'] = '管çè
ãè§£æå¯¾è±¡å¤ã«ãã';
+$lang['dont_count_users'] = 'ãã°ã¤ã³ã¦ã¼ã¶ã¼ãè§£æå¯¾è±¡å¤ã«ãã';
|
tatewake/dokuwiki-plugin-googleanalytics | 6d406df07fb840c05b556ee1f576045eed211b88 | Added Chinese Simplified translate file. | diff --git a/lang/zh/settings.php b/lang/zh/settings.php
new file mode 100644
index 0000000..24586bc
--- /dev/null
+++ b/lang/zh/settings.php
@@ -0,0 +1,4 @@
+<?php
+$lang['GAID'] = 'Google Analitycs è·è¸ª ID';
+$lang['dont_count_admin'] = 'ä¸ç»è®¡ç®¡çååè¶
级管çå';
+$lang['dont_count_users'] = 'ä¸ç»è®¡å·²ç»å½ç¨æ·';
|
tatewake/dokuwiki-plugin-googleanalytics | 34988946ab1ab1e7c0c4b38e73770d93a586ab0c | Changed the tracking code to the async one. | diff --git a/action.php b/action.php
index be1c6fa..116d906 100644
--- a/action.php
+++ b/action.php
@@ -1,51 +1,45 @@
<?php
if(!defined('DOKU_INC')) die();
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'action.php');
class action_plugin_googleanalytics extends DokuWiki_Action_Plugin {
/**
* return some info
*/
function getInfo(){
return array(
'author' => 'Terence J. Grant',
'email' => '[email protected]',
- 'date' => '2009-05-25',
+ 'date' => '2013-02-23',
'name' => 'Google Analytics Plugin',
'desc' => 'Plugin to embed your google analytics code for your site.',
'url' => 'http://tatewake.com/wiki/projects:google_analytics_for_dokuwiki',
);
}
/**
* Register its handlers with the DokuWiki's event controller
*/
function register(&$controller) {
$controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, '_addHeaders');
}
function _addHeaders (&$event, $param) {
global $INFO;
if(!$this->getConf('GAID')) return;
if($this->getConf('dont_count_admin') && $INFO['isadmin']) return;
if($this->getConf('dont_count_users') && $_SERVER['REMOTE_USER']) return;
$event->data["script"][] = array (
"type" => "text/javascript",
- "_data" => "
-var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");
-document.write(unescape(\"%3Cscript src='\" + gaJsHost + \"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\"));
- ",
+ "_data" => "var _gaq = _gaq || []; _gaq.push(['_setAccount', '".$this->getConf('GAID')."']); _gaq.push(['_trackPageview']);"
);
$event->data["script"][] = array (
"type" => "text/javascript",
- "_data" => "
-var pageTracker = _gat._getTracker(\"".$this->getConf('GAID')."\");
-pageTracker._initData();
-pageTracker._trackPageview();
- ",
+ "_data" => "(function(){var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();"
);
+
}
}
?>
\ No newline at end of file
|
alediaferia/webpagewatcher | 96def4deac1078d59c0f842b7d4dcf0a2aff8cca | ui improvements | diff --git a/CMakeLists.txt b/CMakeLists.txt
index 5ac1d65..2578087 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,37 +1,38 @@
cmake_minimum_required(VERSION 2.6)
CONFIGURE_FILE(
"${CMAKE_CURRENT_SOURCE_DIR}/cmake_uninstall.cmake.in"
"${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake"
IMMEDIATE @ONLY)
ADD_CUSTOM_TARGET(uninstall
"${CMAKE_COMMAND}" -P "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake")
######################### The Project ##################################
project (WebPageWatcher)
find_package(Qt4 REQUIRED)
include(${QT_USE_FILE})
set (WebPageWatcher_SRCS
main.cpp
mwindow.cpp
webview.cpp
selectionwidget.cpp
)
set (wpuis_UIS
mwindowui.ui
+ previewwidget.ui
)
include_directories(${CMAKE_CURRENT_BINARY_DIR}
${CMAKE_CURRENT_SOURCE_DIR})
qt4_wrap_ui(WebPageWatcher_SRCS ${wpuis_UIS})
qt4_automoc(${WebPageWatcher_SRCS})
add_executable(wpwatcher ${WebPageWatcher_SRCS})
target_link_libraries(wpwatcher ${QT_QTCORE_LIBRARY} ${QT_QTGUI_LIBRARY} ${QT_QTWEBKIT_LIBRARY})
install( TARGETS wpwatcher RUNTIME DESTINATION bin)
diff --git a/mwindow.cpp b/mwindow.cpp
index 2e2dc99..45d1c3c 100644
--- a/mwindow.cpp
+++ b/mwindow.cpp
@@ -1,68 +1,104 @@
/***************************************************************************
* Copyright (C) 2009 by Alessandro Diaferia <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
**************************************************************************/
#include "mwindow.h"
#include <QLineEdit>
#include <QIcon>
+#include <QProgressBar>
+#include <QDockWidget>
+#include <QLabel>
#include <QDebug>
MWindow::MWindow(QWidget *parent) : QMainWindow(parent)
{
+ ////// The MainWindow //////
ui.setupUi(this);
- statusBar()->addPermanentWidget(ui.progressBar);
- connect (ui.webView, SIGNAL(loadProgress(int)), ui.progressBar, SLOT(setValue(int)));
+ progressBar = new QProgressBar(this);
+ progressBar->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Minimum);
+ statusBar()->addPermanentWidget(progressBar);
+
+ connect (ui.webView, SIGNAL(loadProgress(int)), progressBar, SLOT(setValue(int)));
connect (ui.webView, SIGNAL(loadFinished(bool)), this, SLOT(completeOperations(bool)));
+ connect (ui.webView, SIGNAL(previewReady(const QPixmap &, const QString &)),
+ this, SLOT(showPreview(const QPixmap &, const QString &)));
+
connect (ui.urlBox->lineEdit(), SIGNAL(returnPressed()), this, SLOT(goToUrl()));
connect (ui.goButton, SIGNAL(clicked()), this, SLOT(goToUrl()));
+
+ ////// The PreviewWidget //////
+ QDockWidget *dockWidget = new QDockWidget(tr("Page Preview"), this);
+ dockWidget->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
+ dockWidget->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable);
+ QWidget *widget = new QWidget(this);
+ pwidget.setupUi(widget);
+ dockWidget->setWidget(widget);
+
+ QPalette p = pwidget.scrollArea->palette();
+ p.setColor(QPalette::Window, p.color(QPalette::Dark));
+ pwidget.scrollArea->setPalette(p);
+
+ QLabel *previewLabel = new QLabel(this);
+ previewLabel->setAlignment(Qt::AlignCenter);
+ pwidget.scrollArea->setWidget(previewLabel);
+ pwidget.scrollArea->setAlignment(Qt::AlignCenter);
+
+ addDockWidget(Qt::RightDockWidgetArea, dockWidget);
}
MWindow::~MWindow()
{}
void MWindow::loadPage(QString page)
{
if (!page.contains("://")) {
page.prepend("http://");
}
loadUrl(QUrl(page));
}
void MWindow::loadUrl(const QUrl &url)
{
ui.webView->load(url);
}
void MWindow::goToUrl()
{
loadPage(ui.urlBox->currentText());
}
void MWindow::completeOperations(bool ok)
{
if (!ok) {
ui.urlBox->setItemIcon(ui.urlBox->currentIndex(), QIcon());
return;
}
ui.urlBox->setEditText(ui.webView->url().toString());
ui.urlBox->setItemIcon(ui.urlBox->currentIndex(), ui.webView->icon());
}
+void MWindow::showPreview(const QPixmap &preview, const QString &html)
+{
+ static_cast<QLabel*>(pwidget.scrollArea->widget())->setPixmap(preview);
+ pwidget.textBrowser->setText(html);
+}
+
+
#include "mwindow.moc"
diff --git a/mwindow.h b/mwindow.h
index c64a008..be4c494 100644
--- a/mwindow.h
+++ b/mwindow.h
@@ -1,46 +1,52 @@
/***************************************************************************
* Copyright (C) 2009 by Alessandro Diaferia <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
**************************************************************************/
#ifndef MWINDOW_H
#define MWINDOW_H
#include "ui_mwindowui.h"
+#include "ui_previewwidget.h"
#include <QMainWindow>
+class QProgressBar;
+
class MWindow : public QMainWindow
{
Q_OBJECT
public:
MWindow(QWidget *parent = 0);
~MWindow();
public slots:
void loadPage(QString);
protected slots:
void loadUrl(const QUrl &);
void goToUrl();
void completeOperations(bool);
+ void showPreview(const QPixmap &, const QString &);
private:
Ui::MainWindow ui;
+ Ui::PreviewWidget pwidget;
+ QProgressBar *progressBar;
};
#endif
diff --git a/mwindowui.ui b/mwindowui.ui
index b648e5f..f9d0cfb 100644
--- a/mwindowui.ui
+++ b/mwindowui.ui
@@ -1,82 +1,69 @@
<ui version="4.0" >
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow" >
<property name="geometry" >
<rect>
<x>0</x>
<y>0</y>
- <width>671</width>
- <height>505</height>
+ <width>682</width>
+ <height>489</height>
</rect>
</property>
<property name="windowTitle" >
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget" >
<layout class="QVBoxLayout" name="verticalLayout" >
<item>
<layout class="QHBoxLayout" name="horizontalLayout" >
<item>
<widget class="QComboBox" name="urlBox" >
<property name="editable" >
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="goButton" >
<property name="text" >
<string>Go</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="WebView" native="1" name="webView" >
<property name="sizePolicy" >
<sizepolicy vsizetype="Expanding" hsizetype="Expanding" >
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
- <item>
- <widget class="QProgressBar" name="progressBar" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Fixed" hsizetype="Fixed" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="value" >
- <number>24</number>
- </property>
- </widget>
- </item>
</layout>
</widget>
<widget class="QMenuBar" name="menubar" >
<property name="geometry" >
<rect>
<x>0</x>
<y>0</y>
- <width>671</width>
+ <width>682</width>
<height>24</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar" />
</widget>
<customwidgets>
<customwidget>
<class>WebView</class>
<extends>QWidget</extends>
<header>webview.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>
diff --git a/selectionwidget.cpp b/selectionwidget.cpp
index 6dc75bb..5ee883f 100644
--- a/selectionwidget.cpp
+++ b/selectionwidget.cpp
@@ -1,60 +1,61 @@
/***************************************************************************
* Copyright (C) 2009 by Alessandro Diaferia <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
**************************************************************************/
#include "selectionwidget.h"
#include <QPainter>
SelectionWidget::SelectionWidget(QWidget *parent) : QWidget(parent)
{
}
SelectionWidget::~SelectionWidget()
{}
void SelectionWidget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
QColor pcolor(palette().color(QPalette::Highlight));
painter.setPen(pcolor);
QColor icolor(pcolor);
icolor.setAlpha(127);
painter.setBrush(icolor);
QRect fillRect(rect());
fillRect.setWidth(fillRect.width() - 1);
fillRect.setHeight(fillRect.height() - 1);
painter.drawRect(fillRect);
+
painter.end();
}
QPixmap SelectionWidget::getSelection()
{
QPixmap pixmap(size());
pixmap.fill(Qt::transparent);
QRect selection(pos(), size());
hide();
parentWidget()->render(&pixmap, QPoint(), QRegion(selection));
return pixmap;
}
#include "selectionwidget.moc"
diff --git a/webview.cpp b/webview.cpp
index e12340d..e139dc6 100644
--- a/webview.cpp
+++ b/webview.cpp
@@ -1,78 +1,83 @@
/***************************************************************************
* Copyright (C) 2009 by Alessandro Diaferia <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
**************************************************************************/
#include "webview.h"
#include "selectionwidget.h"
#include <QMouseEvent>
#include <QDebug>
#include <QLabel>
#include <QPushButton>
WebView::WebView(QWidget *parent) : QWebView(parent), m_advancedSelection(false),
m_selectionWidget(0)
{
setUrl(QUrl("about:blank"));
}
WebView::~WebView()
{}
void WebView::mousePressEvent(QMouseEvent *event)
{
if (event->modifiers() & Qt::ControlModifier) {
m_advancedSelection = true;
delete m_selectionWidget;
m_selectionWidget = new SelectionWidget(this);
m_selectionWidget->move(event->pos());
+ startPos = m_selectionWidget->pos();
m_selectionWidget->resize(0, 0);
m_selectionWidget->show();
} else {
QWebView::mousePressEvent(event);
}
}
void WebView::mouseReleaseEvent(QMouseEvent *event)
{
if (!m_advancedSelection) {
delete m_selectionWidget;
m_selectionWidget = 0;
} else {
- QLabel *label = new QLabel();
- label->setAttribute(Qt::WA_DeleteOnClose);
- label->setPixmap(m_selectionWidget->getSelection());
- label->show();
+ emit previewReady(m_selectionWidget->getSelection(), QString());
}
m_advancedSelection = false;
QWebView::mouseReleaseEvent(event);
}
void WebView::mouseMoveEvent(QMouseEvent *event)
{
if (!m_advancedSelection) {
QWebView::mouseMoveEvent(event);
} else {
QPoint delta = event->pos();
- delta -= m_selectionWidget->pos();
- // TODO: handle negative deltas
- m_selectionWidget->resize(delta.x(), delta.y());
+ delta -= startPos;
+ // TODO: better handle negative deltas
+ if (delta.x() > 0 || delta.y() > 0) {
+ m_selectionWidget->resize(delta.x(), delta.y());
+ } else {
+ QPoint source(startPos);
+ m_selectionWidget->move(event->pos());
+ source -= event->pos();
+ m_selectionWidget->resize(source.x(), source.y());
+ }
}
}
#include "webview.moc"
diff --git a/webview.h b/webview.h
index 1aab2cd..6cebd1c 100644
--- a/webview.h
+++ b/webview.h
@@ -1,43 +1,47 @@
/***************************************************************************
* Copyright (C) 2009 by Alessandro Diaferia <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
**************************************************************************/
#ifndef WEBVIEW_H
#define WEBVIEW_H
#include <QtWebKit/QWebView>
class SelectionWidget;
class WebView : public QWebView
{
Q_OBJECT
public:
WebView(QWidget *parent = 0);
~WebView();
private:
bool m_advancedSelection;
SelectionWidget *m_selectionWidget;
+ QPoint startPos;
+
+signals:
+ void previewReady(const QPixmap &, const QString &);
protected:
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
};
#endif
|
alediaferia/webpagewatcher | c862a7ce4b8710c52a45b303183c9649192e7d90 | improving ui | diff --git a/previewwidget.ui b/previewwidget.ui
new file mode 100644
index 0000000..6f020a2
--- /dev/null
+++ b/previewwidget.ui
@@ -0,0 +1,44 @@
+<ui version="4.0" >
+ <class>PreviewWidget</class>
+ <widget class="QWidget" name="PreviewWidget" >
+ <property name="geometry" >
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>325</width>
+ <height>518</height>
+ </rect>
+ </property>
+ <property name="windowTitle" >
+ <string>Form</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout" >
+ <item>
+ <widget class="QScrollArea" name="scrollArea" >
+ <property name="widgetResizable" >
+ <bool>true</bool>
+ </property>
+ <widget class="QWidget" name="scrollAreaWidgetContents" >
+ <property name="geometry" >
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>311</width>
+ <height>247</height>
+ </rect>
+ </property>
+ </widget>
+ </widget>
+ </item>
+ <item>
+ <widget class="QTextBrowser" name="textBrowser" >
+ <property name="frameShape" >
+ <enum>QFrame::NoFrame</enum>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
|
solidsnack/shuffle | aec8d3671a9548767d9df2acb2fb996b43391304 | Including samples and a style file. | diff --git a/sample-run/README b/sample-run/README
new file mode 100644
index 0000000..1b504e9
--- /dev/null
+++ b/sample-run/README
@@ -0,0 +1,7 @@
+
+ Generated with:
+
+ :; ../dist/build/shuffle-bingo-html/shuffle-bingo-html 10 < list | tar x
+
+ The image and style files have already been placed in the output directory.
+
diff --git a/sample-run/list b/sample-run/list
new file mode 100644
index 0000000..d5988b4
--- /dev/null
+++ b/sample-run/list
@@ -0,0 +1,38 @@
+is wearing a hat
+is wearing glasses
+is wearing a bow tie
+needs a haircut
+is fucking hot
+talks like Butthead
+has dyed hair
+has been to Burning Man
+needs a mustache
+looks like Mickey Mouse
+is John Waters
+says the word "Noisebridge"
+runs over time
+says "um" more than ten times
+has spoken at 5mof before
+has never spoken at 5mof before
+has never been to Noisebrige before
+is a Noisebridge member
+is not a Noisebridge member
+is deliberately trying to match items in this game
+is trying to avoid being matched to this game
+has tattoos
+has a Hitler mustache
+violates Godwin's law
+uses their own laptop
+protests against the BINGO game
+is very apologetic
+says the word "dongs" more than five times
+is not wearing pants
+wears a nerdy tshirt
+confuses the hell out of me
+shows a slide of circuits
+likes kitties. aww, kitties!
+rides a bike
+is a probable spook
+has a Noisebridge sticker on their laptop
+has taught a class at Noisebridge
+
diff --git a/sample-run/shuffle-bingo-html-output/00.html b/sample-run/shuffle-bingo-html-output/00.html
new file mode 100644
index 0000000..d724ef3
--- /dev/null
+++ b/sample-run/shuffle-bingo-html-output/00.html
@@ -0,0 +1,56 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!DOCTYPE html
+ PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
+ 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd' >
+<html>
+<head>
+<title> title-it </title>
+<link href='css.css' rel='stylesheet' type='text/css' />
+</head>
+<body>
+<h1 id='shuffle-bingo-header'> header-message </h1>
+<div id='shuffle-bingo-card'> <table> <tbody>
+<tr>
+<td> talks like Butthead </td>
+<td> needs a mustache </td>
+<td> confuses the hell out of me </td>
+<td> is a Noisebridge member </td>
+<td> rides a bike </td>
+</tr>
+
+<tr>
+<td> has spoken at 5mof before </td>
+<td> is deliberately trying to match items in this game </td>
+<td> is trying to avoid being matched to this game </td>
+<td> looks like Mickey Mouse </td>
+<td> is fucking hot </td>
+</tr>
+
+<tr>
+<td> is not a Noisebridge member </td>
+<td> shows a slide of circuits </td>
+<td> <img src='png.png'></img> </td>
+<td> is John Waters </td>
+<td> has been to Burning Man </td>
+</tr>
+
+<tr>
+<td> is wearing glasses </td>
+<td> says the word "dongs" more than five times </td>
+<td> uses their own laptop </td>
+<td> says "um" more than ten times </td>
+<td> is not wearing pants </td>
+</tr>
+
+<tr>
+<td> is very apologetic </td>
+<td> has tattoos </td>
+<td> has never been to Noisebrige before </td>
+<td> is a probable spook </td>
+<td> wears a nerdy tshirt </td>
+</tr>
+
+</tbody> </table> </div>
+<div id='shuffle-bingo-footer'> <p> footer-message </p> </div>
+</body>
+</html>
diff --git a/sample-run/shuffle-bingo-html-output/01.html b/sample-run/shuffle-bingo-html-output/01.html
new file mode 100644
index 0000000..e5f2533
--- /dev/null
+++ b/sample-run/shuffle-bingo-html-output/01.html
@@ -0,0 +1,56 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!DOCTYPE html
+ PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
+ 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd' >
+<html>
+<head>
+<title> title-it </title>
+<link href='css.css' rel='stylesheet' type='text/css' />
+</head>
+<body>
+<h1 id='shuffle-bingo-header'> header-message </h1>
+<div id='shuffle-bingo-card'> <table> <tbody>
+<tr>
+<td> looks like Mickey Mouse </td>
+<td> is not a Noisebridge member </td>
+<td> shows a slide of circuits </td>
+<td> is John Waters </td>
+<td> has been to Burning Man </td>
+</tr>
+
+<tr>
+<td> is deliberately trying to match items in this game </td>
+<td> is wearing glasses </td>
+<td> says the word "dongs" more than five times </td>
+<td> rides a bike </td>
+<td> uses their own laptop </td>
+</tr>
+
+<tr>
+<td> says "um" more than ten times </td>
+<td> needs a mustache </td>
+<td> <img src='png.png'></img> </td>
+<td> is not wearing pants </td>
+<td> is very apologetic </td>
+</tr>
+
+<tr>
+<td> has tattoos </td>
+<td> has never been to Noisebrige before </td>
+<td> is a probable spook </td>
+<td> wears a nerdy tshirt </td>
+<td> has a Hitler mustache </td>
+</tr>
+
+<tr>
+<td> protests against the BINGO game </td>
+<td> likes kitties. aww, kitties! </td>
+<td> has dyed hair </td>
+<td> has spoken at 5mof before </td>
+<td> talks like Butthead </td>
+</tr>
+
+</tbody> </table> </div>
+<div id='shuffle-bingo-footer'> <p> footer-message </p> </div>
+</body>
+</html>
diff --git a/sample-run/shuffle-bingo-html-output/02.html b/sample-run/shuffle-bingo-html-output/02.html
new file mode 100644
index 0000000..8a16305
--- /dev/null
+++ b/sample-run/shuffle-bingo-html-output/02.html
@@ -0,0 +1,56 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!DOCTYPE html
+ PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
+ 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd' >
+<html>
+<head>
+<title> title-it </title>
+<link href='css.css' rel='stylesheet' type='text/css' />
+</head>
+<body>
+<h1 id='shuffle-bingo-header'> header-message </h1>
+<div id='shuffle-bingo-card'> <table> <tbody>
+<tr>
+<td> uses their own laptop </td>
+<td> says "um" more than ten times </td>
+<td> needs a mustache </td>
+<td> is not wearing pants </td>
+<td> is very apologetic </td>
+</tr>
+
+<tr>
+<td> looks like Mickey Mouse </td>
+<td> has tattoos </td>
+<td> has never been to Noisebrige before </td>
+<td> is a probable spook </td>
+<td> wears a nerdy tshirt </td>
+</tr>
+
+<tr>
+<td> has a Hitler mustache </td>
+<td> protests against the BINGO game </td>
+<td> <img src='png.png'></img> </td>
+<td> has been to Burning Man </td>
+<td> likes kitties. aww, kitties! </td>
+</tr>
+
+<tr>
+<td> has dyed hair </td>
+<td> has spoken at 5mof before </td>
+<td> talks like Butthead </td>
+<td> violates Godwin's law </td>
+<td> needs a haircut </td>
+</tr>
+
+<tr>
+<td> confuses the hell out of me </td>
+<td> is wearing glasses </td>
+<td> is a Noisebridge member </td>
+<td> is trying to avoid being matched to this game </td>
+<td> has a Noisebridge sticker on their laptop </td>
+</tr>
+
+</tbody> </table> </div>
+<div id='shuffle-bingo-footer'> <p> footer-message </p> </div>
+</body>
+</html>
diff --git a/sample-run/shuffle-bingo-html-output/03.html b/sample-run/shuffle-bingo-html-output/03.html
new file mode 100644
index 0000000..ee235be
--- /dev/null
+++ b/sample-run/shuffle-bingo-html-output/03.html
@@ -0,0 +1,56 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!DOCTYPE html
+ PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
+ 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd' >
+<html>
+<head>
+<title> title-it </title>
+<link href='css.css' rel='stylesheet' type='text/css' />
+</head>
+<body>
+<h1 id='shuffle-bingo-header'> header-message </h1>
+<div id='shuffle-bingo-card'> <table> <tbody>
+<tr>
+<td> is not wearing pants </td>
+<td> has a Hitler mustache </td>
+<td> protests against the BINGO game </td>
+<td> has been to Burning Man </td>
+<td> likes kitties. aww, kitties! </td>
+</tr>
+
+<tr>
+<td> has dyed hair </td>
+<td> has spoken at 5mof before </td>
+<td> talks like Butthead </td>
+<td> violates Godwin's law </td>
+<td> needs a haircut </td>
+</tr>
+
+<tr>
+<td> confuses the hell out of me </td>
+<td> says "um" more than ten times </td>
+<td> <img src='png.png'></img> </td>
+<td> has tattoos </td>
+<td> is wearing glasses </td>
+</tr>
+
+<tr>
+<td> is a Noisebridge member </td>
+<td> is a probable spook </td>
+<td> wears a nerdy tshirt </td>
+<td> is trying to avoid being matched to this game </td>
+<td> has never been to Noisebrige before </td>
+</tr>
+
+<tr>
+<td> has a Noisebridge sticker on their laptop </td>
+<td> looks like Mickey Mouse </td>
+<td> is wearing a bow tie </td>
+<td> is wearing a hat </td>
+<td> is very apologetic </td>
+</tr>
+
+</tbody> </table> </div>
+<div id='shuffle-bingo-footer'> <p> footer-message </p> </div>
+</body>
+</html>
diff --git a/sample-run/shuffle-bingo-html-output/04.html b/sample-run/shuffle-bingo-html-output/04.html
new file mode 100644
index 0000000..4f408ef
--- /dev/null
+++ b/sample-run/shuffle-bingo-html-output/04.html
@@ -0,0 +1,56 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!DOCTYPE html
+ PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
+ 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd' >
+<html>
+<head>
+<title> title-it </title>
+<link href='css.css' rel='stylesheet' type='text/css' />
+</head>
+<body>
+<h1 id='shuffle-bingo-header'> header-message </h1>
+<div id='shuffle-bingo-card'> <table> <tbody>
+<tr>
+<td> has spoken at 5mof before </td>
+<td> needs a haircut </td>
+<td> confuses the hell out of me </td>
+<td> says "um" more than ten times </td>
+<td> has tattoos </td>
+</tr>
+
+<tr>
+<td> is wearing glasses </td>
+<td> is a Noisebridge member </td>
+<td> is a probable spook </td>
+<td> wears a nerdy tshirt </td>
+<td> is trying to avoid being matched to this game </td>
+</tr>
+
+<tr>
+<td> has never been to Noisebrige before </td>
+<td> protests against the BINGO game </td>
+<td> <img src='png.png'></img> </td>
+<td> has a Noisebridge sticker on their laptop </td>
+<td> has a Hitler mustache </td>
+</tr>
+
+<tr>
+<td> has dyed hair </td>
+<td> looks like Mickey Mouse </td>
+<td> is wearing a bow tie </td>
+<td> is wearing a hat </td>
+<td> is very apologetic </td>
+</tr>
+
+<tr>
+<td> rides a bike </td>
+<td> has taught a class at Noisebridge </td>
+<td> uses their own laptop </td>
+<td> is not wearing pants </td>
+<td> shows a slide of circuits </td>
+</tr>
+
+</tbody> </table> </div>
+<div id='shuffle-bingo-footer'> <p> footer-message </p> </div>
+</body>
+</html>
diff --git a/sample-run/shuffle-bingo-html-output/05.html b/sample-run/shuffle-bingo-html-output/05.html
new file mode 100644
index 0000000..53805f2
--- /dev/null
+++ b/sample-run/shuffle-bingo-html-output/05.html
@@ -0,0 +1,56 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!DOCTYPE html
+ PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
+ 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd' >
+<html>
+<head>
+<title> title-it </title>
+<link href='css.css' rel='stylesheet' type='text/css' />
+</head>
+<body>
+<h1 id='shuffle-bingo-header'> header-message </h1>
+<div id='shuffle-bingo-card'> <table> <tbody>
+<tr>
+<td> is trying to avoid being matched to this game </td>
+<td> has never been to Noisebrige before </td>
+<td> protests against the BINGO game </td>
+<td> has a Noisebridge sticker on their laptop </td>
+<td> is wearing glasses </td>
+</tr>
+
+<tr>
+<td> has a Hitler mustache </td>
+<td> has dyed hair </td>
+<td> looks like Mickey Mouse </td>
+<td> is wearing a bow tie </td>
+<td> is wearing a hat </td>
+</tr>
+
+<tr>
+<td> is very apologetic </td>
+<td> has spoken at 5mof before </td>
+<td> <img src='png.png'></img> </td>
+<td> rides a bike </td>
+<td> has taught a class at Noisebridge </td>
+</tr>
+
+<tr>
+<td> uses their own laptop </td>
+<td> is not wearing pants </td>
+<td> is a probable spook </td>
+<td> shows a slide of circuits </td>
+<td> needs a mustache </td>
+</tr>
+
+<tr>
+<td> wears a nerdy tshirt </td>
+<td> talks like Butthead </td>
+<td> is not a Noisebridge member </td>
+<td> needs a haircut </td>
+<td> says the word "Noisebridge" </td>
+</tr>
+
+</tbody> </table> </div>
+<div id='shuffle-bingo-footer'> <p> footer-message </p> </div>
+</body>
+</html>
diff --git a/sample-run/shuffle-bingo-html-output/06.html b/sample-run/shuffle-bingo-html-output/06.html
new file mode 100644
index 0000000..9563ec9
--- /dev/null
+++ b/sample-run/shuffle-bingo-html-output/06.html
@@ -0,0 +1,56 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!DOCTYPE html
+ PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
+ 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd' >
+<html>
+<head>
+<title> title-it </title>
+<link href='css.css' rel='stylesheet' type='text/css' />
+</head>
+<body>
+<h1 id='shuffle-bingo-header'> header-message </h1>
+<div id='shuffle-bingo-card'> <table> <tbody>
+<tr>
+<td> is very apologetic </td>
+<td> has spoken at 5mof before </td>
+<td> rides a bike </td>
+<td> has taught a class at Noisebridge </td>
+<td> protests against the BINGO game </td>
+</tr>
+
+<tr>
+<td> uses their own laptop </td>
+<td> is not wearing pants </td>
+<td> is a probable spook </td>
+<td> shows a slide of circuits </td>
+<td> is wearing glasses </td>
+</tr>
+
+<tr>
+<td> needs a mustache </td>
+<td> is trying to avoid being matched to this game </td>
+<td> <img src='png.png'></img> </td>
+<td> wears a nerdy tshirt </td>
+<td> talks like Butthead </td>
+</tr>
+
+<tr>
+<td> has a Hitler mustache </td>
+<td> is not a Noisebridge member </td>
+<td> has never been to Noisebrige before </td>
+<td> is wearing a bow tie </td>
+<td> needs a haircut </td>
+</tr>
+
+<tr>
+<td> says the word "Noisebridge" </td>
+<td> has never spoken at 5mof before </td>
+<td> has dyed hair </td>
+<td> has a Noisebridge sticker on their laptop </td>
+<td> says the word "dongs" more than five times </td>
+</tr>
+
+</tbody> </table> </div>
+<div id='shuffle-bingo-footer'> <p> footer-message </p> </div>
+</body>
+</html>
diff --git a/sample-run/shuffle-bingo-html-output/07.html b/sample-run/shuffle-bingo-html-output/07.html
new file mode 100644
index 0000000..62354aa
--- /dev/null
+++ b/sample-run/shuffle-bingo-html-output/07.html
@@ -0,0 +1,56 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!DOCTYPE html
+ PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
+ 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd' >
+<html>
+<head>
+<title> title-it </title>
+<link href='css.css' rel='stylesheet' type='text/css' />
+</head>
+<body>
+<h1 id='shuffle-bingo-header'> header-message </h1>
+<div id='shuffle-bingo-card'> <table> <tbody>
+<tr>
+<td> is wearing glasses </td>
+<td> needs a mustache </td>
+<td> shows a slide of circuits </td>
+<td> is trying to avoid being matched to this game </td>
+<td> wears a nerdy tshirt </td>
+</tr>
+
+<tr>
+<td> talks like Butthead </td>
+<td> protests against the BINGO game </td>
+<td> uses their own laptop </td>
+<td> has a Hitler mustache </td>
+<td> is a probable spook </td>
+</tr>
+
+<tr>
+<td> is not a Noisebridge member </td>
+<td> is very apologetic </td>
+<td> <img src='png.png'></img> </td>
+<td> has never been to Noisebrige before </td>
+<td> is wearing a bow tie </td>
+</tr>
+
+<tr>
+<td> needs a haircut </td>
+<td> says the word "Noisebridge" </td>
+<td> has never spoken at 5mof before </td>
+<td> has dyed hair </td>
+<td> has a Noisebridge sticker on their laptop </td>
+</tr>
+
+<tr>
+<td> says the word "dongs" more than five times </td>
+<td> violates Godwin's law </td>
+<td> confuses the hell out of me </td>
+<td> has taught a class at Noisebridge </td>
+<td> is wearing a hat </td>
+</tr>
+
+</tbody> </table> </div>
+<div id='shuffle-bingo-footer'> <p> footer-message </p> </div>
+</body>
+</html>
diff --git a/sample-run/shuffle-bingo-html-output/08.html b/sample-run/shuffle-bingo-html-output/08.html
new file mode 100644
index 0000000..69b2b34
--- /dev/null
+++ b/sample-run/shuffle-bingo-html-output/08.html
@@ -0,0 +1,56 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!DOCTYPE html
+ PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
+ 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd' >
+<html>
+<head>
+<title> title-it </title>
+<link href='css.css' rel='stylesheet' type='text/css' />
+</head>
+<body>
+<h1 id='shuffle-bingo-header'> header-message </h1>
+<div id='shuffle-bingo-card'> <table> <tbody>
+<tr>
+<td> talks like Butthead </td>
+<td> has a Hitler mustache </td>
+<td> is a probable spook </td>
+<td> is not a Noisebridge member </td>
+<td> is very apologetic </td>
+</tr>
+
+<tr>
+<td> has never been to Noisebrige before </td>
+<td> shows a slide of circuits </td>
+<td> is wearing a bow tie </td>
+<td> needs a haircut </td>
+<td> says the word "Noisebridge" </td>
+</tr>
+
+<tr>
+<td> has never spoken at 5mof before </td>
+<td> has dyed hair </td>
+<td> <img src='png.png'></img> </td>
+<td> has a Noisebridge sticker on their laptop </td>
+<td> says the word "dongs" more than five times </td>
+</tr>
+
+<tr>
+<td> violates Godwin's law </td>
+<td> confuses the hell out of me </td>
+<td> wears a nerdy tshirt </td>
+<td> has taught a class at Noisebridge </td>
+<td> is wearing a hat </td>
+</tr>
+
+<tr>
+<td> is fucking hot </td>
+<td> uses their own laptop </td>
+<td> has tattoos </td>
+<td> is trying to avoid being matched to this game </td>
+<td> needs a mustache </td>
+</tr>
+
+</tbody> </table> </div>
+<div id='shuffle-bingo-footer'> <p> footer-message </p> </div>
+</body>
+</html>
diff --git a/sample-run/shuffle-bingo-html-output/09.html b/sample-run/shuffle-bingo-html-output/09.html
new file mode 100644
index 0000000..9821c89
--- /dev/null
+++ b/sample-run/shuffle-bingo-html-output/09.html
@@ -0,0 +1,56 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!DOCTYPE html
+ PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
+ 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd' >
+<html>
+<head>
+<title> title-it </title>
+<link href='css.css' rel='stylesheet' type='text/css' />
+</head>
+<body>
+<h1 id='shuffle-bingo-header'> header-message </h1>
+<div id='shuffle-bingo-card'> <table> <tbody>
+<tr>
+<td> is wearing a bow tie </td>
+<td> needs a haircut </td>
+<td> says the word "Noisebridge" </td>
+<td> has never spoken at 5mof before </td>
+<td> shows a slide of circuits </td>
+</tr>
+
+<tr>
+<td> has dyed hair </td>
+<td> has a Noisebridge sticker on their laptop </td>
+<td> says the word "dongs" more than five times </td>
+<td> violates Godwin's law </td>
+<td> confuses the hell out of me </td>
+</tr>
+
+<tr>
+<td> wears a nerdy tshirt </td>
+<td> has taught a class at Noisebridge </td>
+<td> <img src='png.png'></img> </td>
+<td> is wearing a hat </td>
+<td> is fucking hot </td>
+</tr>
+
+<tr>
+<td> uses their own laptop </td>
+<td> has tattoos </td>
+<td> is trying to avoid being matched to this game </td>
+<td> has never been to Noisebrige before </td>
+<td> needs a mustache </td>
+</tr>
+
+<tr>
+<td> is a Noisebridge member </td>
+<td> likes kitties. aww, kitties! </td>
+<td> says "um" more than ten times </td>
+<td> has spoken at 5mof before </td>
+<td> talks like Butthead </td>
+</tr>
+
+</tbody> </table> </div>
+<div id='shuffle-bingo-footer'> <p> footer-message </p> </div>
+</body>
+</html>
diff --git a/sample-run/shuffle-bingo-html-output/css.css b/sample-run/shuffle-bingo-html-output/css.css
new file mode 100644
index 0000000..91fa1d3
--- /dev/null
+++ b/sample-run/shuffle-bingo-html-output/css.css
@@ -0,0 +1,42 @@
+body {
+ text-align: center;
+ border: 0;
+ padding: 0;
+ margin: 0;
+}
+
+div#shuffle-bingo-card, h1#shuffle-bingo-header, div#shuffle-bingo-footer {
+ position: fixed
+ left: 0;
+ right: 0;
+}
+
+h1#shuffle-bingo-header {
+ top: 0;
+ z-index: 1;
+}
+
+div#shuffle-bingo-footer {
+ bottom: 0;
+ z-index: 1;
+}
+
+div#shuffle-bingo-card {
+ top: 100px;
+ bottom: 0;
+ z-index: 0;
+}
+
+div#shuffle-bingo-card table {
+ margin-left: auto;
+ margin-right: auto;
+}
+div#shuffle-bingo-card table, div#shuffle-bingo-card td {
+ border: 1px solid black;
+}
+
+div#shuffle-bingo-card img, div#shuffle-bingo-card td {
+ height: 100px;
+ width: 115px;
+}
+
diff --git a/sample-run/shuffle-bingo-html-output/png.png b/sample-run/shuffle-bingo-html-output/png.png
new file mode 100644
index 0000000..bcab7e3
Binary files /dev/null and b/sample-run/shuffle-bingo-html-output/png.png differ
|
solidsnack/shuffle | 99548e202839edec0d5032fc1e1857d5f2cd7b3f | Works okay. | diff --git a/ShuffleBingoHTML.hs b/ShuffleBingoHTML.hs
index d9e05ca..1676f23 100755
--- a/ShuffleBingoHTML.hs
+++ b/ShuffleBingoHTML.hs
@@ -1,126 +1,128 @@
#!/usr/bin/env runhaskell
import Data.Word
import qualified Data.List as List
import qualified Data.Set as Set
import qualified Data.ByteString.Lazy as Bytes (hPutStr)
import qualified Data.ByteString.Lazy.Char8 as Bytes
import qualified Data.Char as Char
import Control.Applicative
import System.Environment
import System.IO
import System.Exit
import qualified System.Random as Random
import System.Posix.Time as Posix
import Text.Printf
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Tar.Entry as Tar
n = 24
usage name = unlines
[ "USAGE: " ++ name ++ " count < some-lines"
, ""
, " Shuffles lines into groups of "
++ show n ++ " unique lines, then puts them into"
, " an HTML table that is 5x5 and has an empty square in the middle."
, " You specify $count to get only that many files in the output. The"
, " output is a streaming TAR archive."
]
main = do
name <- getProgName
args <- getArgs
time <- floor . realToFrac <$> Posix.epochTime
if List.any (`elem` args) ["-h","-?","--help"]
then hPutStrLn stdout (usage name) >> exitSuccess
else go name args time
go name args time = do
case digitize args of
Left s -> fail s
Right count -> do
choices <- Set.fromList . no_empty . Bytes.lines <$> b_in
g <- Random.getStdGen
if Set.size choices < n
then fail "Not enough lines to choose from."
else do
(Bytes.hPutStr stdout . tar (name_nums count))
(render <$> block_out g count choices)
where
tar names contents = Tar.write (tars time dir' names contents)
dir = "shuffle-bingo-html-output"
Right dir' = Tar.toTarPath True "shuffle-bingo-html-output"
name_nums how_many = name <$> [0..(how_many-1)]
where
name num = p
where
Right p = Tar.toTarPath False
(dir ++ "/" ++ printf (digits ++ ".html") num)
digits = "%0" ++ (show . length . show) how_many ++ "d"
no_empty = filter (not . Bytes.all Char.isSpace)
fail s = do
hPutStrLn stderr s
hPutStrLn stderr ""
hPutStrLn stderr (usage name)
exitFailure
b_in = Bytes.hGetContents stdin
digitize :: [String] -> Either String Word
digitize [s] = case reads s of
[(i,"")] -> if i > 0 then Right i else Left "Non-positive."
_ -> Left "Argument error."
digitize _ = Left "Wrong number of args."
block_out :: Random.StdGen -> Word -> Set.Set t -> [[t]]
block_out g k choices = pick . List.nub <$> stepped
where
stepped = List.iterate (drop (fromIntegral k)) indices
indices = Random.randomRs (0, Set.size choices-1) g
pick = ((Set.toList choices !!) <$>)
render texts = Bytes.unlines
[ Bytes.pack "<?xml version='1.0' encoding='UTF-8'?>"
, Bytes.pack "<!DOCTYPE html"
, Bytes.pack " PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'"
, Bytes.pack " 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd' >"
, Bytes.pack "<html>"
, Bytes.pack "<head>"
- , Bytes.pack "<title>title-it</title>"
+ , Bytes.pack "<title> title-it </title>"
, Bytes.pack "<link href='css.css' rel='stylesheet' type='text/css' />"
, Bytes.pack "</head>"
- , Bytes.pack "<body> <table id='outer'> <tbody> <tr> <td>"
- , Bytes.pack "<table id='shuffle-bingo'> <tbody>"
+ , Bytes.pack "<body>"
+ , Bytes.pack "<h1 id='shuffle-bingo-header'> header-message </h1>"
+ , Bytes.pack "<div id='shuffle-bingo-card'> <table> <tbody>"
, tr (pick [0..4])
, tr (pick [5..9])
, tr (pick [10..11] ++ [place_image] ++ pick [12..13])
, tr (pick [14..18])
, tr (pick [19..23])
- , Bytes.pack "</tbody> </table>"
- , Bytes.pack "</td> </tr> </tbody> </table> </body>"
+ , Bytes.pack "</tbody> </table> </div>"
+ , Bytes.pack "<div id='shuffle-bingo-footer'> <p> footer-message </p> </div>"
+ , Bytes.pack "</body>"
, Bytes.pack "</html>"
]
where
tr elems = Bytes.unlines ([Bytes.pack "<tr>"] ++
(td <$> elems)
++ [Bytes.pack "</tr>"])
td text = Bytes.unwords
[Bytes.pack "<td>", text, Bytes.pack "</td>"]
pick = ((texts !!) <$>)
place_image = Bytes.pack "<img src='png.png'></img>"
tars t dir names contents = t_set (Tar.directoryEntry dir) :
[ t_set (Tar.fileEntry name content) | name <- names | content <- contents ]
where
t_set entry = entry {Tar.entryTime = t}
|
solidsnack/shuffle | b6cef1e64c8c2f2ac4405ffb4079ed26cdf46d59 | Not quite right but probably the most HTML I will use. | diff --git a/ShuffleBingoHTML.hs b/ShuffleBingoHTML.hs
index 456c4d0..d9e05ca 100755
--- a/ShuffleBingoHTML.hs
+++ b/ShuffleBingoHTML.hs
@@ -1,114 +1,126 @@
#!/usr/bin/env runhaskell
import Data.Word
import qualified Data.List as List
import qualified Data.Set as Set
import qualified Data.ByteString.Lazy as Bytes (hPutStr)
import qualified Data.ByteString.Lazy.Char8 as Bytes
import qualified Data.Char as Char
import Control.Applicative
import System.Environment
import System.IO
import System.Exit
import qualified System.Random as Random
import System.Posix.Time as Posix
import Text.Printf
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Tar.Entry as Tar
n = 24
usage name = unlines
[ "USAGE: " ++ name ++ " count < some-lines"
, ""
, " Shuffles lines into groups of "
++ show n ++ " unique lines, then puts them into"
, " an HTML table that is 5x5 and has an empty square in the middle."
, " You specify $count to get only that many files in the output. The"
, " output is a streaming TAR archive."
]
main = do
name <- getProgName
args <- getArgs
time <- floor . realToFrac <$> Posix.epochTime
if List.any (`elem` args) ["-h","-?","--help"]
then hPutStrLn stdout (usage name) >> exitSuccess
else go name args time
go name args time = do
case digitize args of
Left s -> fail s
Right count -> do
choices <- Set.fromList . no_empty . Bytes.lines <$> b_in
g <- Random.getStdGen
if Set.size choices < n
then fail "Not enough lines to choose from."
else do
(Bytes.hPutStr stdout . tar (name_nums count))
(render <$> block_out g count choices)
where
tar names contents = Tar.write (tars time dir' names contents)
dir = "shuffle-bingo-html-output"
Right dir' = Tar.toTarPath True "shuffle-bingo-html-output"
name_nums how_many = name <$> [0..(how_many-1)]
where
name num = p
where
Right p = Tar.toTarPath False
(dir ++ "/" ++ printf (digits ++ ".html") num)
digits = "%0" ++ (show . length . show) how_many ++ "d"
no_empty = filter (not . Bytes.all Char.isSpace)
fail s = do
hPutStrLn stderr s
hPutStrLn stderr ""
hPutStrLn stderr (usage name)
exitFailure
b_in = Bytes.hGetContents stdin
digitize :: [String] -> Either String Word
digitize [s] = case reads s of
[(i,"")] -> if i > 0 then Right i else Left "Non-positive."
_ -> Left "Argument error."
digitize _ = Left "Wrong number of args."
block_out :: Random.StdGen -> Word -> Set.Set t -> [[t]]
block_out g k choices = pick . List.nub <$> stepped
where
stepped = List.iterate (drop (fromIntegral k)) indices
indices = Random.randomRs (0, Set.size choices-1) g
pick = ((Set.toList choices !!) <$>)
render texts = Bytes.unlines
- [ Bytes.pack "<table> <tbody>"
+ [ Bytes.pack "<?xml version='1.0' encoding='UTF-8'?>"
+ , Bytes.pack "<!DOCTYPE html"
+ , Bytes.pack " PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'"
+ , Bytes.pack " 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd' >"
+ , Bytes.pack "<html>"
+ , Bytes.pack "<head>"
+ , Bytes.pack "<title>title-it</title>"
+ , Bytes.pack "<link href='css.css' rel='stylesheet' type='text/css' />"
+ , Bytes.pack "</head>"
+ , Bytes.pack "<body> <table id='outer'> <tbody> <tr> <td>"
+ , Bytes.pack "<table id='shuffle-bingo'> <tbody>"
, tr (pick [0..4])
, tr (pick [5..9])
, tr (pick [10..11] ++ [place_image] ++ pick [12..13])
, tr (pick [14..18])
, tr (pick [19..23])
- , Bytes.pack "</table> </tbody>"
+ , Bytes.pack "</tbody> </table>"
+ , Bytes.pack "</td> </tr> </tbody> </table> </body>"
+ , Bytes.pack "</html>"
]
where
tr elems = Bytes.unlines ([Bytes.pack "<tr>"] ++
(td <$> elems)
++ [Bytes.pack "</tr>"])
td text = Bytes.unwords
[Bytes.pack "<td>", text, Bytes.pack "</td>"]
pick = ((texts !!) <$>)
- place_image = Bytes.pack "<!-- Place image here. -->"
+ place_image = Bytes.pack "<img src='png.png'></img>"
tars t dir names contents = t_set (Tar.directoryEntry dir) :
[ t_set (Tar.fileEntry name content) | name <- names | content <- contents ]
where
t_set entry = entry {Tar.entryTime = t}
|
solidsnack/shuffle | 3c1c2b11a2ee7afd734ab3c252ee760d36a31cbb | Too many table cells :( | diff --git a/ShuffleBingoHTML.hs b/ShuffleBingoHTML.hs
index 017ab54..456c4d0 100755
--- a/ShuffleBingoHTML.hs
+++ b/ShuffleBingoHTML.hs
@@ -1,114 +1,114 @@
#!/usr/bin/env runhaskell
import Data.Word
import qualified Data.List as List
import qualified Data.Set as Set
import qualified Data.ByteString.Lazy as Bytes (hPutStr)
import qualified Data.ByteString.Lazy.Char8 as Bytes
import qualified Data.Char as Char
import Control.Applicative
import System.Environment
import System.IO
import System.Exit
import qualified System.Random as Random
import System.Posix.Time as Posix
import Text.Printf
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Tar.Entry as Tar
n = 24
usage name = unlines
[ "USAGE: " ++ name ++ " count < some-lines"
, ""
, " Shuffles lines into groups of "
++ show n ++ " unique lines, then puts them into"
, " an HTML table that is 5x5 and has an empty square in the middle."
, " You specify $count to get only that many files in the output. The"
, " output is a streaming TAR archive."
]
main = do
name <- getProgName
args <- getArgs
time <- floor . realToFrac <$> Posix.epochTime
if List.any (`elem` args) ["-h","-?","--help"]
then hPutStrLn stdout (usage name) >> exitSuccess
else go name args time
go name args time = do
case digitize args of
Left s -> fail s
Right count -> do
choices <- Set.fromList . no_empty . Bytes.lines <$> b_in
g <- Random.getStdGen
if Set.size choices < n
then fail "Not enough lines to choose from."
else do
(Bytes.hPutStr stdout . tar (name_nums count))
(render <$> block_out g count choices)
where
tar names contents = Tar.write (tars time dir' names contents)
dir = "shuffle-bingo-html-output"
Right dir' = Tar.toTarPath True "shuffle-bingo-html-output"
name_nums how_many = name <$> [0..(how_many-1)]
where
name num = p
where
Right p = Tar.toTarPath False
(dir ++ "/" ++ printf (digits ++ ".html") num)
digits = "%0" ++ (show . length . show) how_many ++ "d"
no_empty = filter (not . Bytes.all Char.isSpace)
fail s = do
hPutStrLn stderr s
hPutStrLn stderr ""
hPutStrLn stderr (usage name)
exitFailure
b_in = Bytes.hGetContents stdin
digitize :: [String] -> Either String Word
digitize [s] = case reads s of
[(i,"")] -> if i > 0 then Right i else Left "Non-positive."
_ -> Left "Argument error."
digitize _ = Left "Wrong number of args."
block_out :: Random.StdGen -> Word -> Set.Set t -> [[t]]
block_out g k choices = pick . List.nub <$> stepped
where
stepped = List.iterate (drop (fromIntegral k)) indices
indices = Random.randomRs (0, Set.size choices-1) g
pick = ((Set.toList choices !!) <$>)
render texts = Bytes.unlines
[ Bytes.pack "<table> <tbody>"
, tr (pick [0..4])
, tr (pick [5..9])
, tr (pick [10..11] ++ [place_image] ++ pick [12..13])
, tr (pick [14..18])
- , tr (pick [19..24])
+ , tr (pick [19..23])
, Bytes.pack "</table> </tbody>"
]
where
tr elems = Bytes.unlines ([Bytes.pack "<tr>"] ++
(td <$> elems)
++ [Bytes.pack "</tr>"])
td text = Bytes.unwords
[Bytes.pack "<td>", text, Bytes.pack "</td>"]
pick = ((texts !!) <$>)
place_image = Bytes.pack "<!-- Place image here. -->"
tars t dir names contents = t_set (Tar.directoryEntry dir) :
[ t_set (Tar.fileEntry name content) | name <- names | content <- contents ]
where
t_set entry = entry {Tar.entryTime = t}
|
solidsnack/shuffle | 4179ad27db4f71f21ce63ead0078fb3397b3e14f | Now with random, unique lines in each board (instead of a combination or permutation). | diff --git a/ShuffleBingoHTML.hs b/ShuffleBingoHTML.hs
index 52b1cac..017ab54 100755
--- a/ShuffleBingoHTML.hs
+++ b/ShuffleBingoHTML.hs
@@ -1,112 +1,114 @@
#!/usr/bin/env runhaskell
import Data.Word
import qualified Data.List as List
import qualified Data.Set as Set
import qualified Data.ByteString.Lazy as Bytes (hPutStr)
import qualified Data.ByteString.Lazy.Char8 as Bytes
import qualified Data.Char as Char
import Control.Applicative
import System.Environment
import System.IO
import System.Exit
-import Text.Printf
+import qualified System.Random as Random
import System.Posix.Time as Posix
+import Text.Printf
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Tar.Entry as Tar
n = 24
usage name = unlines
[ "USAGE: " ++ name ++ " count < some-lines"
, ""
, " Shuffles lines into groups of "
++ show n ++ " unique lines, then puts them into"
, " an HTML table that is 5x5 and has an empty square in the middle."
, " You specify $count to get only that many files in the output. The"
, " output is a streaming TAR archive."
]
main = do
name <- getProgName
args <- getArgs
time <- floor . realToFrac <$> Posix.epochTime
if List.any (`elem` args) ["-h","-?","--help"]
then hPutStrLn stdout (usage name) >> exitSuccess
else go name args time
go name args time = do
case digitize args of
Left s -> fail s
Right count -> do
choices <- Set.fromList . no_empty . Bytes.lines <$> b_in
+ g <- Random.getStdGen
if Set.size choices < n
then fail "Not enough lines to choose from."
else do
(Bytes.hPutStr stdout . tar (name_nums count))
- (render <$> block_out count choices)
+ (render <$> block_out g count choices)
where
tar names contents = Tar.write (tars time dir' names contents)
dir = "shuffle-bingo-html-output"
Right dir' = Tar.toTarPath True "shuffle-bingo-html-output"
name_nums how_many = name <$> [0..(how_many-1)]
where
name num = p
where
Right p = Tar.toTarPath False
(dir ++ "/" ++ printf (digits ++ ".html") num)
digits = "%0" ++ (show . length . show) how_many ++ "d"
no_empty = filter (not . Bytes.all Char.isSpace)
fail s = do
hPutStrLn stderr s
hPutStrLn stderr ""
hPutStrLn stderr (usage name)
exitFailure
b_in = Bytes.hGetContents stdin
digitize :: [String] -> Either String Word
digitize [s] = case reads s of
[(i,"")] -> if i > 0 then Right i else Left "Non-positive."
_ -> Left "Argument error."
digitize _ = Left "Wrong number of args."
-block_out :: Word -> Set.Set t -> [[t]]
-block_out choose choices = (combinations choose . Set.toList) choices
+block_out :: Random.StdGen -> Word -> Set.Set t -> [[t]]
+block_out g k choices = pick . List.nub <$> stepped
where
- combinations 0 _ = [[]]
- combinations _ [] = []
- combinations k (x:xs) = map (x:) (combinations (k-1) xs) ++ combinations k xs
+ stepped = List.iterate (drop (fromIntegral k)) indices
+ indices = Random.randomRs (0, Set.size choices-1) g
+ pick = ((Set.toList choices !!) <$>)
render texts = Bytes.unlines
[ Bytes.pack "<table> <tbody>"
, tr (pick [0..4])
, tr (pick [5..9])
, tr (pick [10..11] ++ [place_image] ++ pick [12..13])
, tr (pick [14..18])
, tr (pick [19..24])
, Bytes.pack "</table> </tbody>"
]
where
tr elems = Bytes.unlines ([Bytes.pack "<tr>"] ++
(td <$> elems)
++ [Bytes.pack "</tr>"])
td text = Bytes.unwords
[Bytes.pack "<td>", text, Bytes.pack "</td>"]
pick = ((texts !!) <$>)
place_image = Bytes.pack "<!-- Place image here. -->"
tars t dir names contents = t_set (Tar.directoryEntry dir) :
[ t_set (Tar.fileEntry name content) | name <- names | content <- contents ]
where
t_set entry = entry {Tar.entryTime = t}
diff --git a/shuffle-bingo.cabal b/shuffle-bingo.cabal
index e52c6c6..522fc13 100644
--- a/shuffle-bingo.cabal
+++ b/shuffle-bingo.cabal
@@ -1,27 +1,28 @@
name : shuffle-bingo
version : 0.0.0
license : BSD3
license-file : LICENSE
author : Jason Dusek
maintainer : [email protected]
homepage : http://github.com/jsnx/JSONb/
synopsis : Bingo shuffler for 5MOF.
description :
Shuffles input into a bingo card for 5 Minutes of Fame.
cabal-version : >= 1.6.0
build-type : Simple
extra-source-files : README
executable shuffle-bingo-html
main-is : ShuffleBingoHTML.hs
build-depends : base >= 2 && < 4
, tar >= 0.3.1.0
, bytestring >= 0.9
, containers
, unix
+ , random
extensions : NoMonomorphismRestriction
ParallelListComp
|
solidsnack/shuffle | 3111361b6175bb27252be792cdbc71376235f9b3 | Missing word in docs. | diff --git a/ShuffleBingoHTML.hs b/ShuffleBingoHTML.hs
index 28f7cbf..52b1cac 100755
--- a/ShuffleBingoHTML.hs
+++ b/ShuffleBingoHTML.hs
@@ -1,112 +1,112 @@
#!/usr/bin/env runhaskell
import Data.Word
import qualified Data.List as List
import qualified Data.Set as Set
import qualified Data.ByteString.Lazy as Bytes (hPutStr)
import qualified Data.ByteString.Lazy.Char8 as Bytes
import qualified Data.Char as Char
import Control.Applicative
import System.Environment
import System.IO
import System.Exit
import Text.Printf
import System.Posix.Time as Posix
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Tar.Entry as Tar
n = 24
usage name = unlines
[ "USAGE: " ++ name ++ " count < some-lines"
, ""
, " Shuffles lines into groups of "
++ show n ++ " unique lines, then puts them into"
, " an HTML table that is 5x5 and has an empty square in the middle."
, " You specify $count to get only that many files in the output. The"
- , " is a streaming TAR archive."
+ , " output is a streaming TAR archive."
]
main = do
name <- getProgName
args <- getArgs
time <- floor . realToFrac <$> Posix.epochTime
if List.any (`elem` args) ["-h","-?","--help"]
then hPutStrLn stdout (usage name) >> exitSuccess
else go name args time
go name args time = do
case digitize args of
Left s -> fail s
Right count -> do
choices <- Set.fromList . no_empty . Bytes.lines <$> b_in
if Set.size choices < n
then fail "Not enough lines to choose from."
else do
(Bytes.hPutStr stdout . tar (name_nums count))
(render <$> block_out count choices)
where
tar names contents = Tar.write (tars time dir' names contents)
dir = "shuffle-bingo-html-output"
Right dir' = Tar.toTarPath True "shuffle-bingo-html-output"
name_nums how_many = name <$> [0..(how_many-1)]
where
name num = p
where
Right p = Tar.toTarPath False
(dir ++ "/" ++ printf (digits ++ ".html") num)
digits = "%0" ++ (show . length . show) how_many ++ "d"
no_empty = filter (not . Bytes.all Char.isSpace)
fail s = do
hPutStrLn stderr s
hPutStrLn stderr ""
hPutStrLn stderr (usage name)
exitFailure
b_in = Bytes.hGetContents stdin
digitize :: [String] -> Either String Word
digitize [s] = case reads s of
[(i,"")] -> if i > 0 then Right i else Left "Non-positive."
_ -> Left "Argument error."
digitize _ = Left "Wrong number of args."
block_out :: Word -> Set.Set t -> [[t]]
block_out choose choices = (combinations choose . Set.toList) choices
where
combinations 0 _ = [[]]
combinations _ [] = []
combinations k (x:xs) = map (x:) (combinations (k-1) xs) ++ combinations k xs
render texts = Bytes.unlines
[ Bytes.pack "<table> <tbody>"
, tr (pick [0..4])
, tr (pick [5..9])
, tr (pick [10..11] ++ [place_image] ++ pick [12..13])
, tr (pick [14..18])
, tr (pick [19..24])
, Bytes.pack "</table> </tbody>"
]
where
tr elems = Bytes.unlines ([Bytes.pack "<tr>"] ++
(td <$> elems)
++ [Bytes.pack "</tr>"])
td text = Bytes.unwords
[Bytes.pack "<td>", text, Bytes.pack "</td>"]
pick = ((texts !!) <$>)
place_image = Bytes.pack "<!-- Place image here. -->"
tars t dir names contents = t_set (Tar.directoryEntry dir) :
[ t_set (Tar.fileEntry name content) | name <- names | content <- contents ]
where
t_set entry = entry {Tar.entryTime = t}
|
solidsnack/shuffle | 58258ccbb9f45d0626c0c8fb2eaf8984112aaaeb | Added help and correct time stamps. | diff --git a/ShuffleBingoHTML.hs b/ShuffleBingoHTML.hs
index 1234d9c..28f7cbf 100755
--- a/ShuffleBingoHTML.hs
+++ b/ShuffleBingoHTML.hs
@@ -1,108 +1,112 @@
#!/usr/bin/env runhaskell
import Data.Word
import qualified Data.List as List
import qualified Data.Set as Set
import qualified Data.ByteString.Lazy as Bytes (hPutStr)
import qualified Data.ByteString.Lazy.Char8 as Bytes
import qualified Data.Char as Char
import Control.Applicative
import System.Environment
import System.IO
-import System.IO (stdin, stderr, stdout)
import System.Exit
import Text.Printf
+import System.Posix.Time as Posix
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Tar.Entry as Tar
n = 24
usage name = unlines
[ "USAGE: " ++ name ++ " count < some-lines"
, ""
, " Shuffles lines into groups of "
++ show n ++ " unique lines, then puts them into"
, " an HTML table that is 5x5 and has an empty square in the middle."
, " You specify $count to get only that many files in the output. The"
, " is a streaming TAR archive."
]
main = do
name <- getProgName
- go name
+ args <- getArgs
+ time <- floor . realToFrac <$> Posix.epochTime
+ if List.any (`elem` args) ["-h","-?","--help"]
+ then hPutStrLn stdout (usage name) >> exitSuccess
+ else go name args time
-go name = do
- parsed <- digitize <$> getArgs
- case parsed of
+go name args time = do
+ case digitize args of
Left s -> fail s
Right count -> do
choices <- Set.fromList . no_empty . Bytes.lines <$> b_in
if Set.size choices < n
then fail "Not enough lines to choose from."
else do
(Bytes.hPutStr stdout . tar (name_nums count))
(render <$> block_out count choices)
where
- tar names contents = Tar.write (tars dir' names contents)
+ tar names contents = Tar.write (tars time dir' names contents)
dir = "shuffle-bingo-html-output"
Right dir' = Tar.toTarPath True "shuffle-bingo-html-output"
name_nums how_many = name <$> [0..(how_many-1)]
where
name num = p
where
Right p = Tar.toTarPath False
(dir ++ "/" ++ printf (digits ++ ".html") num)
digits = "%0" ++ (show . length . show) how_many ++ "d"
no_empty = filter (not . Bytes.all Char.isSpace)
fail s = do
hPutStrLn stderr s
hPutStrLn stderr ""
hPutStrLn stderr (usage name)
exitFailure
b_in = Bytes.hGetContents stdin
digitize :: [String] -> Either String Word
digitize [s] = case reads s of
[(i,"")] -> if i > 0 then Right i else Left "Non-positive."
_ -> Left "Argument error."
digitize _ = Left "Wrong number of args."
block_out :: Word -> Set.Set t -> [[t]]
block_out choose choices = (combinations choose . Set.toList) choices
where
combinations 0 _ = [[]]
combinations _ [] = []
combinations k (x:xs) = map (x:) (combinations (k-1) xs) ++ combinations k xs
render texts = Bytes.unlines
[ Bytes.pack "<table> <tbody>"
, tr (pick [0..4])
, tr (pick [5..9])
, tr (pick [10..11] ++ [place_image] ++ pick [12..13])
, tr (pick [14..18])
, tr (pick [19..24])
, Bytes.pack "</table> </tbody>"
]
where
tr elems = Bytes.unlines ([Bytes.pack "<tr>"] ++
(td <$> elems)
++ [Bytes.pack "</tr>"])
td text = Bytes.unwords
[Bytes.pack "<td>", text, Bytes.pack "</td>"]
pick = ((texts !!) <$>)
place_image = Bytes.pack "<!-- Place image here. -->"
-tars dir names contents = Tar.directoryEntry dir :
- [ Tar.fileEntry name content | name <- names | content <- contents ]
-
+tars t dir names contents = t_set (Tar.directoryEntry dir) :
+ [ t_set (Tar.fileEntry name content) | name <- names | content <- contents ]
+ where
+ t_set entry = entry {Tar.entryTime = t}
diff --git a/shuffle-bingo.cabal b/shuffle-bingo.cabal
index e2e9e08..e52c6c6 100644
--- a/shuffle-bingo.cabal
+++ b/shuffle-bingo.cabal
@@ -1,26 +1,27 @@
name : shuffle-bingo
version : 0.0.0
license : BSD3
license-file : LICENSE
author : Jason Dusek
maintainer : [email protected]
homepage : http://github.com/jsnx/JSONb/
synopsis : Bingo shuffler for 5MOF.
description :
Shuffles input into a bingo card for 5 Minutes of Fame.
cabal-version : >= 1.6.0
build-type : Simple
extra-source-files : README
executable shuffle-bingo-html
main-is : ShuffleBingoHTML.hs
build-depends : base >= 2 && < 4
, tar >= 0.3.1.0
, bytestring >= 0.9
, containers
+ , unix
extensions : NoMonomorphismRestriction
ParallelListComp
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.