public function getTableDefinition($tableName) { $tableSymbol = new Symbol($tableName); $res = $this->database->query("DESC ?", $tableSymbol); $columns = new \stdClass(); while ($row = $res->fetchRow()) { $type = $row['Type']; $field = $row['Field']; $phpType = $this->getTypeByString($type); if ('auto_increment' === $row['Extra']) { $phpType += Column::AUTO_ID; } $column = new Column($phpType); $columns->{$field} = $column; $column->schemaName = $field; $notNull = $row['Null'] === 'NO'; if ($row['Default'] !== null || !$notNull) { $column->setDefault($row['Default']); } $column->setFlag(Column::NOT_NULL, $notNull); } $definition = new Table($columns, $this->database, $tableName); $res = $this->database->query("SHOW INDEX FROM ?", $tableSymbol); $indexes = array(); $uniqueIndex = array(); foreach ($res as $row) { $indexes[$row['Key_name']][$row['Seq_in_index']] = $columns->{$row['Column_name']}; $uniqueIndex[$row['Key_name']] = !$row['Non_unique']; } foreach ($indexes as $indexName => $indexData) { ksort($indexData); $index = new Index(array_values($indexData)); $index->setName($indexName); $index->setType($uniqueIndex[$indexName] ? Index::TYPE_UNIQUE : Index::TYPE_KEY); if ($indexName === self::_PRIMARY) { $definition->setPrimaryKey($index->columns); } else { $definition->addIndex($index); } } return $definition; }
public function exportCombined() { $res = Database::getInstance()->query("select\n child.name as child,\n parent.name as parent,\n sum(wall_time) as wt,\n sum(count) as ct,\n sum(cpu) as cpu,\n round(avg(memory_usage)) as mu,\n max(peak_memory_usage) as pmu\nfrom phperf_xhprof_related_stat\n LEFT JOIN phperf_xhprof_symbol as child ON phperf_xhprof_related_stat.child_symbol_id = child.id\n LEFT JOIN phperf_xhprof_symbol as parent ON phperf_xhprof_related_stat.parent_symbol_id = parent.id\nGROUP BY child_symbol_id, parent_symbol_id;")->fetchAll(); $result = array(); foreach ($res as $row) { $result[$row['parent'] . '==>' . $row['child']] = array('ct' => (int) $row['ct'], 'wt' => (int) $row['wt'], 'cpu' => (int) $row['cpu'], 'mu' => (int) $row['mu'], 'pmu' => (int) $row['pmu']); } $res = Database::getInstance()->query("select\n symbol.name as symbol,\n sum(wall_time) as wt,\n sum(count) as ct,\n sum(cpu) as cpu,\n round(avg(memory_usage)) as mu,\n max(peak_memory_usage) as pmu\nfrom phperf_xhprof_single_stat\n LEFT JOIN phperf_xhprof_symbol as symbol ON phperf_xhprof_single_stat.symbol_id = symbol.id\nGROUP BY symbol_id;")->fetchAll(); foreach ($res as $row) { $result[$row['symbol']] = array('ct' => (int) $row['ct'], 'wt' => (int) $row['wt'], 'cpu' => (int) $row['cpu'], 'mu' => (int) $row['mu'], 'pmu' => (int) $row['pmu']); } file_put_contents('export.serialized', serialize($result)); }
public function listTop() { $database = Database::getInstance(); $esc = SymbolStat::columns(); $statement = $database->select(SymbolStat::table())->select("SUM(?) AS total_wt, SUM(?) AS total_ct, COUNT(DISTINCT ?) AS runs, ?, ?", $esc->wallTime, $esc->calls, $esc->runId, $esc->symbolId, Symbol::columns()->name)->leftJoin('? ON ? = ?', Symbol::table(), Symbol::columns()->id, $esc->symbolId)->groupBy(SymbolStat::columns()->symbolId)->order('total_wt DESC')->limit(50); $res = $statement->query(); $table = new HTML(); foreach ($res as $row) { $row['name'] = '<a href="?symbol=' . urlencode($row['name']) . '">' . $row['name'] . '</a>'; unset($row['symbol_id']); $table->addRow($row); } $this->layout->pushMain($table)->render(); }
public function performAction() { $database = Database::getInstance(); $settings = $database->getSettings(); $tables = $settings->getTables(); $log = new Log('colored-stdout'); if ($this->wipe) { foreach ($tables as $table) { $table->migration()->setDryRun($this->dryRun)->setLog($log)->rollback(); } } foreach ($tables as $table) { $table->migration()->setDryRun($this->dryRun)->setLog($log)->apply(); } }
public function showSymbol() { if (!empty($_GET['run'])) { $run = new Run(); $run->name = $_GET['run']; $run->findSaved()->id; $this->runName = $run->findSaved()->id; } /** @var Symbol $symbol */ $symbol = Symbol::statement()->where('? = ?', Symbol::columns()->name, $this->symbol)->query()->fetchRow(); if (null === $symbol) { return $this->error('Symbol ? not found', $this->symbol); } $stack = new Stack(); $database = Database::getInstance(); $inc = RelatedStat::columns(); $mainSymbol = new Symbol(); $mainSymbol->name = 'main()'; $mainSymbol->findOrSave(); $total_wt = $database->select(Run::table())->select("SUM(?) AS total_wt", Run::columns()->wallTime)->query()->fetchRow('total_wt'); $stack->push(Raw::create('<h2>Total: ' . $total_wt . '</h2>')); $statement = $database->select(RelatedStat::table())->select("SUM(?)/1000000 AS total_wt, SUM(?) AS total_ct, COUNT(DISTINCT ?) AS runs, ? AS symbol_id, ?", $inc->wallTime, $inc->calls, $inc->runId, $inc->parentSymbolId, Symbol::columns()->name)->leftJoin('? ON ? = ?', Symbol::table(), Symbol::columns()->id, $inc->parentSymbolId)->where('? = ?', $inc->childSymbolId, $symbol->id)->groupBy($inc->parentSymbolId)->order('total_wt DESC')->limit(50); $res = $statement->query(); $table = new HTML(); $stack->push(Raw::create('<h2>Parents</h2>')); $stack->push($table); foreach ($res as $row) { $row['percent'] = round(100 * $row['total_wt'] / $total_wt, 2); $row['name'] = '<a href="?symbol=' . urlencode($row['name']) . '&run=' . $_GET['run'] . '">' . $row['name'] . '</a>'; unset($row['symbol_id']); $table->addRow($row); } $statement = $database->select(RelatedStat::table())->select("SUM(?)/1000000 AS total_wt, SUM(?) AS total_ct, COUNT(DISTINCT ?) AS runs, ? AS symbol_id, ?", $inc->wallTime, $inc->calls, $inc->runId, $inc->childSymbolId, Symbol::columns()->name)->leftJoin('? ON ? = ?', Symbol::table(), Symbol::columns()->id, $inc->childSymbolId)->where('? = ?', $inc->parentSymbolId, $symbol->id)->groupBy($inc->childSymbolId)->order('total_wt DESC')->limit(50); $res = $statement->query(); $table = new HTML(); $stack->push(Raw::create('<h2>Children</h2>')); $stack->push($table); foreach ($res as $row) { $row['percent'] = round(100 * $row['total_wt'] / $total_wt, 2); $row['name'] = '<a href="?symbol=' . urlencode($row['name']) . '&run=' . $_GET['run'] . '">' . $row['name'] . '</a>'; unset($row['symbol_id']); $table->addRow($row); } $this->layout->setTitle($symbol->name)->pushMain($stack)->render(); }
/** * @return ClosureMigration */ public function getMigration() { $migrationId = 'storage_db_wrapper' . '_' . get_class($this->db->getDriver()) . $this->table->name; $table = $this->table; $keyField = $this->keyField; $valueField = $this->valueField; $expireField = $this->expireField; $db = $this->db; return new ClosureMigration($migrationId, function () use($table, $keyField, $valueField, $expireField, $db) { //if ($this->db->getDriver() instanceof Database_Server_Mysql) { $db->query("CREATE TABLE IF NOT EXISTS :table (\n:key VARCHAR(255) NOT NULL DEFAULT '',\n:value TEXT NOT NULL,\n:expire INTEGER NOT NULL DEFAULT 0,\nPRIMARY KEY (:key)\n)", array('table' => $table, 'key' => $keyField, 'value' => $valueField, 'expire' => $expireField)); //} return true; }, function () use($table, $db) { $db->query("DROP TABLE ?", $table); return true; }); }
private function readForeignKeys(Table $def) { $res = $this->database->select()->select('tc.constraint_name, kcu.column_name')->select('ccu.table_name AS foreign_table_name, ccu.column_name AS foreign_column_name')->from('information_schema.table_constraints AS tc')->innerJoin('information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name')->innerJoin('information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name')->where('constraint_type = \'FOREIGN KEY\'')->where('tc.table_name = ?', $def->schemaName)->query()->fetchAll(); $fk = array(); foreach ($res as $r) { $fk[$r['constraint_name']][$r['column_name']] = array($r['foreign_table_name'], $r['foreign_column_name']); } foreach ($fk as $constraintName => $constraintColumns) { $localColumns = array(); $referenceColumns = array(); foreach ($constraintColumns as $localName => $refData) { $localColumns[] = $def->columns->{$localName}; $column = new Column(); $column->table = new Table(null, null, $refData[0]); $column->schemaName = $refData[1]; $referenceColumns[] = $column; } $foreignKey = new Database\Definition\ForeignKey($localColumns, $referenceColumns); $foreignKey->setName($constraintName); $def->addForeignKey($foreignKey); } }
<?php namespace Phperf\Xhprof; use Yaoi\Database; use Yaoi\Log; require_once __DIR__ . '/../vendor/autoload.php'; $dbFilePath = sys_get_temp_dir() . '/xh-tests.sqlite'; register_shutdown_function(function () use($dbFilePath) { unlink($dbFilePath); }); Database::register('sqlite:///' . $dbFilePath); unset($dbFilePath); Entity\Migrations::create()->run(); Database::getInstance()->log(new Log('colored-stdout'));
<?php namespace PHPerf; use Yaoi\Database; use Yaoi\Http\Auth; use Yaoi\Http\Auth\Settings; use Yaoi\Log; use Yaoi\Storage; date_default_timezone_set('Europe/Moscow'); header("Content-Type: text/html; charset=utf8"); error_reporting(E_ALL); ini_set('display_errors', 'on'); umask('0002'); Auth::register(function () { $dsn = new Settings(); $dsn->title = 'Developers Only Area'; $dsn->salt = '<random-string>'; $dsn->users = array('<login>' => '<password-hash>'); return $dsn; }, 'dev'); Storage::register(new Storage\PhpVar(), 'debug_log'); Log::register('storage:///?storage=debug_log', 'debug_log'); Database::register(function () { $database = new Database('mysqli://root@localhost/phperf_result'); $database->log(Log::getInstance('debug_log')); return $database; });
public function performAction() { if (!file_exists($this->path)) { throw new \Exception(Expression::create('File ? not found', $this->path)); } $GPSEssentials = new GPSEssentials($this->path); $database = new Database('sqlite:///' . realpath($this->path)); $database->log(new Log('colored-stdout')); TrackElement::bindDatabase($database); //$this->count = $database->query("SELECT COUNT(1) AS c FROM ?", TrackElement::table())->fetchRow('c'); $pageQuery = TrackElement::statement()->order("? ASC", TrackElement::columns()->id)->limit($this->pageSize); if ($this->from) { $pageQuery->where('? >= 1000 * ?', TrackElement::columns()->time, strtotime($this->from)); } if ($this->to) { $pageQuery->where('? <= 1000 * ?', TrackElement::columns()->time, strtotime($this->to)); } $this->segments = array(Segment5::className(), Segment10::className(), Segment100::className(), Segment500::className(), Segment1k::className(), Segment5k::className(), Segment10k::className()); $timeSegments = array(Segment10s::className(), Segment60s::className()); /** @var BatchSaver[] $batchSavers */ $batchSavers = array(); foreach ($this->segments as $segment) { $batchSavers[$segment] = new BatchSaver(); } foreach ($timeSegments as $segment) { $batchSavers[$segment] = new BatchSaver(); } while ($res = $pageQuery->query()->fetchAll()) { /** @var TrackElement $row */ foreach ($res as $row) { $row->time /= 1000; /** @var Segment5|string $segment */ foreach ($this->segments as $segment) { if (!isset($this->lastPoints[$segment])) { $this->lastPoints[$segment] = $row; } /** @var TrackElement $lastPoint */ $lastPoint = $this->lastPoints[$segment]; if (($distance = GPSEssentials::distance($lastPoint, $row)) > $segment::MIN_DISTANCE) { /** @var Segment5 $segmentItem */ $segmentItem = new $segment(); $segmentItem->distance = $distance; $segmentItem->latitude = $row->latitude; $segmentItem->longitude = $row->longitude; $segmentItem->ut = $row->time; $segmentItem->altitude = $row->altitude; $segmentItem->time = $row->time - $lastPoint->time; if ($segmentItem->time) { $segmentItem->speed = $segmentItem->distance / $segmentItem->time; } $segmentItem->elevation = $row->altitude - $lastPoint->altitude; $batchSavers[$segment]->add($segmentItem); //$segmentItem->save(); $this->lastPoints[$segment] = $row; } } /** @var Segment10s|string $segment */ foreach ($timeSegments as $segment) { if (!isset($this->lastPoints[$segment])) { $this->lastPoints[$segment] = $row; } /** @var TrackElement $lastPoint */ $lastPoint = $this->lastPoints[$segment]; if ($row->time - $lastPoint->time > $segment::MIN_TIME) { /** @var Segment5 $segmentItem */ $segmentItem = new $segment(); $segmentItem->distance = GPSEssentials::distance($lastPoint, $row); $segmentItem->latitude = $row->latitude; $segmentItem->longitude = $row->longitude; $segmentItem->ut = $row->time; $segmentItem->altitude = $row->altitude; $segmentItem->time = $row->time - $lastPoint->time; if ($segmentItem->time) { $segmentItem->speed = $segmentItem->distance / $segmentItem->time; } $segmentItem->elevation = $row->altitude - $lastPoint->altitude; $batchSavers[$segment]->add($segmentItem); //$segmentItem->save(); $this->lastPoints[$segment] = $row; } } } $this->offset += $this->pageSize; $pageQuery->offset($this->offset); } foreach ($batchSavers as $batchSaver) { $batchSaver->flush(); } }
public function dropTable($tableName) { $this->database->query($this->generateDropTable($tableName)); }
private static function getDatabase($class) { if (isset(self::$databases[$class])) { return self::$databases[$class]; } else { return Database::getInstance(); } }
<?php namespace Phperf\Xhprof; use Yaoi\Database; use Yaoi\Log; Database::register('sqlite:///' . __DIR__ . '/../xh-stat.sqlite'); //Database::register('mysqli://root:@localhost/xhprof_stat2'); //Database::getInstance()->log(new Log('colored-stdout'));
/** * @return $this|\Yaoi\Sql\SelectInterface|\Yaoi\Sql\UpdateInterface */ public function build($statExpr) { $symbolsDerived = SymbolStat::table('s'); $symbolsDerivedCols = SymbolStat::columns($symbolsDerived); $symbolCols = Symbol::columns(); $this->expr = Database::getInstance()->statement()->select('? AS ?', $symbolCols->name, new S('function'))->from('? AS s', $statExpr)->leftJoin('? ON ? = ?', Symbol::table(), $symbolsDerivedCols->symbolId, $symbolCols->id)->groupBy('?', $symbolsDerivedCols->symbolId); $this->avgWtSymbols = array(); foreach ($this->runs as $run) { $runXTable = SymbolStat::table($run->name); $runXCols = SymbolStat::columns($runXTable); $this->addColumns($run, $runXCols); $this->expr->leftJoin('? ON ? = ? AND ? = ? AND ? = ?', $runXTable, $runXCols->symbolId, $symbolsDerivedCols->symbolId, $runXCols->isInclusive, $this->isInclusive, $runXCols->runId, $run->id); } $outerExpr = Database::getInstance()->statement()->select('*')->from('? AS ss', $this->expr)->order('COALESCE(null, ?) DESC', array($this->avgWtSymbols))->limit($this->limit); return $outerExpr; }
$settings->username = '******'; $settings->password = '******'; return $settings; }); Http\Client::register(function () { $client = new Http\Client(); $client->mock(new Mock(Storage::getInstance('mock'))); return $client; }); Storage::register(function () { $settings = new Storage\Settings(); $settings->driverClassName = Storage\Driver\SerializedFile::className(); $settings->path = __DIR__ . '/resources/mock4.serialized'; return $settings; }, 'mock'); Database::register('mysqli://root:@localhost/wakabot?timezone=Asia/Jakarta'); /* Database::register(function(){ $settings = new Database\Settings(); $settings->driverClassName = Database\Driver\Sqlite::className(); $settings->path = __DIR__ . '/resources/db.sqlite'; return $settings; }, 'sqlite'); */ Migration\Manager::register(function () { $settings = new Migration\Settings(); $settings->storage = new Storage('serialized-file:///' . __DIR__ . '/resources/migration.serialized'); $settings->run = function () { }; return $settings; });
<?php namespace Wtf; use Yaoi\Database; Database::register('sqlite:///' . __DIR__ . '/../data.sqlite');
/** * @param string $identifier * @return Database\Contract */ static function database($identifier = Service::PRIMARY) { return Database::getInstance($identifier); }