Exemple #1
0
 /**
  * REPLACE INTO
  *
  * @param Model $obj
  * @param bool $saveAllColumns
  * @return null
  */
 public function saveByReplace(Model $obj, $saveAllColumns = false)
 {
     $rtn = null;
     $data = $obj->getDataArray();
     $modified = $saveAllColumns ? array_keys($data) : $obj->getModified();
     $cols = array();
     $values = array();
     $qParams = array();
     foreach ($modified as $key) {
         $cols[] = '`' . $key . '`';
         $values[] = ':' . $key;
         $qParams[':' . $key] = $data[$key];
     }
     if (count($cols)) {
         $colString = implode(', ', $cols);
         $valString = implode(', ', $values);
         $queryString = 'REPLACE INTO ' . $this->tableName . ' (' . $colString . ') VALUES (' . $valString . ')';
         $query = Database::getConnection('write')->prepare($queryString);
         if ($query->execute($qParams)) {
             $newId = !empty($data[$this->primaryKey]) ? $data[$this->primaryKey] : Database::getConnection('write')->lastInsertId();
             $rtn = $this->getByPrimaryKey($newId, 'write');
         }
     }
     return $rtn;
 }
 public function setUp()
 {
     \b8\Database::setDetails($this->_name, $this->_user, $this->_pass);
     \b8\Database::setWriteServers(array($this->_host));
     $this->_db = \b8\Database::getConnection('write');
     $this->_db->query('DROP TABLE IF EXISTS tres');
     $this->_db->query('DROP TABLE IF EXISTS dos');
     $this->_db->query('DROP TABLE IF EXISTS uno');
 }
Exemple #3
0
 public function execute(InputInterface $input, OutputInterface $output)
 {
     unset($input, $output);
     $connection = Database::getConnection();
     $namespaces = Config::getInstance()->get('app.namespaces');
     $paths = Config::getInstance()->get('Octo.paths.namespaces');
     $gen = new Database\CodeGenerator($connection, $namespaces, $paths, true);
     $gen->generateModels();
     $gen->generateStores();
 }
Exemple #4
0
 /**
  * Gets the total number of errors for a given build.
  * @param $buildId
  * @param string $since date string
  * @return array
  */
 public function getErrorTotalForBuild($buildId)
 {
     $query = 'SELECT COUNT(*) AS total FROM build_error
                 WHERE build_id = :build';
     $stmt = Database::getConnection('read')->prepare($query);
     $stmt->bindValue(':build', $buildId, \PDO::PARAM_INT);
     if ($stmt->execute()) {
         $res = $stmt->fetch(\PDO::FETCH_ASSOC);
         return $res['total'];
     } else {
         return array();
     }
 }
 public static function setUpBeforeClass()
 {
     Database::setDetails('b8_test_' . getenv('PHPCI_BUILD'), 'b8_test', 'b8_test');
     Database::setWriteServers(array('localhost'));
     Database::setReadServers(array('localhost'));
     Registry::getInstance()->set('b8.app.namespace', 'Generation');
     self::$_db = Database::getConnection('write');
     self::$_db->query('DROP TABLE IF EXISTS tres');
     self::$_db->query('DROP TABLE IF EXISTS dos');
     self::$_db->query('DROP TABLE IF EXISTS uno');
     self::$_base = dirname(__FILE__) . '/data/generation/';
     $gen = new Generator(self::$_db, 'Test', self::$_base . 'models/');
     $gen->generate();
 }
Exemple #6
0
 public function getPermissionsArray(User $user)
 {
     $pdo = Database::getConnection('read');
     $stmt = $pdo->prepare('SELECT uri, can_access FROM permission WHERE user_id = :userId');
     $stmt->bindValue(':userId', $user->getId());
     if ($stmt->execute()) {
         $perms = $stmt->fetchAll(Database::FETCH_ASSOC);
         $rtn = [];
         foreach ($perms as $perm) {
             $rtn[$perm['uri']] = (bool) $perm['can_access'];
         }
         return $rtn;
     }
     return [];
 }
Exemple #7
0
 public function getByEmail($value, $useConnection = 'read')
 {
     if (is_null($value)) {
         throw new HttpException('Value passed to ' . __FUNCTION__ . ' cannot be null.');
     }
     $query = 'SELECT * FROM `user` WHERE `email` = :email LIMIT 1';
     $stmt = Database::getConnection($useConnection)->prepare($query);
     $stmt->bindValue(':email', $value);
     if ($stmt->execute()) {
         if ($data = $stmt->fetch(\PDO::FETCH_ASSOC)) {
             return new User($data);
         }
     }
     return null;
 }
Exemple #8
0
 public function search($query)
 {
     $query = 'SELECT * FROM `user` WHERE `name` LIKE \'%' . $query . '%\'';
     $stmt = Database::getConnection('read')->prepare($query);
     if ($stmt->execute()) {
         $res = $stmt->fetchAll(\PDO::FETCH_ASSOC);
         $map = function ($item) {
             return new User($item);
         };
         $rtn = array_map($map, $res);
         return $rtn;
     } else {
         return [];
     }
 }
Exemple #9
0
 public function runMigration(array $migration)
 {
     $pdo = Database::getConnection('write');
     $pdo->beginTransaction();
     try {
         $pdo->exec('SET foreign_key_checks = 0');
         foreach ($migration['queries'] as $query) {
             $pdo->exec($query);
         }
         $pdo->exec('SET foreign_key_checks = 1');
         $pdo->commit();
     } catch (\Exception $ex) {
         $pdo->rollBack();
         throw $ex;
     }
 }
Exemple #10
0
 public function getCount()
 {
     $select = $this->select;
     $this->select = 'COUNT(*) AS total';
     $query = $this->buildBaseQuery();
     $this->select = $select;
     $stmt = $this->database->prepare($query);
     foreach ($this->params as $key => $value) {
         $stmt->bindValue($key, $value);
     }
     if ($stmt->execute()) {
         $res = $stmt->fetch(Database::FETCH_ASSOC);
         return (int) $res['total'];
     }
     return 0;
 }
Exemple #11
0
 public function updateSearchIndex($class, $contentId, $content)
 {
     $database = Database::getConnection('write');
     $stmt = $database->prepare('DELETE FROM search_index WHERE model = :model AND content_id = :id');
     $stmt->bindValue(':model', $class);
     $stmt->bindValue(':id', $contentId);
     $stmt->execute();
     $stmt = $database->prepare('INSERT INTO search_index (word, model, content_id, instances) VALUES (:word, :model, :id, :count)');
     $stmt->bindValue(':model', $class);
     $stmt->bindValue(':id', $contentId);
     foreach ($this->extractWords($content) as $word => $count) {
         $stmt->bindValue(':word', $word);
         $stmt->bindValue(':count', $count);
         $stmt->execute();
     }
 }
Exemple #12
0
 /**
  * Get a list of all projects, ordered by their title.
  * @return array
  */
 public function getAll()
 {
     $query = 'SELECT * FROM `project` ORDER BY `title` ASC';
     $stmt = Database::getConnection('read')->prepare($query);
     if ($stmt->execute()) {
         $res = $stmt->fetchAll(\PDO::FETCH_ASSOC);
         $map = function ($item) {
             return new Project($item);
         };
         $rtn = array_map($map, $res);
         $count = count($rtn);
         return array('items' => $rtn, 'count' => $count);
     } else {
         return array('items' => array(), 'count' => 0);
     }
 }
Exemple #13
0
 public function getByScopeKey($scope, $key)
 {
     $query = 'SELECT setting.* FROM setting WHERE scope = :scope AND `key` = :key LIMIT 1';
     $stmt = Database::getConnection('read')->prepare($query);
     $stmt->bindParam(':scope', $scope);
     $stmt->bindParam(':key', $key);
     if ($stmt->execute()) {
         $res = $stmt->fetch(\PDO::FETCH_ASSOC);
         if ($res) {
             return new Setting($res);
         } else {
             return null;
         }
     } else {
         return null;
     }
 }
Exemple #14
0
 /**
  * Only used by an upgrade migration to move errors from build_meta to build_error
  * @param $start
  * @param $limit
  * @return array
  */
 public function getErrorsForUpgrade($limit)
 {
     $query = 'SELECT * FROM build_meta
                 WHERE meta_key IN (\'phpmd-data\', \'phpcs-data\', \'phpdoccheck-data\')
                 ORDER BY id ASC LIMIT :limit';
     $stmt = Database::getConnection('read')->prepare($query);
     $stmt->bindValue(':limit', $limit, \PDO::PARAM_INT);
     if ($stmt->execute()) {
         $res = $stmt->fetchAll(\PDO::FETCH_ASSOC);
         $map = function ($item) {
             return new BuildMeta($item);
         };
         $rtn = array_map($map, $res);
         return $rtn;
     } else {
         return array();
     }
 }
Exemple #15
0
 public function search($query)
 {
     $query = 'SELECT * FROM contact
                 WHERE first_name LIKE \'%' . $query . '%\'
                     OR last_name LIKE \'%' . $query . '%\'
                     OR company LIKE \'%' . $query . '%\' ';
     $stmt = Database::getConnection('read')->prepare($query);
     if ($stmt->execute()) {
         $res = $stmt->fetchAll(\PDO::FETCH_ASSOC);
         $map = function ($item) {
             return new Contact($item);
         };
         $rtn = array_map($map, $res);
         return $rtn;
     } else {
         return [];
     }
 }
Exemple #16
0
 /**
  * Get multiple User by Name.
  * @return array
  */
 public function getByName($value, $limit = 1000, $useConnection = 'read')
 {
     if (is_null($value)) {
         throw new HttpException('Value passed to ' . __FUNCTION__ . ' cannot be null.');
     }
     $query = 'SELECT * FROM `user` WHERE `name` = :name LIMIT :limit';
     $stmt = Database::getConnection($useConnection)->prepare($query);
     $stmt->bindValue(':name', $value);
     $stmt->bindValue(':limit', (int) $limit, \PDO::PARAM_INT);
     if ($stmt->execute()) {
         $res = $stmt->fetchAll(\PDO::FETCH_ASSOC);
         $map = function ($item) {
             return new User($item);
         };
         $rtn = array_map($map, $res);
         $count = count($rtn);
         return array('items' => $rtn, 'count' => $count);
     } else {
         return array('items' => array(), 'count' => 0);
     }
 }
Exemple #17
0
 /**
  * @param Builder $phpci
  * @param Build   $build
  * @param array   $options
  */
 public function __construct(Builder $phpci, Build $build, array $options = array())
 {
     $this->phpci = $phpci;
     $this->build = $build;
     $this->queries = $options;
     $config = \b8\Database::getConnection('write')->getDetails();
     $this->host = defined('PHPCI_DB_HOST') ? PHPCI_DB_HOST : null;
     $this->user = $config['user'];
     $this->pass = $config['pass'];
     $buildSettings = $phpci->getConfig('build_settings');
     if (!isset($buildSettings['mysql'])) {
         return;
     }
     if (!empty($buildSettings['mysql']['host'])) {
         $this->host = $this->phpci->interpolate($buildSettings['mysql']['host']);
     }
     if (!empty($buildSettings['mysql']['user'])) {
         $this->user = $this->phpci->interpolate($buildSettings['mysql']['user']);
     }
     if (array_key_exists('pass', $buildSettings['mysql'])) {
         $this->pass = $buildSettings['mysql']['pass'];
     }
 }
Exemple #18
0
 /**
  * Get a list of errors for a given build, since a given time.
  * @param $buildId
  * @param string $since date string
  * @return array
  */
 public function getErrorsForBuild($buildId, $since = null)
 {
     $query = 'SELECT * FROM build_error
                 WHERE build_id = :build';
     if (!is_null($since)) {
         $query .= ' AND created_date > :since';
     }
     $query .= ' LIMIT 15000';
     $stmt = Database::getConnection('read')->prepare($query);
     $stmt->bindValue(':build', $buildId, \PDO::PARAM_INT);
     if (!is_null($since)) {
         $stmt->bindValue(':since', $since);
     }
     if ($stmt->execute()) {
         $res = $stmt->fetchAll(\PDO::FETCH_ASSOC);
         $map = function ($item) {
             return new BuildError($item);
         };
         $rtn = array_map($map, $res);
         return $rtn;
     } else {
         return array();
     }
 }
Exemple #19
0
 /**
  * Get an array of Project by Title.
  * @param mixed $value.
  * @param int $limit
  * @param string $useConnection Connection to use (read / write)
  * @throws \b8\Exception\HttpException
  * @return \PHPCI\Model\Project[]
  */
 public function getByTitle($value, $limit = null, $useConnection = 'read')
 {
     if (is_null($value)) {
         throw new HttpException('Value passed to ' . __FUNCTION__ . ' cannot be null.');
     }
     $add = '';
     if ($limit) {
         $add .= ' LIMIT ' . $limit;
     }
     $count = null;
     $query = 'SELECT * FROM `project` WHERE `title` = :title' . $add;
     $stmt = Database::getConnection($useConnection)->prepare($query);
     $stmt->bindValue(':title', $value);
     if ($stmt->execute()) {
         $res = $stmt->fetchAll(\PDO::FETCH_ASSOC);
         $map = function ($item) {
             return new Project($item);
         };
         $rtn = array_map($map, $res);
         return array('items' => $rtn, 'count' => $count);
     } else {
         return array('items' => array(), 'count' => 0);
     }
 }
Exemple #20
0
 /**
  * Set a metadata value for a given project and build ID.
  * @param $projectId
  * @param $buildId
  * @param $key
  * @param $value
  * @return bool
  */
 public function setMeta($projectId, $buildId, $key, $value)
 {
     $cols = '`project_id`, `build_id`, `meta_key`, `meta_value`';
     $query = 'REPLACE INTO build_meta (' . $cols . ') VALUES (:projectId, :buildId, :key, :value)';
     $stmt = Database::getConnection('read')->prepare($query);
     $stmt->bindValue(':key', $key, \PDO::PARAM_STR);
     $stmt->bindValue(':projectId', (int) $projectId, \PDO::PARAM_INT);
     $stmt->bindValue(':buildId', (int) $buildId, \PDO::PARAM_INT);
     $stmt->bindValue(':value', $value, \PDO::PARAM_STR);
     if ($stmt->execute()) {
         return true;
     } else {
         return false;
     }
 }
Exemple #21
0
 /**
  * Generates Model and Store classes by reading database meta data.
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $gen = new CodeGenerator(Database::getConnection(), array('default' => 'PHPCI'), array('default' => PHPCI_DIR), false);
     $gen->generateModels();
     $gen->generateStores();
 }
Exemple #22
0
 /**
  * Start the worker.
  */
 public function startWorker()
 {
     $this->pheanstalk->watch($this->queue);
     $this->pheanstalk->ignore('default');
     $buildStore = Factory::getStore('Build');
     while ($this->run) {
         // Get a job from the queue:
         $job = $this->pheanstalk->reserve();
         $this->checkJobLimit();
         // Get the job data and run the job:
         $jobData = json_decode($job->getData(), true);
         if (!$this->verifyJob($job, $jobData)) {
             continue;
         }
         $this->logger->addInfo('Received build #' . $jobData['build_id'] . ' from Beanstalkd');
         // If the job comes with config data, reset our config and database connections
         // and then make sure we kill the worker afterwards:
         if (!empty($jobData['config'])) {
             $this->logger->addDebug('Using job-specific config.');
             $currentConfig = Config::getInstance()->getArray();
             $config = new Config($jobData['config']);
             Database::reset($config);
         }
         try {
             $build = BuildFactory::getBuildById($jobData['build_id']);
         } catch (\Exception $ex) {
             $this->logger->addWarning('Build #' . $jobData['build_id'] . ' does not exist in the database.');
             $this->pheanstalk->delete($job);
         }
         try {
             // Logging relevant to this build should be stored
             // against the build itself.
             $buildDbLog = new BuildDBLogHandler($build, Logger::INFO);
             $this->logger->pushHandler($buildDbLog);
             $builder = new Builder($build, $this->logger);
             $builder->execute();
             // After execution we no longer want to record the information
             // back to this specific build so the handler should be removed.
             $this->logger->popHandler($buildDbLog);
         } catch (\PDOException $ex) {
             // If we've caught a PDO Exception, it is probably not the fault of the build, but of a failed
             // connection or similar. Release the job and kill the worker.
             $this->run = false;
             $this->pheanstalk->release($job);
         } catch (\Exception $ex) {
             $build->setStatus(Build::STATUS_FAILED);
             $build->setFinished(new \DateTime());
             $build->setLog($build->getLog() . PHP_EOL . PHP_EOL . $ex->getMessage());
             $buildStore->save($build);
             $build->sendStatusPostback();
         }
         // Reset the config back to how it was prior to running this job:
         if (!empty($currentConfig)) {
             $config = new Config($currentConfig);
             Database::reset($config);
         }
         // Delete the job when we're done:
         $this->pheanstalk->delete($job);
     }
 }
 /**
  * @expectedException \Exception
  */
 public function testConnectionFailure()
 {
     \b8\Database::setDetails('non_existant', 'invalid_user', 'incorrect_password');
     \b8\Database::setReadServers(array('localhost'));
     \b8\Database::getConnection('read');
 }
Exemple #24
0
 public function delete(Model $obj)
 {
     if (!isset($this->primaryKey)) {
         throw new HttpException\BadRequestException('Delete not implemented for this store.');
     }
     if (!$obj instanceof $this->modelName) {
         throw new HttpException\BadRequestException(get_class($obj) . ' is an invalid model type for this store.');
     }
     $data = $obj->getDataArray();
     $stmt = Database::getConnection('write')->prepare('DELETE FROM ' . $this->tableName . ' WHERE ' . $this->primaryKey . ' = :primaryKey');
     $stmt->bindValue(':primaryKey', $data[$this->primaryKey]);
     $stmt->execute();
     $this->setCache($data[$this->primaryKey], null);
     return true;
 }