/** * Compile a rename column command. * * @param \Illuminate\Database\Schema\Blueprint $blueprint * @param \Illuminate\Support\Fluent $command * @param \Illuminate\Database\Connection $connection * @return array */ public function compileRenameColumn(Blueprint $blueprint, Fluent $command, Connection $connection) { $schema = $connection->getDoctrineSchemaManager(); $column = $connection->getDoctrineColumn($blueprint->getTable(), $command->from); $tableDiff = $this->getRenamedDiff($blueprint, $command, $column, $schema); return (array) $schema->getDatabasePlatform()->getAlterTableSQL($tableDiff); }
public function __construct(Connection $connection, RepositoryContract $config) { $dbconfig = $config->get('database.connections.' . $connection->getName()); $this->dsn = static::parseDSN($dbconfig); $this->username = $dbconfig['username']; $this->password = $dbconfig['password']; }
public function __construct(\Illuminate\Database\Connection $connection) { if (!$connection->getSchemaGrammar()) { $connection->useDefaultGrammar(); } parent::__construct($connection); }
/** * function to safely drop trigger db object * * @param string $name * @return boolean */ public function drop($name) { if (!$name) { return false; } return $this->connection->statement("\n declare\n e exception;\n pragma exception_init(e,-4080);\n begin\n execute immediate 'drop trigger {$name}';\n exception\n when e then\n null;\n end;"); }
/** * * @param string $query * @param array $bindings * @param float $time * @param \Illuminate\Database\Connection $connection */ public function addQuery($query, $bindings, $time, $connection) { $time = $time / 1000; $endTime = microtime(true); $startTime = $endTime - $time; $pdo = $connection->getPdo(); $bindings = $connection->prepareBindings($bindings); $bindings = $this->checkBindings($bindings); if (!empty($bindings) && $this->renderSqlWithParams) { foreach ($bindings as $binding) { $query = preg_replace('/\\?/', $pdo->quote($binding), $query, 1); } } $source = null; if ($this->findSource) { try { $source = $this->findSource(); } catch (\Exception $e) { } } $this->queries[] = array('query' => $query, 'bindings' => $bindings, 'time' => $time, 'source' => $source); if ($this->timeCollector !== null) { $this->timeCollector->addMeasure($query, $startTime, $endTime); } }
/** * @param Connection $connection */ public function __construct(Connection $connection) { $this->connection = $connection; $this->grammar = $connection->getSchemaGrammar(); $this->helper = new OracleAutoIncrementHelper($connection); $this->comment = new Comment($connection); }
/** * * @param string $query * @param array $bindings * @param float $time * @param \Illuminate\Database\Connection $connection */ public function addQuery($query, $bindings, $time, $connection) { $explainResults = array(); $time = $time / 1000; $endTime = microtime(true); $startTime = $endTime - $time; $hints = $this->performQueryAnalysis($query); $pdo = $connection->getPdo(); $bindings = $connection->prepareBindings($bindings); // Run EXPLAIN on this query (if needed) if ($this->explainQuery && preg_match('/^(' . implode($this->explainTypes) . ') /i', $query)) { $statement = $pdo->prepare('EXPLAIN ' . $query); $statement->execute($bindings); $explainResults = $statement->fetchAll(\PDO::FETCH_CLASS); } $bindings = $this->checkBindings($bindings); if (!empty($bindings) && $this->renderSqlWithParams) { foreach ($bindings as $binding) { $query = preg_replace('/\\?/', $pdo->quote($binding), $query, 1); } } $source = null; if ($this->findSource) { try { $source = $this->findSource(); } catch (\Exception $e) { } } $this->queries[] = array('query' => $query, 'bindings' => $this->escapeBindings($bindings), 'time' => $time, 'source' => $source, 'explain' => $explainResults, 'hints' => $hints); if ($this->timeCollector !== null) { $this->timeCollector->addMeasure($query, $startTime, $endTime); } }
/** * Retrieve the schema builder for the database connection. And set a custom blueprint resolver to return an * instance of the Culpa Blueprint class. * * @param Connection $connection * @return \Illuminate\Database\Schema\Builder */ protected static function getSchemaBuilder(Connection $connection) { $schemaBuilder = $connection->getSchemaBuilder(); $schemaBuilder->blueprintResolver(function ($table, $callback) { return new Blueprint($table, $callback); }); return $schemaBuilder; }
/** * @param EventStreamInterface $eventStream * @return void * @throws SerializationException */ public function append(EventStreamInterface $eventStream) { $events = collect(iterator_to_array($eventStream))->map(function ($event) { /** @var EventInterface $event */ return ['aggregate_root_id' => (string) $event->getAggregateRootId(), 'type' => get_class($event), 'payload' => $this->serializer->serialize($event)]; }); $this->db->table('events')->insert($events->toArray()); }
/** * Process an "insert get ID" query for ODBC. * * @param \Illuminate\Database\Connection $connection * @return int */ protected function processInsertGetIdForOdbc($connection) { $result = $connection->select('SELECT CAST(COALESCE(SCOPE_IDENTITY(), @@IDENTITY) AS int) AS insertid'); if (!$result) { throw new Exception('Unable to retrieve lastInsertID for ODBC.'); } return $result[0]->insertid; }
/** * @param $table * @param $field * @param $hash * @param $min_length * @param $max_length * @return string */ private function checkIfHAshIsUnique($table, $field, $hash, $min_length, $max_length) { if (!$this->db->table($table)->where($field, '=', $hash)->get()) { return $hash; } else { return $this->makeHAsh($table, $field, true, $min_length, $max_length); } }
/** * @param \Illuminate\Database\Connection $db * @param int $channelId * @param string $nick * @return int */ protected function getNickId(Connection $db, $channelId, $nick) { $targetNick = $db->table('nicks')->select('id')->where('channel_id', '=', $channelId)->where('nick', '=', $nick)->first(); if ($targetNick) { return $targetNick['id']; } else { return $db->table('nicks')->insertGetId(['channel_id' => $channelId, 'nick' => $nick]); } }
/** * Process an "insert get ID" query for ODBC. * * @param \Illuminate\Database\Connection $connection * @return int */ protected function processInsertGetIdForOdbc($connection) { $result = $connection->selectFromWriteConnection('SELECT CAST(COALESCE(SCOPE_IDENTITY(), @@IDENTITY) AS int) AS insertid'); if (!$result) { throw new Exception('Unable to retrieve lastInsertID for ODBC.'); } $row = $result[0]; return is_object($row) ? $row->insertid : $row['insertid']; }
public function run() { $this->database->table(DbEventStore::TABLE)->truncate(); $startTaskList = new StartTaskListCommand(['Eat cake', 'Walk cake off', 'Rinse and repeat']); $this->service->handleStartTaskListCommand($startTaskList); $startTaskList = new StartTaskListCommand(['Read: Learn DDD', 'Read: Implementing DDD', 'Read: The data model resource book volume 1', 'Read: The data model resource book volume 2']); $this->service->handleStartTaskListCommand($startTaskList); $this->command->getOutput()->writeln("<info>Seeded:</info> Task Lists!"); }
/** * Create a new schema blueprint. * * @param string $table * @param Closure $callback */ public function __construct(Connection $connection, $collection) { $this->connection = $connection; try { $this->collection = $connection->getCollection($collection); } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) { $this->collection = ['type' => $collection]; } }
/** * Append the character set specifications to a command. * * @param string $sql * @param \Illuminate\Database\Connection $connection * @return string */ protected function compileCreateEncoding($sql, Connection $connection) { if (!is_null($charset = $connection->getConfig('charset'))) { $sql .= ' default character set ' . $charset; } if (!is_null($collation = $connection->getConfig('collation'))) { $sql .= ' collate ' . $collation; } return $sql; }
/** * @test */ public function it_appends_events() { $event = new PointsWereAdded(100); $stream = new EventStream($event); $eventData = ['aggregate_root_id' => 'BarId', 'type' => PointsWereAdded::class, 'payload' => ['amount' => '100']]; $this->db->table('events')->willReturn($this->queryBuilder); $this->serializer->serialize($event)->willReturn(['amount' => '100']); $this->queryBuilder->insert([$eventData])->willReturn(true); $this->eventStore->append($stream); }
/** * {@inheritdoc} */ public function hasTable($table) { try { if (!is_null($this->connection->openBucket($table)->getName())) { return true; } } catch (\CouchbaseException $e) { return false; } }
/** * Prepare the database connection instance. * * @param Illuminate\Database\Connection $connection * @return Illuminate\Database\Connection */ protected function prepare(Connection $connection) { $connection->setFetchMode($this->app['config']['database.fetch']); $connection->setEventDispatcher($this->app['events']); // We will setup a Closure to resolve the paginator instance on the connection // since the Paginator isn't sued on every request and needs quite a few of // our dependencies. It'll be more efficient to lazily resolve instances. $app = $this->app; $connection->setPaginator(function () use($app) { return $app['paginator']; }); return $connection; }
/** * Append the character set specifications to a command. * * @param string $sql * @param \Illuminate\Database\Connection $connection * @param \Illuminate\Database\Schema\Blueprint $blueprint * @return string */ protected function compileCreateEncoding($sql, Connection $connection, Blueprint $blueprint) { if (isset($blueprint->charset)) { $sql .= ' default character set ' . $blueprint->charset; } elseif (!is_null($charset = $connection->getConfig('charset'))) { $sql .= ' default character set ' . $charset; } if (isset($blueprint->collation)) { $sql .= ' collate ' . $blueprint->collation; } elseif (!is_null($collation = $connection->getConfig('collation'))) { $sql .= ' collate ' . $collation; } return $sql; }
private function _explainAndShowIndex(Connection $connection, $sql, $bindings) { $explainResults = $connection->select('explain ' . $sql, $bindings); foreach ($explainResults as $explainResult) { $results = get_object_vars($explainResult); $results['sql'] = $sql; $this->explainResults[] = $results; if (empty($results['table'])) { continue; } $showIndexResults = $connection->select('show index from ' . $results['table']); foreach ($showIndexResults as $showIndexResult) { $this->showIndexResults[] = get_object_vars($showIndexResult); } } }
/** * Set the default fetch mode for the connection. * * NOTE! Crate cannot use PDO::FETCH_CLASS fetch mode, so * we silently change it to PDO::FETCH_ASSOC * * @param int $fetchMode * @return int */ public function setFetchMode($fetchMode) { if ($fetchMode === \PDO::FETCH_CLASS) { $fetchMode = \PDO::FETCH_ASSOC; } parent::setFetchMode($fetchMode); }
/** * Generate a table from metadata. * * @param table \Doctrine\DBAL\Schema\Schema * @param \ProAI\Datamapper\Metadata\Definitions\Table $tableMetadata * @return void */ protected function generateTableFromMetadata($schema, TableDefinition $tableMetadata) { $primaryKeys = []; $uniqueIndexes = []; $indexes = []; $table = $schema->createTable($this->connection->getTablePrefix() . $tableMetadata['name']); foreach ($tableMetadata['columns'] as $columnMetadata) { $columnMetadata = $this->getDoctrineColumnAliases($columnMetadata); // add column $options = $this->getDoctrineColumnOptions($columnMetadata); $table->addColumn($columnMetadata['name'], $columnMetadata['type'], $options); // add primary keys, unique indexes and indexes if (!empty($columnMetadata['primary'])) { $primaryKeys[] = $columnMetadata['name']; } if (!empty($columnMetadata['unique'])) { $uniqueIndexes[] = $columnMetadata['name']; } if (!empty($columnMetadata['index'])) { $indexes[] = $columnMetadata['name']; } } // add primary keys, unique indexes and indexes if (!empty($primaryKeys)) { $table->setPrimaryKey($primaryKeys); } if (!empty($uniqueIndexes)) { $table->addUniqueIndex($uniqueIndexes); } if (!empty($indexes)) { $table->addIndex($indexes); } }
/** * Create and return a new query to identify untranslated records. * * @param string $locale * @return \Illuminate\Database\Query\Builder */ protected function untranslatedQuery($locale) { $table = $this->model->getTable(); return $this->database->table("{$table} as {$table}")->select("{$table}.id")->leftJoin("{$table} as e", function (JoinClause $query) use($table, $locale) { $query->on('e.namespace', '=', "{$table}.namespace")->on('e.group', '=', "{$table}.group")->on('e.item', '=', "{$table}.item")->where('e.locale', '=', $locale); })->where("{$table}.locale", $this->defaultLocale)->whereNull("e.id"); }
/** * Returns the database connection. * * @return \Illuminate\Database\Connection * @throws \InvalidArgumentException */ public function getConnection() { if ($this->connection === null) { $this->connection = new Connection($this->pdo, '', $this->tablePrefix); // We will now provide the query grammar to the connection. switch ($this->driverName) { case 'mysql': $queryGrammar = 'Illuminate\\Database\\Query\\Grammars\\MySqlGrammar'; break; case 'pgsql': $queryGrammar = 'Illuminate\\Database\\Query\\Grammars\\PostgresGrammar'; break; case 'sqlsrv': $queryGrammar = 'Illuminate\\Database\\Query\\Grammars\\SqlServerGrammar'; break; case 'sqlite': $queryGrammar = 'Illuminate\\Database\\Query\\Grammars\\SQLiteGrammar'; break; default: throw new \InvalidArgumentException("Cannot determine grammar to use based on {$this->driverName}."); break; } $this->connection->setQueryGrammar(new $queryGrammar()); } return $this->connection; }
/** * Create Schema * * @return AdapterInterface */ public function createSchema() { /* @var \Illuminate\Database\Schema\Blueprint $table */ $this->adapter->getSchemaBuilder()->create($this->tableName, function ($table) { $table->string('version'); }); }
/** * Set the default fetch mode for the connection. * * NOTE! Crate cannot use PDO::FETCH_CLASS fetch mode, so * we silently change it to PDO::FETCH_ASSOC * https://crate.io/docs/reference/pdo/usage.html#fetch-modes * * @param int $fetchMode * @return int */ public function setFetchMode($fetchMode, $fetchArgument = null, array $ctorArgs = []) { if ($fetchMode !== \PDO::FETCH_ASSOC) { $fetchMode = \PDO::FETCH_ASSOC; } parent::setFetchMode($fetchMode, $fetchArgument, $ctorArgs); }
/** * @param \Illuminate\Database\Connection $eloquentConnection * * @return \DreamFactory\Core\Database\Connection * @throws \DreamFactory\Core\Exceptions\InternalServerErrorException */ public static function getLegacyConnection($eloquentConnection) { if (empty(static::$connection)) { $driver = $eloquentConnection->getDriverName(); if (empty($driver)) { throw new InternalServerErrorException('No database driver supplied'); } $connections = config('database.connections'); if (empty($connections)) { throw new InternalServerErrorException('No connections found in database.connections config'); } $configKeys = []; foreach ($connections as $name => $connectionConfig) { if ($driver === $name || $driver === $connectionConfig['driver'] || $driver === 'dblib' && $name === 'sqlsrv') { $configKeys = array_keys($connectionConfig); } } if (empty($configKeys)) { throw new InternalServerErrorException('Unsupported driver - ' . $driver); } $config = []; foreach ($configKeys as $key) { $config[$key] = $eloquentConnection->getConfig($key); } switch ($driver) { case 'sqlite': $dsn = $driver . ":" . $config['database']; break; case 'mysql': $dsn = static::getMySqlDsn($config); break; case 'pgsql': $dsn = static::getPgSqlDsn($config); break; case 'sqlsrv': case 'dblib': $dsn = static::getSqlSrvDsn($config); break; default: throw new InternalServerErrorException('Unsupported driver - ' . $driver); break; } $config['dsn'] = $dsn; static::$connection = ConnectionFactory::createConnection($driver, $config); } return static::$connection; }
private function getTableColumns($callback = null) { if ($this->tableColumns === null) { $this->tableColumns = $this->db->select('SHOW COLUMNS FROM ' . $this->table); } $filteredColumns = $callback ? array_filter($this->tableColumns, $callback) : $this->tableColumns; return array_pluck($filteredColumns, 'Field'); }
/** * Delete a reserved job from the queue. * * @param string $queue * @param string $id * @return void */ public function deleteReserved($queue, $id) { $this->database->beginTransaction(); if ($this->database->table($this->table)->lockForUpdate()->find($id)) { $this->database->table($this->table)->where('id', $id)->delete(); } $this->database->commit(); }