static function getDbConnection()
 {
     if (!CommandCache::$db) {
         if (Yii::app()->params['sqlitecache_commands']) {
             $file = realpath(dirname(__FILE__) . '/../data/') . '/cmdcache.db';
             $init = false;
             if (@(!filesize($file))) {
                 $init = true;
             }
             $db = new CDbConnection('sqlite:' . $file);
             $db->emulatePrepare = true;
             $db->charset = 'utf8';
             $db->schemaCachingDuration = '3600';
             $db->active = true;
             if ($init) {
                 $cmd = $db->createCommand('create table if not exists `command_cache` (' . '`server_id` integer not null, `command` integer not null, `ts` integer not null,' . ' `data` text not null, primary key (`server_id`, `command`))');
                 $cmd->execute();
             }
             CommandCache::$db = $db;
         } else {
             CommandCache::$db = Yii::app()->db;
         }
     }
     return CommandCache::$db;
 }
 /**
  * Generates a string which is suitable for output into an sql query from
  * any data that may be outputable. This method protects strings against
  *
  * @param CDbConnection $connection
  * @param mixed $columnInsertValue
  * @return string
  */
 public function secureOutput(CDbConnection $connection, $columnInsertValue)
 {
     if ($columnInsertValue === null) {
         return 'NULL';
     }
     return $connection->quoteValue($columnInsertValue);
 }
Example #3
0
 public function actionIndex()
 {
     $data = array();
     if (!empty($_GET['dest'])) {
         $redirect = base64_decode($_GET['dest']);
     }
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {
         if (!isset($_GET['dest'])) {
             $redirect = $this->createUrl('index/index');
         }
         $email = formPostParams('email', VARIABLE_STRING);
         $password = formPostParams('password', VARIABLE_STRING);
         $condition = array(':email' => $email, ':password' => md5($password));
         $query = "SELECT * FROM {{" . $this->_table . "}} WHERE email = :email AND password = :password";
         $user = $this->db->createCommand($query)->bindValues($condition)->queryRow();
         if (!empty($user)) {
             Yii::app()->session['user'] = $user;
             $this->redirect($redirect);
         } else {
             createMessage('Email hoặc mật khẩu không đúng', 'danger');
         }
     } else {
         $user = Yii::app()->session['user'];
         if (!empty($user)) {
             $this->redirect($redirect);
         }
     }
     $this->renderPartial('index', array('data' => $data));
 }
 public function up()
 {
     try {
         $db = \Yii::app()->db;
         $dsn = 'mysql:host=127.0.0.1;port=3306;dbname=tiu_last';
         $connection = new CDbConnection($dsn, $db->username, $db->password);
         $connection->connectionStatus;
         echo "ALTER TABLE `specification` \n";
         $sql = "ALTER TABLE `specification`\n\t\t\t\t\tADD INDEX `id_product` (`id_product`);";
         $command = $connection->createCommand($sql)->execute();
         echo "ALTER TABLE `productToCat` \n";
         $sql = "ALTER TABLE `productToCat`\n\t\t\t\t\tADD INDEX `id_product` (`id_product`),\n\t\t\t\t\tADD INDEX `id_cat` (`id_cat`),\n\t\t\t\t\tADD INDEX `id_product_id_cat` (`id_product`, `id_cat`);";
         $command = $connection->createCommand($sql)->execute();
         echo "ALTER TABLE `image` \n";
         $sql = "ALTER TABLE `image`\n\t\t\t\t\tADD INDEX `id_item` (`id_item`);";
         $command = $connection->createCommand($sql)->execute();
         echo "ALTER TABLE `category_all` \n";
         $sql = "ALTER TABLE `category_all`\n\t\t\t\t\tADD INDEX `id_item` (`id_item`);";
         $command = $connection->createCommand($sql)->execute();
         $connection = null;
     } catch (CDbException $e) {
         echo $e->getMessage();
     }
     $this->execute("\n\t\t\tALTER TABLE `site_store_product`\n\t\t\t\tADD INDEX `user_id` (`user_id`);\n\t\t");
 }
Example #5
0
 public function makeDb(CDbConnection $db)
 {
     $bb_account_sql = $db->createCommand('INSERT INTO bb_account
                                     ( account_name, vendor_id )
                                     VALUES
                                     ( :account_name, :vendor_id )');
     $cps_order_sql = $db->createCommand('INSERT INTO cps_order
                                     ( vendor_id, order_id, place_order_time, sign_contract_time)
                                     VALUES
                                     ( :vendor_id, :order_id, :place_order_time, :sign_contract_time)
                                     ');
     $cps_purchase_order_sql = $db->createCommand('INSERT INTO cps_purchase_order
                                     ( order_id, expense, vendor_id, expense_ratio, purchase_order_id)
                                     VALUES
                                     ( :order_id, :expense, :vendor_id, :expense_ratio, :purchase_order_id)');
     $order_id = 10000;
     for ($i = 500; $i < 600; $i++) {
         $bb_account_sql->execute(array(':account_name' => 'vendor' . $i, ':vendor_id' => $i));
         for ($j = 0; $j < 10; $j++) {
             $order_id++;
             $cps_order_sql->execute(array(':vendor_id' => $i, ':order_id' => $order_id, ':place_order_time' => date("Y-m-D H:i:s"), ':sign_contract_time' => date('Y-m-d')));
             //'0000-00-00' COMMENT '签约时间',
             for ($k = 0; $k < 20; $k++) {
                 $cps_purchase_order_sql->execute(array(':order_id' => $order_id, ':expense' => $k * 88, ':vendor_id' => $i, ':purchase_order_id' => $order_id * 20 + $k, ':expense_ratio' => 0.03 + $k / 2000));
             }
         }
     }
 }
Example #6
0
 public function createUser()
 {
     $connection = new CDbConnection("mysql:host={$this->_DBHOST};dbname={$this->_DBNAME}", "{$this->_DBUSER}", "{$this->_DBPASS}");
     $sql = "INSERT INTO users (name,surname,login,password,email,telephone) VALUES('{$this->name}','{$this->surname}','{$this->login}','{$this->password}','{$this->email}','{$this->telephone}')";
     $command = $connection->createCommand($sql);
     $command->execute();
 }
 /**
  * Constructor.
  * @param CDbConnection $conn database connection.
  */
 public function __construct($conn)
 {
     $conn->setActive(true);
     $this->_connection = $conn;
     foreach ($conn->schemaCachingExclude as $name) {
         $this->_cacheExclude[$name] = true;
     }
 }
 public function testInitialized()
 {
     $db = new CDbConnection();
     $db->autoConnect = false;
     $this->assertFalse($db->isInitialized);
     $db->init();
     $this->assertTrue($db->isInitialized);
 }
Example #9
0
 public function createDbConnection($db_must_exists = true)
 {
     $conn_string = 'mysql:host=' . $this->db_host . ';' . ($db_must_exists ? 'dbname=' . $this->db_name : '');
     $con = new CDbConnection($conn_string, $this->db_login, $this->db_pass);
     $con->initSQLs = array("SET NAMES 'utf8' COLLATE 'utf8_general_ci';");
     $con->init();
     return $con;
 }
 /**
  * https://github.com/yiisoft/yii/issues/2449
  */
 public function testFetchKeysWithDbCommandSpecifiedAndPdoFetchObjEnabled()
 {
     $command1 = $this->db->createCommand()->select('*')->from('posts')->setFetchMode(PDO::FETCH_ASSOC);
     $dataProvider1 = new CSqlDataProvider($command1);
     $this->assertSame(array('1', '2', '3', '4', '5'), $dataProvider1->keys);
     $command2 = $this->db->createCommand()->select('*')->from('posts')->setFetchMode(PDO::FETCH_OBJ);
     $dataProvider2 = new CSqlDataProvider($command2);
     $this->assertSame(array('1', '2', '3', '4', '5'), $dataProvider2->keys);
 }
Example #11
0
 public function install()
 {
     # Does the application need installing? Check if database exists, and can connect
     try {
         # Required fields
         $required = array("db-host", "db-name", "db-username", "db-password", "table-prefix");
         # Did all the required fields get passed in?
         if (count(array_intersect($required, array_keys($_REQUEST))) != count($required)) {
             throw new Exception("Not all required fields were submitted.");
         }
         # Verify the required unempty fields
         foreach ($required as $field) {
             # Skip the fields that can be empty
             if ($field == "table-prefix" or $field == "db-password") {
                 continue;
             }
             # Check if empty, throw error if they are.
             if (empty($_REQUEST[$field])) {
                 throw new Exception("Field <i>" . lookupfieldname($field) . "</i> cannot be empty.");
             }
         }
         # Try connecting to the database with the passed in credentials
         try {
             # Setup connection details
             $dsn = 'mysql:host=' . $_REQUEST["db-host"] . ';dbname=' . $_REQUEST["db-name"];
             $username = $_REQUEST["db-username"];
             $password = $_REQUEST["db-password"];
             $prefix = $_REQUEST["table-prefix"];
             # Make the connection
             $conn = new CDbConnection($dsn, $username, $password);
             $conn->active = true;
             $conn->setActive(true);
         } catch (Exception $e) {
             throw new Exception("Could not connect to database. Make sure you have created the database first. Details: " . $e->getMessage());
         }
         # Setup the database params for saving in the extended configuration
         $db_params = array('components' => array('db' => array('connectionString' => $dsn, 'emulatePrepare' => true, 'username' => $username, 'password' => $password, 'charset' => 'utf8', 'tablePrefix' => $prefix)), 'params' => array('LOCALAPP_SERVER' => $_SERVER["HTTP_HOST"]));
         # Make sure to only overwrite if explicitly asked to
         $config_ext = Yii::app()->basePath . "\\config\\main-ext.php";
         if (is_file($config_ext)) {
             throw new Exception("Database configuration already exists. Delete this configuration in order to install this application.");
         }
         # Open up the file and write the new configuration.
         $handle = fopen($config_ext, "w");
         fwrite($handle, "<?php return ");
         fwrite($handle, var_export($db_params, true));
         fwrite($handle, "; ?>");
         fclose($handle);
         # Make read-only
         chmod($config_ext, 060);
     } catch (Exception $e) {
         $this->set_error($e->getMessage());
         return false;
     }
     # If we made it to here, installation is a success!
     return true;
 }
Example #12
0
 public function fork()
 {
     $this->b2b_DbConnection->setActive(false);
     $this->oneC_DbConnection->setActive(false);
     $pid = pcntl_fork();
     $this->b2b_DbConnection->setActive(true);
     $this->oneC_DbConnection->setActive(true);
     return $pid;
 }
Example #13
0
 /**
  * Initializes the command object.
  * This method is invoked after a command object is created and initialized with configurations.
  * You may override this method to further customize the command before it executes.
  * @since 1.1.6
  */
 public function init()
 {
     if (null === Yii::app()->db) {
         throw new CException('An active "db" connection is required to run this command.');
     }
     $this->dbConnection = Yii::app()->db;
     $this->dbSchema = $this->dbConnection->getSchema();
     $this->tableNames = array_diff($this->dbSchema->tableNames, (array) $this->ignoreTableNames, (array) $this->systemTableNames);
 }
Example #14
0
 /**
  * gets the list of left and right boundaries for any given owner objects.
  *
  * @param CDbConnection $db
  * @param string        $tree_table
  * @param string        $obj_id
  *
  * @returns array of array(left, right)
  */
 protected function _treeLimits($db, $tree_table, $obj_id)
 {
     $query = 'SELECT ' . $this->leftAttribute . ',' . $this->rightAttribute . ' FROM ' . $tree_table . ' WHERE ' . $this->idAttribute . ' = ' . $db->quoteValue($obj_id);
     $res = $db->createCommand($query)->query();
     $result = array();
     foreach ($res as $r) {
         $result[] = array($r[$this->leftAttribute], $r[$this->rightAttribute]);
     }
     return $result;
 }
Example #15
0
 public static function saveAdToRt($adID)
 {
     $ad = Ad::model()->findByPk($adID);
     $connection = new CDbConnection(Yii::app()->params['sphinx']['dsn'], Yii::app()->params['sphinx']['user'], Yii::app()->params['sphinx']['pass']);
     $connection->active = true;
     $sphinxIndexes = Yii::app()->params['sphinx']['indexes'];
     $rt = $sphinxIndexes['rt'][0];
     $sql = "INSERT INTO {$rt} (id, title, description, added)\n                VALUES (:id, :title, :description, :added)";
     $command = $connection->createCommand($sql);
     $command->execute(array(':id' => $ad->id, ':title' => $ad->title, ':description' => $ad->description, ':added' => time()));
 }
Example #16
0
 /**
  * 
  * @param CDbConnection $db
  * @param string $key
  * @param string $query
  */
 public static function fetchWithKey($db, $key = '', $query)
 {
     $data = array();
     $list = $db->createCommand($query)->queryAll();
     if (!empty($list)) {
         foreach ($list as $item) {
             $data[$item[$key]] = $item;
         }
     }
     return $data;
 }
Example #17
0
 /**
  * Creates the session DB table.
  * @param CDbConnection $db the database connection
  * @param string $tableName the name of the table to be created
  */
 protected function createSessionTable($db, $tableName)
 {
     $driver = $db->getDriverName();
     if ($driver === 'mysql') {
         $blob = 'LONGBLOB';
     } elseif ($driver === 'pgsql') {
         $blob = 'BYTEA';
     } else {
         $blob = 'BLOB';
     }
     $db->createCommand()->createTable($tableName, array('id' => 'CHAR(255) PRIMARY KEY', 'expire' => 'integer', 'user_id' => 'integer', 'data' => $blob));
 }
Example #18
0
 /**
  * Search via sphinx (mysql client)
  */
 protected function sphinxSearch($phrase)
 {
     $connection = new CDbConnection(Yii::app()->params['sphinx']['dsn'], Yii::app()->params['sphinx']['user'], Yii::app()->params['sphinx']['pass']);
     $connection->active = true;
     $words = mb_split('[^\\w]+', $phrase);
     $words = array_filter($words);
     // unset empty elements
     $search = implode('|', $words);
     $sphinxIndexes = SphinxService::implodeIndexes();
     $sql = "SELECT * FROM {$sphinxIndexes} WHERE MATCH('{$search}') LIMIT 10000";
     $command = $connection->createCommand($sql);
     return $command->queryColumn();
 }
Example #19
0
 public function testCreateDb()
 {
     $step1 = new Step1();
     $step1->setAttributes($this->data, false);
     $this->assertTrue($step1->createDb());
     $conn_string = 'mysql:host=' . $step1->db_host . ';dbname=' . $step1->db_name;
     $con = new CDbConnection($conn_string, $step1->db_login, $step1->db_pass);
     try {
         $con->init();
     } catch (Exception $e) {
         $this->assert('Db was not created');
     }
     $con->createCommand('DROP DATABASE IF EXISTS ' . $con->quoteTableName($this->data['db_name']))->execute();
 }
 public function actionIndex()
 {
     $fisrt_day_of_month = date("Y-m-01");
     $last_day_of_month = date("Y-m-30");
     $connection = new CDbConnection("mysql:host=localhost;dbname=shop", "mysql", "mysql");
     $sql = "SELECT COUNT(*),`productid` FROM `order`   WHERE `time` BETWEEN STR_TO_DATE('{$fisrt_day_of_month}', '%Y-%m-%d')  AND STR_TO_DATE('{$last_day_of_month}', '%Y-%m-%d') GROUP BY `productid`";
     $command = $connection->createCommand($sql);
     $order = $command->queryAll();
     $sql2 = "SELECT * FROM `product`";
     $command2 = $connection->createCommand($sql2);
     $products = $command2->queryAll();
     // BETWEEN "2008.11.01"  AND  "2009.10.12"
     $this->render('index', ['orders' => $order, 'products' => $products]);
 }
Example #21
0
 /**
  * Creates the DB table for storing log messages.
  * @param CDbConnection $db the database connection
  * @param string $tableName the name of the table to be created
  */
 protected function createLogTable($db, $tableName)
 {
     $driver = $db->getDriverName();
     if ($driver === 'mysql') {
         $logID = 'id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY';
     } else {
         if ($driver === 'pgsql') {
             $logID = 'id SERIAL PRIMARY KEY';
         } else {
             $logID = 'id INTEGER NOT NULL PRIMARY KEY';
         }
     }
     $sql = "\r\nCREATE TABLE {$tableName}\r\n(\r\n\t{$logID},\r\n\tlevel VARCHAR(128),\r\n\tcategory VARCHAR(128),\r\n\tlogtime INTEGER,\r\n\tmessage TEXT\r\n)";
     $db->createCommand($sql)->execute();
 }
Example #22
0
 public function checkUser()
 {
     if ($this->hasErrors('db_exp_sql_host') || $this->hasErrors('db_exp_sql_dbname') || $this->hasErrors('db_exp_sql_login') || $this->hasErrors('db_exp_sql_password') || $this->hasErrors('db_exp_sql_port')) {
         return false;
     }
     try {
         $connection = new CDbConnection('mysql:host=' . $this->db_exp_sql_host, $this->db_exp_sql_login, $this->db_exp_sql_password);
         $res = $connection->setActive(true);
         $sql = "CREATE DATABASE IF NOT EXISTS `{$this->db_exp_sql_dbname}` CHARACTER SET UTF8";
         $res = $connection->createCommand($sql)->query();
     } catch (CDbException $e) {
         $this->addError('db_exp_sql_login', $e->getMessage());
         return false;
     }
     return true;
 }
Example #23
0
 public function testTransactions()
 {
     $transaction = $this->db->beginTransaction();
     $schema = $this->db->schema;
     $builder = $schema->commandBuilder;
     $table = $schema->getTable('posts');
     // Working transaction
     try {
         $builder->createInsertCommand($table, array('title' => 'working transaction test post 1', 'create_time' => '2009-01-01', 'author_id' => 1, 'content' => 'test content'))->execute();
         $builder->createInsertCommand($table, array('title' => 'working transaction test post 2', 'create_time' => '2009-01-01', 'author_id' => 1, 'content' => 'test content'))->execute();
         $transaction->commit();
     } catch (Exception $e) {
         $transaction->rollback();
     }
     $n = $builder->createCountCommand($table, new CDbCriteria(array('condition' => "title LIKE 'working transaction%'")))->queryScalar();
     $this->assertEquals(2, $n);
     // Failing Transaction
     $transaction = $this->db->beginTransaction();
     try {
         $builder->createInsertCommand($table, array('title' => 'failed transaction test post 1', 'create_time' => '2009-01-01', 'author_id' => 1, 'content' => 'test content'))->execute();
         $builder->createInsertCommand($table, array('id' => 1, 'title' => 'failed transaction test post 2', 'create_time' => '2009-01-01', 'author_id' => 1, 'content' => 'test content'))->execute();
         $transaction->commit();
     } catch (Exception $e) {
         $transaction->rollback();
     }
     $n = $builder->createCountCommand($table, new CDbCriteria(array('condition' => "title LIKE 'failed transaction%'")))->queryScalar();
     $this->assertEquals(0, $n);
 }
 /**
  * Function to install the LimeSurvey database from the command line
  * Call it like:
  *    php index.php installer cmd_install_db
  * from your command line
  * The function assumes that /config/database.php is already configured and the database controller
  * is added in autoload.php in the libraries array
  *
  */
 function cmd_install_db()
 {
     if (php_sapi_name() != 'cli') {
         die('This function can only be run from the command line');
     }
     $sDbType = $this->db->dbdriver;
     if (!in_array($sDbType, InstallerConfigForm::supported_db_types)) {
         throw new Exception(sprintf('Unkown database type "%s".', $sDbType));
     }
     $aDbConfig = array('sDatabaseName' => $this->db->database, 'sDatabaseLocation' => $this->db->hostname, 'sDatabaseUser' => $this->db->username, 'sDatabasePwd' => $this->db->password, 'sDatabaseType' => $sDbType, 'sDatabasePort' => $this->db->port);
     $sDbPrefix = $this->db->dbprefix;
     self::_dbConnect($aDbConfig);
     $aErrors = self::_setup_tables(Yii::app()->getConfig('rootdir') . '/installer/sql/create-' . $sFileName . '.sql', $aDbConfig, $sDbPrefix);
     foreach ($aErrors as $sError) {
         echo $sError . PHP_EOL;
     }
     $sPasswordHash = hash('sha256', Yii::app()->getConfig('defaultpass'));
     try {
         $this->connection->createCommand()->insert("{{settings_global}}", array('stg_name' => 'SessionName', 'stg_value' => 'ls' . self::_getRandomID() . self::_getRandomID() . self::_getRandomID()));
         $this->connection->createCommand()->insert('{{users}}', array('users_name' => Yii::app()->getConfig('defaultuser'), 'password' => $sPasswordHash, 'full_name' => Yii::app()->getConfig('siteadminname'), 'parent_id' => 0, 'lang' => 'auto', 'email' => Yii::app()->getConfig('siteadminemail'), 'create_survey' => 1, 'participant_panel' => 1, 'create_user' => 1, 'delete_user' => 1, 'superadmin' => 1, 'configurator' => 1, 'manage_template' => 1, 'manage_label' => 1));
     } catch (Exception $e) {
         $aErrors[] = $e;
     }
     if (count($aErrors) > 0) {
         echo "There were errors during the installation.\n";
         foreach ($aErrors as $sError) {
             echo "Error: " . $sError . "\n";
         }
     } else {
         echo "Installation was successful.\n";
     }
 }
Example #25
0
 /**
  * 打开或关闭数据库连接
  *
  * @param boolean $value whether to open or close DB connection
  * @throws CException if connection fails
  */
 public function setActive($value)
 {
     if ($value != $this->getActive() && $value) {
         $this->setAttribute(PDO::ATTR_TIMEOUT, $this->timeout);
     }
     parent::setActive($value);
 }
Example #26
0
 /**
  * Контроль предметов
  *
  * @params array $itemsIds
  *
  * @return array
  */
 public function getItemsControl(array $itemsIds)
 {
     if (!$itemsIds) {
         return array();
     }
     $res = AllItems::model()->findAllByAttributes(array('item_id' => $itemsIds));
     $itemNames = array();
     foreach ($res as $row) {
         $itemNames[$row->getPrimaryKey()] = $row;
     }
     unset($res);
     $res = $this->_db->createCommand()->select("Max(items.count) AS maxCountItems,Count(items.count) AS countItems,items.object_id,items.owner_id,items.item_id,items.count,items.enchant_level,items.loc,items.loc_data,characters.account_name,characters.char_name,characters.x,characters.y,characters.z,characters.obj_Id AS char_id,characters.sex,characters.karma,\r\n                characters.pvpkills,characters.pkkills,characters.clanid AS clan_id,characters.title,characters.accesslevel AS access_level,characters.online,characters.onlinetime,character_subclasses.class_id AS base_class,character_subclasses.level,character_subclasses.exp,\r\n                character_subclasses.sp,character_subclasses.curHp,character_subclasses.curMp,character_subclasses.curCp,character_subclasses.maxHp,character_subclasses.maxMp,character_subclasses.maxCp,clan_data.clan_level,clan_data.hasCastle,clan_data.hasFortress AS hasFort,\r\n                clan_data.crest AS clan_crest,clan_data.reputation_score,clan_subpledges.name AS clan_name")->leftJoin('characters', 'items.owner_id = characters.obj_Id')->leftJoin('character_subclasses', 'characters.obj_Id = character_subclasses.char_obj_id AND character_subclasses.isBase = 1')->leftJoin('clan_data', 'characters.clanid = clan_data.clan_id')->leftJoin('clan_subpledges', 'clan_data.clan_id = clan_subpledges.clan_id AND clan_subpledges.type = 0')->where(array('in', 'item_id', $itemsIds))->group('items.owner_id, items.item_id')->from('items')->queryAll();
     $characters = array();
     foreach ($res as $item) {
         if (!isset($characters[$item['item_id']]['maxTotalItems'])) {
             $characters[$item['item_id']]['maxTotalItems'] = 0;
         }
         $characters[$item['item_id']]['itemInfo'] = $itemNames[$item['item_id']];
         $characters[$item['item_id']]['characters'][] = $item;
         $characters[$item['item_id']]['maxTotalItems'] += $item['maxCountItems'];
         $characters[$item['item_id']]['totalItems'] = count($characters[$item['item_id']]['characters']);
     }
     foreach (array_diff_key($itemNames, $characters) as $item) {
         $characters[$item->item_id]['itemInfo'] = $item;
         $characters[$item->item_id]['characters'] = array();
         $characters[$item->item_id]['maxTotalItems'] = 0;
         $characters[$item->item_id]['totalItems'] = 0;
     }
     return $characters;
 }
 /**
  * @inheritdoc
  */
 protected function open()
 {
     parent::open();
     if ($this->hasEventHandler('onAfterOpen')) {
         $this->onAfterOpen(new \CEvent($this));
     }
 }
Example #28
0
 /**
  *
  */
 public function init()
 {
     try {
         parent::init();
     } catch (\CDbException $e) {
         Craft::log($e->getMessage(), LogLevel::Error);
         $missingPdo = false;
         // TODO: Multi-db driver check.
         if (!extension_loaded('pdo')) {
             $missingPdo = true;
             $messages[] = Craft::t('Craft requires the PDO extension to operate.');
         }
         if (!extension_loaded('pdo_mysql')) {
             $missingPdo = true;
             $messages[] = Craft::t('Craft requires the PDO_MYSQL driver to operate.');
         }
         if (!$missingPdo) {
             Craft::log($e->getMessage(), LogLevel::Error);
             $messages[] = Craft::t('There is a problem connecting to the database with the credentials supplied in your db config file.');
         }
     } catch (\Exception $e) {
         Craft::log($e->getMessage(), LogLevel::Error);
         $messages[] = Craft::t('There is a problem connecting to the database with the credentials supplied in your db config file.');
     }
     if (!empty($messages)) {
         throw new DbConnectException(Craft::t('Database configuration errors: {errors}', array('errors' => implode(PHP_EOL, $messages))));
     }
     $this->_isDbConnectionValid = true;
     // Now that we've validated the config and connection, set extra db logging if devMode is enabled.
     if (craft()->config->get('devMode')) {
         $this->enableProfiling = true;
         $this->enableParamLogging = true;
     }
 }
 /**
  * Executes an SQL file
  *
  * @param string $sFileName
  * @param string $sDatabasePrefix
  */
 function _executeSQLFile($sFileName, $sDatabasePrefix)
 {
     $aMessages = array();
     $sCommand = '';
     if (!is_readable($sFileName)) {
         return false;
     } else {
         $aLines = file($sFileName);
     }
     foreach ($aLines as $sLine) {
         $sLine = rtrim($sLine);
         $iLineLength = strlen($sLine);
         if ($iLineLength && $sLine[0] != '#' && substr($sLine, 0, 2) != '--') {
             if (substr($sLine, $iLineLength - 1, 1) == ';') {
                 $line = substr($sLine, 0, $iLineLength - 1);
                 $sCommand .= $sLine;
                 $sCommand = str_replace('prefix_', $sDatabasePrefix, $sCommand);
                 // Table prefixes
                 try {
                     $this->connection->createCommand($sCommand)->execute();
                 } catch (Exception $e) {
                     $aMessages[] = "Executing: " . $sCommand . " failed! Reason: " . $e;
                 }
                 $sCommand = '';
             } else {
                 $sCommand .= $sLine;
             }
         }
     }
     return $aMessages;
 }
Example #30
0
 public function testResetSequence()
 {
     // we're assuming in this test that COciSchema::resetSequence() is not implemented
     // empty CDbSchema::resetSequence() being used
     $max = $this->db->createCommand('SELECT MAX("id") FROM "users"')->queryScalar();
     $this->db->createCommand('DELETE FROM "users"')->execute();
     $this->db->createCommand('INSERT INTO "users" ("username", "password", "email") VALUES (\'user4\', \'pass4\', \'email4\')')->execute();
     $max2 = $this->db->createCommand('SELECT MAX("id") FROM "users"')->queryScalar();
     $this->assertEquals($max + 1, $max2);
     $userTable = $this->db->schema->getTable('users');
     $this->db->createCommand('DELETE FROM "users"')->execute();
     $this->db->schema->resetSequence($userTable);
     $this->db->createCommand('INSERT INTO "users" ("username", "password", "email") VALUES (\'user4\', \'pass4\', \'email4\')')->execute();
     $max = $this->db->createCommand('SELECT MAX("id") FROM "users"')->queryScalar();
     $this->assertEquals(6, $max);
     $this->db->createCommand('INSERT INTO "users" ("username", "password", "email") VALUES (\'user4\', \'pass4\', \'email4\')')->execute();
     $max = $this->db->createCommand('SELECT MAX("id") FROM "users"')->queryScalar();
     $this->assertEquals(7, $max);
     $this->db->createCommand('DELETE FROM "users"')->execute();
     $this->db->schema->resetSequence($userTable, 10);
     $this->db->createCommand('INSERT INTO "users" ("username", "password", "email") VALUES (\'user4\', \'pass4\', \'email4\')')->execute();
     $max = $this->db->createCommand('SELECT MAX("id") FROM "users"')->queryScalar();
     $this->assertEquals(8, $max);
     $this->db->createCommand('INSERT INTO "users" ("username", "password", "email") VALUES (\'user4\', \'pass4\', \'email4\')')->execute();
     $max = $this->db->createCommand('SELECT MAX("id") FROM "users"')->queryScalar();
     $this->assertEquals(9, $max);
 }