public function test_migration_initializes_migration_table() { // because Migration was instantiated in setup, the version table should exist $metadata = new Metadata($this->adapter); $tableNames = $metadata->getTableNames(); $this->assertContains(MigrationVersion::TABLE_NAME, $tableNames); }
/** * Process the command * * @return integer */ public function processCommandTask() { // output message $this->console->writeTaskLine('task_crud_check_table_name', array($this->console->colorize($this->params->paramTableName, Color::GREEN))); /** @var Adapter $dbAdapter */ $dbAdapter = $this->params->dbAdapter; // get Metadata for database adapter $metaData = new Metadata($dbAdapter); // fetch database $database = $dbAdapter->getCurrentSchema(); // fetch table object try { $table = $metaData->getTable($this->params->paramTableName); } catch (Exception $e) { $this->console->writeFailLine('task_crud_check_table_not_exists', array($this->console->colorize($this->params->paramTableName, Color::GREEN), $this->console->colorize($database, Color::GREEN))); return 1; } $tableObjects = array(); /** @var TableObject $tableObject */ foreach ($metaData->getTables() as $tableObject) { $tableObjects[$tableObject->getName()] = $tableObject; } $this->params->currentTableObjects = $tableObjects; return 0; }
/** * (non-PHPdoc) * @see \ZfcDB\Mapper\MapperInterface::save() */ public function save($object) { $metadata = new Metadata($this->getDbAdapter()); $constraints = $metadata->getConstraints($this->tableName); $datas = $object; if (!is_array($datas)) { $datas = $this->getHydrator()->extract($object); } $primaries = array(); if (count($constraints)) { foreach ($constraints as $constraint) { if ($constraint->getType() == "PRIMARY KEY") { $primaries = $constraint->getColumns(); } } } $edit = true; if (count($primaries)) { foreach ($primaries as $primarie) { if (empty($datas[$primarie])) { $edit = false; break; } } } $this->getEventManager()->trigger(__FUNCTION__, $this, array('entity' => $object)); if ($edit) { $this->update($datas, array_intersect_key($datas, array_flip($primaries))); } else { $this->insert($datas); } $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array('entity' => $object)); return $this; }
/** * @param Adapter $adapter * @param null $options * @param bool $autoLoad */ public function __construct(Adapter $adapter, $options = null, $autoLoad = true) { /** @var $db Adapter */ $this->db = $adapter; self::$defaultDb = $adapter; $this->options = $options; if (isset($options['blacklist']) && !isset($options['whitelist'])) { if (is_array($options['blacklist'])) { $this->blackList = $options['blacklist']; } else { $this->blackList[] = (string) $options['blacklist']; } } elseif (isset($options['whitelist']) && !empty($options['whitelist'])) { if (is_array($options['whitelist'])) { $this->whiteList = $options['whitelist']; } else { $this->whiteList[] = (string) $options['whitelist']; } } if ($autoLoad) { $metadata = new Metadata($adapter); $tables = $metadata->getTables(); foreach ($tables as $table) { $this->addTable($table->getName()); } } }
public function getPerTimeHeader($is_admin = false) { $metadata = new Metadata($this->adapter); $header = $metadata->getColumnNames($this->table); // return ($is_admin) ? $header : array_diff($header, $this->adminFields); return $is_admin ? $header : $header; }
protected function ensureMigrationsTableExists() { $metadata = new Metadata($this->adapter); if (!in_array($this->migrationsTableName, $metadata->getTableNames())) { $schema = new Schema\Schema($this->adapter); $schema->createTable($this->migrationsTableName, ['id' => false], function ($t) { $t->string('version'); }); $schema->addIndex($this->migrationsTableName, 'version', ['unique' => true]); } }
private function getTableMeta() { if (!$this->tableMeta) { $db = $this->db; $meta = new Metadata($db); try { $meta->getTable($this->table, $this->schema); } catch (\Exception $e) { exit($e->getMessage()); } $this->tableMeta = $meta; } return $this->tableMeta; }
/** * Can the factory create an instance for the service? * * For Service manager V3 * Edit 'use' section if need: * Change: * 'use Zend\ServiceManager\AbstractFactoryInterface;' for V2 to * 'use Zend\ServiceManager\Factory\AbstractFactoryInterface;' for V3 * * @param Interop\Container\ContainerInterface $container * @param string $requestedName * @return bool */ public function canCreate(ContainerInterface $container, $requestedName) { if (!isset($this->tableNames)) { $db = $container->has('db') ? $container->get('db') : null; if (isset($db)) { $dbMetadata = new Metadata($db); $this->tableNames = $dbMetadata->getTableNames(); } else { $this->tableNames = false; } } //is there table with same name? if (is_array($this->tableNames) && in_array($requestedName, $this->tableNames, true)) { return true; } else { return false; } }
/** * Process the command * * @return integer */ public function processCommandTask() { // output message $this->console->writeTaskLine('task_crud_load_entity_class', [$this->console->colorize($this->params->paramEntityClass, Color::GREEN), $this->console->colorize($this->params->paramEntityModule, Color::GREEN)]); if (!file_exists($this->params->entityModuleDir)) { $this->console->writeFailLine('task_crud_load_entity_module_not_found', [$this->console->colorize($this->params->paramEntityModule, Color::GREEN)]); return 1; } if (!file_exists($this->params->entityFile)) { $this->console->writeFailLine('task_crud_load_entity_entity_not_found', [$this->console->colorize($this->params->paramEntityClass, Color::GREEN), $this->console->colorize($this->params->paramEntityModule, Color::GREEN)]); return 1; } require_once $this->params->entityFile; $entityClass = new FileReflection($this->params->entityFile); $this->params->loadedEntity = $entityClass->getClass(); /** @var Adapter $dbAdapter */ $dbAdapter = $this->params->dbAdapter; // get Metadata for database adapter $metaData = new Metadata($dbAdapter); // init loaded tables $loadedTables = []; /** @var TableObject $tableObject */ foreach ($metaData->getTables() as $tableObject) { $columns = []; $primaryKey = []; $foreignKeys = []; /** @var ColumnObject $columnObject */ foreach ($tableObject->getColumns() as $columnObject) { $columns[$columnObject->getName()] = $columnObject; } /** @var ConstraintObject $constraintObject */ foreach ($tableObject->getConstraints() as $constraintObject) { if ($constraintObject->isPrimaryKey()) { $primaryKey = $constraintObject; } elseif ($constraintObject->isForeignKey()) { $foreignKeys[$constraintObject->getName()] = $constraintObject; } } $loadedTables[$tableObject->getName()] = ['columns' => $columns, 'primaryKey' => $primaryKey, 'foreignKeys' => $foreignKeys]; } $this->params->loadedTables = $loadedTables; return 0; }
/** * Process the command * * @return integer */ public function processCommandTask() { /** @var Adapter $dbAdapter */ $dbAdapter = $this->params->dbAdapter; // get Metadata for database adapter $metaData = new Metadata($dbAdapter); // fetch database $database = $dbAdapter->getCurrentSchema(); // fetch tables $tables = $metaData->getTables(); // output found modules $this->console->writeTaskLine('task_crud_show_tables_found', array($this->console->colorize($database, Color::GREEN))); $this->console->writeLine(); // loop through modules foreach ($tables as $tableObject) { $this->console->writeListItemLine('task_crud_show_tables_table_name', array($this->console->colorize($tableObject->getName(), Color::GREEN))); } return 0; }
/** * @param $filter * @param $orderBy * @param $order * @param string $source * @return Paginator * @throws \Exception */ public function paginate($filter, $orderBy, $order, $source = '') { try { $metadata = new Metadata($this->adapter); if (empty($source)) { $source = $this->table; } $columns = $metadata->getColumnNames($source); $select = new Select($source); $select->order($orderBy . ' ' . $order); if (!empty($filter)) { $query = "CONCAT_WS(' '," . implode(',', $columns) . ') LIKE ?'; $where = new Where(); $where->literal($query, '%' . $filter . '%'); $select->where($where); } $paginatorAdapter = new DbSelect($select, $this->adapter); return new Paginator($paginatorAdapter); } catch (\Exception $ex) { throw $ex; } }
private function create_database() { // Try to create a database named by $post_data->database try { $createDatabse_stament = $this->adapter->createStatement('CREATE DATABASE IF NOT EXISTS `' . $this->config['database'] . '` CHARACTER SET = utf8 COLLATE = utf8_general_ci'); $rs = $createDatabse_stament->execute(); parent::__construct(new Adapter($this->config)); if ($this->adapter->getCurrentSchema() == $this->config['database']) { $this->tables = $this->getTableNames(); $local_db_config = new Config(array('db' => $this->config), true); $this->generateConfigFile($local_db_config); } } catch (\Exception $e) { throw $e; } }
protected function _insertInto($table, array $data, $columns = null) { if (!$data) { return; } if ($columns === null) { $columns = $this->_metadata->getColumnNames($table); } $insertStmt = new InsertMultiple($table); if ($columns !== null) { $insertStmt->columns($columns); } foreach ($data as $row) { $insertStmt->values($row, InsertMultiple::VALUES_MERGE); } $sql = $this->_sql->buildSqlString($insertStmt); $this->_db->query($sql, Adapter::QUERY_MODE_EXECUTE); }
/** * Função que pega a ID do registro inserido * @param array $rawState * @param object $sql * @return integer */ private function getLastInsertId(array $rawState, $sql) { if (self::$varReturnInsertId) { $table = $rawState['table']; $tableMetadata = new \Zend\Db\Metadata\Metadata($this->getAdapter($this->varConfigAdapter)); $tableInfo = $tableMetadata->getTable($table->getTable(), $table->getSchema()); if (!empty(self::$varSqlSequence)) { return $this->getAdapter($this->varConfigAdapter)->getDriver()->getConnection()->getLastGeneratedValue(self::$varSqlSequence); } else { $primaryKeyColumn = null; foreach ($tableInfo->getConstraints() as $key => $value) { if ($value->getType() == 'PRIMARY KEY') { $temp = $value->getColumns(); $primaryKeyColumn = $temp[0]; } } $select = $sql->select($rawState['table']); foreach ($rawState['columns'] as $key => $value) { if (!empty($rawState['values'][$key])) { $select->where("{$value} = '{$rawState['values'][$key]}'"); } else { $select->where("{$value} IS NULL"); } } $statement = $sql->prepareStatementForSqlObject($select); $results = $statement->execute(); $retorno = self::$resultSetPrototype->initialize($results)->toArray(); self::freeMemory(); return $retorno[0][$primaryKeyColumn]; } } }
/** * Função que retorna o post formatado de acordo com a tabela * @param array $arrayPost * @param string $table * @param string $schema * @return array */ public function fromArray(array $arrayPost, $table, $schema) { $metadata = new zendMetadata($this->getAdapter($this->varConfigAdapter)); $tableColumns = $metadata->getColumns($table, $schema); $returnPost = array(); if (count($arrayPost) > 0) { foreach ($tableColumns as $key => $value) { if (isset($arrayPost[$value->getName()]) and !empty($arrayPost[$value->getName()])) { if (trim($arrayPost[$value->getName()]) == '') { $returnPost[$value->getName()] = null; } else { $returnPost[$value->getName()] = $arrayPost[$value->getName()]; } } else { unset($arrayPost[$key]); } } } return $returnPost; }
/** * Função que gera um print dos metadados */ public function getPrintMetadata() { $metadata = new Metadata($this->getDbAdapter()); foreach ($metadata->getSchemas() as $valueSchema) { echo 'In Schema ' . $valueSchema . PHP_EOL; // get the table names $tableNames = $metadata->getTableNames($valueSchema); foreach ($tableNames as $tableName) { echo 'In Table ' . $tableName . PHP_EOL; $table = $metadata->getTable($tableName, $valueSchema); echo ' With columns: ' . PHP_EOL; foreach ($table->getColumns() as $column) { echo ' ' . $column->getName() . ' -> ' . $column->getDataType() . PHP_EOL; } echo PHP_EOL; echo ' With constraints: ' . PHP_EOL; foreach ($metadata->getConstraints($tableName, $valueSchema) as $constraint) { /** @var $constraint Zend\Db\Metadata\Object\ConstraintObject */ echo ' ' . $constraint->getName() . ' -> ' . $constraint->getType() . PHP_EOL; if (!$constraint->hasColumns()) { continue; } echo ' column: ' . implode(', ', $constraint->getColumns()); if ($constraint->isForeignKey()) { $fkCols = array(); foreach ($constraint->getReferencedColumns() as $refColumn) { $fkCols[] = $constraint->getReferencedTableName() . '.' . $refColumn; } echo ' => ' . implode(', ', $fkCols); } echo PHP_EOL; } echo '----' . PHP_EOL; } echo '-------------------------------------------' . PHP_EOL; } }
public function getPerTimeHeader($is_admin = false) { $metadata = new Metadata($this->adapter); $header = $metadata->getColumnNames('PublisherImpressionsAndSpendHourly'); return $is_admin ? $header : array_values(array_diff($header, $this->adminFields)); }
public function getUserImpressionsSpendHeadersAdmin() { $metadata = new Metadata($this->adapter); return $metadata->getColumnNames('userImpressionsSpendAdmin'); }
/** * @param Metadata $metadata * @param $tableName * @param $columnName * @return null|\Zend\Db\Metadata\Object\ConstraintObject */ protected function getConstraintForColumn(Metadata $metadata, $tableName, $columnName) { /** @var \Zend\Db\Metadata\Object\ConstraintObject $constraint */ foreach ($metadata->getConstraints($tableName) as $constraint) { foreach ($constraint->getColumns() as $column) { if ($column == $columnName) { return $constraint; } } } return null; }
/** * Process the command * * @return integer */ public function processCommandTask() { // output message $this->console->writeTaskLine('task_crud_load_tables_name', [$this->console->colorize($this->params->paramTableName, Color::GREEN)]); /** @var Adapter $dbAdapter */ $dbAdapter = $this->params->dbAdapter; // get Metadata for database adapter $metaData = new Metadata($dbAdapter); // fetch database $database = $dbAdapter->getCurrentSchema(); // init loaded tables $loadedTables = []; /** @var TableObject $tableObject */ foreach ($metaData->getTables() as $tableObject) { $columns = []; $primaryKey = []; $foreignKeys = []; /** @var ColumnObject $columnObject */ foreach ($tableObject->getColumns() as $columnObject) { $columns[$columnObject->getName()] = $columnObject; } /** @var ConstraintObject $constraintObject */ foreach ($tableObject->getConstraints() as $constraintObject) { if ($constraintObject->isPrimaryKey()) { $primaryKey = $constraintObject; } elseif ($constraintObject->isForeignKey()) { $foreignKeys[$constraintObject->getName()] = $constraintObject; } } $loadedTables[$tableObject->getName()] = ['columns' => $columns, 'primaryKey' => $primaryKey, 'foreignKeys' => $foreignKeys]; } // get missing tables $missingTables = array_values(array_diff($this->params->paramTableList, array_keys($loadedTables))); // check missing tables if (count($missingTables) == 1) { $this->console->writeFailLine('task_crud_load_tables_not_exists_one', [$this->console->colorize($missingTables[0], Color::GREEN), $this->console->colorize($database, Color::GREEN)]); return 1; } elseif (count($missingTables) > 1) { $this->console->writeFailLine('task_crud_load_tables_not_exists_more', [$this->console->colorize(implode(', ', $missingTables), Color::GREEN), $this->console->colorize($database, Color::GREEN)]); return 1; } // Ini needed tables $neededTables = []; // loop through table list foreach ($this->params->paramTableList as $tableName) { $neededTables[] = $tableName; /** @var ConstraintObject $foreignKey */ foreach ($loadedTables[$tableName]['foreignKeys'] as $foreignKey) { $neededTables[] = $foreignKey->getReferencedTableName(); } } // get missing tables $missingTables = array_values(array_diff($neededTables, $this->params->paramTableList)); // check missing tables if (count($missingTables) == 1) { $this->console->writeFailLine('task_crud_load_tables_needed_one', [$this->console->colorize($missingTables[0], Color::GREEN), $this->console->colorize($database, Color::GREEN)]); return 1; } elseif (count($missingTables) > 1) { $this->console->writeFailLine('task_crud_load_tables_needed_more', [$this->console->colorize(implode(', ', $missingTables), Color::GREEN), $this->console->colorize($database, Color::GREEN)]); return 1; } // get unneeded tables $unneededTables = array_diff(array_keys($loadedTables), $this->params->paramTableList); // clear unneeded tables foreach ($unneededTables as $tableName) { unset($loadedTables[$tableName]); } $this->params->loadedTables = $loadedTables; return 0; }
/** * Is the schema ready? * * @return bool */ public function hasSchema() { try { $metadata = new Metadata($this->adapter); $metadata->getTable($this->tableName); return true; } catch (\Exception $exception) { return false; } }
/** * Load table metadata. * * @param bool $reload Force a reload? (Default is false). * * @return array */ protected function getTableInfo($reload = false) { if ($reload || !$this->tableInfo) { $metadata = new DbMetadata($this->getAdapter()); $tables = $metadata->getTables(); $this->tableInfo = array(); foreach ($tables as $current) { $this->tableInfo[$current->getName()] = $current; } } return $this->tableInfo; }
/** * @param Adapter $adapter */ public function __construct(Adapter $adapter) { parent::__construct($adapter); }
public function getPerTimeHeader($is_admin = false) { $metadata = new Metadata($this->adapter); $header = $metadata->getColumnNames('buySideHourlyBidsPerTime'); return $is_admin ? $header : array_values(array_diff($header, $this->adminFields)); }
public function getPerTimeHeaderPrivateExchange() { $metadata = new Metadata($this->adapter); $header = $metadata->getColumnNames('PublisherImpressionsAndSpendHourly'); return array_values(array_diff($header, $this->domainAdminFields)); }
/** * 根据表名获得字段 * @return array|bool */ public function getColumns($conPri = false) { if (empty($this->table)) { return false; } $metadata = new Metadata($this->getAdapter()); $table = $metadata->getTable($this->table); $columns = $table->getColumns(); $cols = array(); if (in_array($this->table, array('MemberInfo'))) { $conPri = true; } if (!empty($columns)) { foreach ($columns as $c) { $cols[$c->getName()]['ableNull'] = $c->getIsNullable(); $cols[$c->getName()]['default'] = $c->getColumnDefault(); $cols[$c->getName()]['comment'] = $c->getColumnComment(); } if (!$conPri) { unset($cols[$this->_primary]); } } return $cols; }
/** * @return Adapter */ protected function getAdapter() { global $globalTestConfiguration; if (!isset($globalTestConfiguration) || !isset($globalTestConfiguration['zenddb']) || !isset($globalTestConfiguration['zenddb']['driver'])) { $this->markTestIncomplete('Invalid configuration found in test.config.php. Make sure "zenddb" is set and contains' . 'a valid config array for Zend\\Db\\Adapter\\Adapter'); } $this->adapter = $adapter = new Adapter($globalTestConfiguration['zenddb']); // attempt to connect $adapter->getDriver()->getConnection()->connect(); $this->assertTrue($adapter->getDriver()->getConnection()->isConnected(), 'DB connection established.'); $meta = new Metadata($adapter); $sql = new Sql($adapter); static::$schemaCleanup = true; // drop previous tables if needed if (in_array('model', $meta->getTableNames())) { $ddl = new Ddl\DropTable('model'); $adapter->query($sql->getSqlStringForSqlObject($ddl))->execute(); } if (in_array('minimalmodel', $meta->getTableNames())) { $ddl = new Ddl\DropTable('minimalmodel'); $adapter->query($sql->getSqlStringForSqlObject($ddl))->execute(); } // create test tables $ddl = new Ddl\CreateTable('model'); $ddl->addColumn(new Ddl\Column\Integer('id', true, null, ['auto_increment' => true])); $ddl->addColumn((new Ddl\Column\Varchar('magicProperty', 255))->setNullable(true)); $ddl->addColumn((new Ddl\Column\Varchar('protectedProperty', 255))->setNullable(true)); $ddl->addConstraint(new Ddl\Constraint\PrimaryKey('id')); $adapter->query($sql->getSqlStringForSqlObject($ddl), $adapter::QUERY_MODE_EXECUTE); $ddl = new Ddl\CreateTable('minimalmodel'); $ddl->addColumn(new Ddl\Column\Integer('id', true, null, ['auto_increment' => true])); $ddl->addColumn((new Ddl\Column\Varchar('name', 255))->setNullable(true)); $ddl->addColumn((new Ddl\Column\Varchar('value', 255))->setNullable(true)); $ddl->addConstraint(new Ddl\Constraint\PrimaryKey('id')); $adapter->query($sql->getSqlStringForSqlObject($ddl), $adapter::QUERY_MODE_EXECUTE); // return the adapter return $adapter; }
/** * Initialize migration history table * * @return $this */ protected function init() { if (!$this->isInited) { $metadata = new Metadata($this->adapter); if (!in_array($this->getStoreTableName(), $metadata->getTableNames())) { $this->runMigration($this->getInitialMigrationFile(), Migration::ACTION_UP); } $this->isInited = true; } return $this; }
/** * Render * * @param \Zend\Db\Metadata\Metadata $metadata * @return string */ public function render(\Zend\Db\Metadata\Metadata $metadata) { $output = ''; $output .= $this->renderTables($metadata->getTables()); return $output; }
/** * For static tables set * * @param ContainerInterface $container * @return array|false */ protected function getCachedTables(ContainerInterface $container) { if (!isset($this->tableNames)) { if ($this->setDbAdapter($container)) { $dbMetadata = new Metadata($this->db); $this->tableNames = $dbMetadata->getTableNames(); } else { $this->tableNames = false; } } return $this->tableNames; }