code
stringlengths 31
1.39M
| docstring
stringlengths 23
16.8k
| func_name
stringlengths 1
126
| language
stringclasses 1
value | repo
stringlengths 7
63
| path
stringlengths 7
166
| url
stringlengths 50
220
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
protected function createPdoResolverWithoutHosts(array $config)
{
return fn () => $this->createConnector($config)->connect($config);
}
|
Create a new Closure that resolves to a PDO instance where there is no configured host.
@param array $config
@return \Closure
|
createPdoResolverWithoutHosts
|
php
|
illuminate/database
|
Connectors/ConnectionFactory.php
|
https://github.com/illuminate/database/blob/master/Connectors/ConnectionFactory.php
|
MIT
|
public function createConnector(array $config)
{
if (! isset($config['driver'])) {
throw new InvalidArgumentException('A driver must be specified.');
}
if ($this->container->bound($key = "db.connector.{$config['driver']}")) {
return $this->container->make($key);
}
return match ($config['driver']) {
'mysql' => new MySqlConnector,
'mariadb' => new MariaDbConnector,
'pgsql' => new PostgresConnector,
'sqlite' => new SQLiteConnector,
'sqlsrv' => new SqlServerConnector,
default => throw new InvalidArgumentException("Unsupported driver [{$config['driver']}]."),
};
}
|
Create a connector instance based on the configuration.
@param array $config
@return \Illuminate\Database\Connectors\ConnectorInterface
@throws \InvalidArgumentException
|
createConnector
|
php
|
illuminate/database
|
Connectors/ConnectionFactory.php
|
https://github.com/illuminate/database/blob/master/Connectors/ConnectionFactory.php
|
MIT
|
protected function createConnection($driver, $connection, $database, $prefix = '', array $config = [])
{
if ($resolver = Connection::getResolver($driver)) {
return $resolver($connection, $database, $prefix, $config);
}
return match ($driver) {
'mysql' => new MySqlConnection($connection, $database, $prefix, $config),
'mariadb' => new MariaDbConnection($connection, $database, $prefix, $config),
'pgsql' => new PostgresConnection($connection, $database, $prefix, $config),
'sqlite' => new SQLiteConnection($connection, $database, $prefix, $config),
'sqlsrv' => new SqlServerConnection($connection, $database, $prefix, $config),
default => throw new InvalidArgumentException("Unsupported driver [{$driver}]."),
};
}
|
Create a new connection instance.
@param string $driver
@param \PDO|\Closure $connection
@param string $database
@param string $prefix
@param array $config
@return \Illuminate\Database\Connection
@throws \InvalidArgumentException
|
createConnection
|
php
|
illuminate/database
|
Connectors/ConnectionFactory.php
|
https://github.com/illuminate/database/blob/master/Connectors/ConnectionFactory.php
|
MIT
|
public function createConnection($dsn, array $config, array $options)
{
[$username, $password] = [
$config['username'] ?? null, $config['password'] ?? null,
];
try {
return $this->createPdoConnection(
$dsn, $username, $password, $options
);
} catch (Exception $e) {
return $this->tryAgainIfCausedByLostConnection(
$e, $dsn, $username, $password, $options
);
}
}
|
Create a new PDO connection.
@param string $dsn
@param array $config
@param array $options
@return \PDO
@throws \Exception
|
createConnection
|
php
|
illuminate/database
|
Connectors/Connector.php
|
https://github.com/illuminate/database/blob/master/Connectors/Connector.php
|
MIT
|
protected function createPdoConnection($dsn, $username, #[\SensitiveParameter] $password, $options)
{
return version_compare(phpversion(), '8.4.0', '<')
? new PDO($dsn, $username, $password, $options)
: PDO::connect($dsn, $username, $password, $options); /** @phpstan-ignore staticMethod.notFound (PHP 8.4) */
}
|
Create a new PDO connection instance.
@param string $dsn
@param string $username
@param string $password
@param array $options
@return \PDO
|
createPdoConnection
|
php
|
illuminate/database
|
Connectors/Connector.php
|
https://github.com/illuminate/database/blob/master/Connectors/Connector.php
|
MIT
|
protected function tryAgainIfCausedByLostConnection(Throwable $e, $dsn, $username, #[\SensitiveParameter] $password, $options)
{
if ($this->causedByLostConnection($e)) {
return $this->createPdoConnection($dsn, $username, $password, $options);
}
throw $e;
}
|
Handle an exception that occurred during connect execution.
@param \Throwable $e
@param string $dsn
@param string $username
@param string $password
@param array $options
@return \PDO
@throws \Throwable
|
tryAgainIfCausedByLostConnection
|
php
|
illuminate/database
|
Connectors/Connector.php
|
https://github.com/illuminate/database/blob/master/Connectors/Connector.php
|
MIT
|
public function getOptions(array $config)
{
$options = $config['options'] ?? [];
return array_diff_key($this->options, $options) + $options;
}
|
Get the PDO options based on the configuration.
@param array $config
@return array
|
getOptions
|
php
|
illuminate/database
|
Connectors/Connector.php
|
https://github.com/illuminate/database/blob/master/Connectors/Connector.php
|
MIT
|
public function getDefaultOptions()
{
return $this->options;
}
|
Get the default PDO connection options.
@return array
|
getDefaultOptions
|
php
|
illuminate/database
|
Connectors/Connector.php
|
https://github.com/illuminate/database/blob/master/Connectors/Connector.php
|
MIT
|
public function setDefaultOptions(array $options)
{
$this->options = $options;
}
|
Set the default PDO connection options.
@param array $options
@return void
|
setDefaultOptions
|
php
|
illuminate/database
|
Connectors/Connector.php
|
https://github.com/illuminate/database/blob/master/Connectors/Connector.php
|
MIT
|
protected function getSqlMode(PDO $connection, array $config)
{
if (isset($config['modes'])) {
return implode(',', $config['modes']);
}
if (! isset($config['strict'])) {
return null;
}
if (! $config['strict']) {
return 'NO_ENGINE_SUBSTITUTION';
}
return 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
}
|
Get the sql_mode value.
@param \PDO $connection
@param array $config
@return string|null
|
getSqlMode
|
php
|
illuminate/database
|
Connectors/MariaDbConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/MariaDbConnector.php
|
MIT
|
public function connect(array $config)
{
$dsn = $this->getDsn($config);
$options = $this->getOptions($config);
// We need to grab the PDO options that should be used while making the brand
// new connection instance. The PDO options control various aspects of the
// connection's behavior, and some might be specified by the developers.
$connection = $this->createConnection($dsn, $config, $options);
if (! empty($config['database']) &&
(! isset($config['use_db_after_connecting']) ||
$config['use_db_after_connecting'])) {
$connection->exec("use `{$config['database']}`;");
}
$this->configureConnection($connection, $config);
return $connection;
}
|
Establish a database connection.
@param array $config
@return \PDO
|
connect
|
php
|
illuminate/database
|
Connectors/MySqlConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/MySqlConnector.php
|
MIT
|
protected function getDsn(array $config)
{
return $this->hasSocket($config)
? $this->getSocketDsn($config)
: $this->getHostDsn($config);
}
|
Create a DSN string from a configuration.
Chooses socket or host/port based on the 'unix_socket' config value.
@param array $config
@return string
|
getDsn
|
php
|
illuminate/database
|
Connectors/MySqlConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/MySqlConnector.php
|
MIT
|
protected function hasSocket(array $config)
{
return isset($config['unix_socket']) && ! empty($config['unix_socket']);
}
|
Determine if the given configuration array has a UNIX socket value.
@param array $config
@return bool
|
hasSocket
|
php
|
illuminate/database
|
Connectors/MySqlConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/MySqlConnector.php
|
MIT
|
protected function getSocketDsn(array $config)
{
return "mysql:unix_socket={$config['unix_socket']};dbname={$config['database']}";
}
|
Get the DSN string for a socket configuration.
@param array $config
@return string
|
getSocketDsn
|
php
|
illuminate/database
|
Connectors/MySqlConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/MySqlConnector.php
|
MIT
|
protected function getHostDsn(array $config)
{
return isset($config['port'])
? "mysql:host={$config['host']};port={$config['port']};dbname={$config['database']}"
: "mysql:host={$config['host']};dbname={$config['database']}";
}
|
Get the DSN string for a host / port configuration.
@param array $config
@return string
|
getHostDsn
|
php
|
illuminate/database
|
Connectors/MySqlConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/MySqlConnector.php
|
MIT
|
protected function configureConnection(PDO $connection, array $config)
{
if (isset($config['isolation_level'])) {
$connection->exec(sprintf('SET SESSION TRANSACTION ISOLATION LEVEL %s;', $config['isolation_level']));
}
$statements = [];
if (isset($config['charset'])) {
if (isset($config['collation'])) {
$statements[] = sprintf("NAMES '%s' COLLATE '%s'", $config['charset'], $config['collation']);
} else {
$statements[] = sprintf("NAMES '%s'", $config['charset']);
}
}
if (isset($config['timezone'])) {
$statements[] = sprintf("time_zone='%s'", $config['timezone']);
}
$sqlMode = $this->getSqlMode($connection, $config);
if ($sqlMode !== null) {
$statements[] = sprintf("SESSION sql_mode='%s'", $sqlMode);
}
if ($statements !== []) {
$connection->exec(sprintf('SET %s;', implode(', ', $statements)));
}
}
|
Configure the given PDO connection.
@param \PDO $connection
@param array $config
@return void
|
configureConnection
|
php
|
illuminate/database
|
Connectors/MySqlConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/MySqlConnector.php
|
MIT
|
protected function getSqlMode(PDO $connection, array $config)
{
if (isset($config['modes'])) {
return implode(',', $config['modes']);
}
if (! isset($config['strict'])) {
return null;
}
if (! $config['strict']) {
return 'NO_ENGINE_SUBSTITUTION';
}
$version = $config['version'] ?? $connection->getAttribute(PDO::ATTR_SERVER_VERSION);
if (version_compare($version, '8.0.11') >= 0) {
return 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
}
return 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
}
|
Get the sql_mode value.
@param \PDO $connection
@param array $config
@return string|null
|
getSqlMode
|
php
|
illuminate/database
|
Connectors/MySqlConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/MySqlConnector.php
|
MIT
|
public function connect(array $config)
{
// First we'll create the basic DSN and connection instance connecting to the
// using the configuration option specified by the developer. We will also
// set the default character set on the connections to UTF-8 by default.
$connection = $this->createConnection(
$this->getDsn($config), $config, $this->getOptions($config)
);
$this->configureIsolationLevel($connection, $config);
// Next, we will check to see if a timezone has been specified in this config
// and if it has we will issue a statement to modify the timezone with the
// database. Setting this DB timezone is an optional configuration item.
$this->configureTimezone($connection, $config);
$this->configureSearchPath($connection, $config);
$this->configureSynchronousCommit($connection, $config);
return $connection;
}
|
Establish a database connection.
@param array $config
@return \PDO
|
connect
|
php
|
illuminate/database
|
Connectors/PostgresConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/PostgresConnector.php
|
MIT
|
protected function getDsn(array $config)
{
// First we will create the basic DSN setup as well as the port if it is in
// in the configuration options. This will give us the basic DSN we will
// need to establish the PDO connections and return them back for use.
extract($config, EXTR_SKIP);
$host = isset($host) ? "host={$host};" : '';
// Sometimes - users may need to connect to a database that has a different
// name than the database used for "information_schema" queries. This is
// typically the case if using "pgbouncer" type software when pooling.
$database = $connect_via_database ?? $database ?? null;
$port = $connect_via_port ?? $port ?? null;
$dsn = "pgsql:{$host}dbname='{$database}'";
// If a port was specified, we will add it to this Postgres DSN connections
// format. Once we have done that we are ready to return this connection
// string back out for usage, as this has been fully constructed here.
if (! is_null($port)) {
$dsn .= ";port={$port}";
}
if (isset($charset)) {
$dsn .= ";client_encoding='{$charset}'";
}
// Postgres allows an application_name to be set by the user and this name is
// used to when monitoring the application with pg_stat_activity. So we'll
// determine if the option has been specified and run a statement if so.
if (isset($application_name)) {
$dsn .= ";application_name='".str_replace("'", "\'", $application_name)."'";
}
return $this->addSslOptions($dsn, $config);
}
|
Create a DSN string from a configuration.
@param array $config
@return string
|
getDsn
|
php
|
illuminate/database
|
Connectors/PostgresConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/PostgresConnector.php
|
MIT
|
protected function addSslOptions($dsn, array $config)
{
foreach (['sslmode', 'sslcert', 'sslkey', 'sslrootcert'] as $option) {
if (isset($config[$option])) {
$dsn .= ";{$option}={$config[$option]}";
}
}
return $dsn;
}
|
Add the SSL options to the DSN.
@param string $dsn
@param array $config
@return string
|
addSslOptions
|
php
|
illuminate/database
|
Connectors/PostgresConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/PostgresConnector.php
|
MIT
|
protected function configureIsolationLevel($connection, array $config)
{
if (isset($config['isolation_level'])) {
$connection->prepare("set session characteristics as transaction isolation level {$config['isolation_level']}")->execute();
}
}
|
Set the connection transaction isolation level.
@param \PDO $connection
@param array $config
@return void
|
configureIsolationLevel
|
php
|
illuminate/database
|
Connectors/PostgresConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/PostgresConnector.php
|
MIT
|
protected function configureTimezone($connection, array $config)
{
if (isset($config['timezone'])) {
$timezone = $config['timezone'];
$connection->prepare("set time zone '{$timezone}'")->execute();
}
}
|
Set the timezone on the connection.
@param \PDO $connection
@param array $config
@return void
|
configureTimezone
|
php
|
illuminate/database
|
Connectors/PostgresConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/PostgresConnector.php
|
MIT
|
protected function configureSearchPath($connection, $config)
{
if (isset($config['search_path']) || isset($config['schema'])) {
$searchPath = $this->quoteSearchPath(
$this->parseSearchPath($config['search_path'] ?? $config['schema'])
);
$connection->prepare("set search_path to {$searchPath}")->execute();
}
}
|
Set the "search_path" on the database connection.
@param \PDO $connection
@param array $config
@return void
|
configureSearchPath
|
php
|
illuminate/database
|
Connectors/PostgresConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/PostgresConnector.php
|
MIT
|
protected function quoteSearchPath($searchPath)
{
return count($searchPath) === 1 ? '"'.$searchPath[0].'"' : '"'.implode('", "', $searchPath).'"';
}
|
Format the search path for the DSN.
@param array $searchPath
@return string
|
quoteSearchPath
|
php
|
illuminate/database
|
Connectors/PostgresConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/PostgresConnector.php
|
MIT
|
public function connect(array $config)
{
$options = $this->getOptions($config);
$path = $this->parseDatabasePath($config['database']);
$connection = $this->createConnection("sqlite:{$path}", $config, $options);
$this->configureForeignKeyConstraints($connection, $config);
$this->configureBusyTimeout($connection, $config);
$this->configureJournalMode($connection, $config);
$this->configureSynchronous($connection, $config);
return $connection;
}
|
Establish a database connection.
@param array $config
@return \PDO
|
connect
|
php
|
illuminate/database
|
Connectors/SQLiteConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/SQLiteConnector.php
|
MIT
|
protected function parseDatabasePath(string $path): string
{
$database = $path;
// SQLite supports "in-memory" databases that only last as long as the owning
// connection does. These are useful for tests or for short lifetime store
// querying. In-memory databases shall be anonymous (:memory:) or named.
if ($path === ':memory:' ||
str_contains($path, '?mode=memory') ||
str_contains($path, '&mode=memory')
) {
return $path;
}
$path = realpath($path) ?: realpath(base_path($path));
// Here we'll verify that the SQLite database exists before going any further
// as the developer probably wants to know if the database exists and this
// SQLite driver will not throw any exception if it does not by default.
if ($path === false) {
throw new SQLiteDatabaseDoesNotExistException($database);
}
return $path;
}
|
Get the absolute database path.
@param string $path
@return string
@throws \Illuminate\Database\SQLiteDatabaseDoesNotExistException
|
parseDatabasePath
|
php
|
illuminate/database
|
Connectors/SQLiteConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/SQLiteConnector.php
|
MIT
|
protected function configureForeignKeyConstraints($connection, array $config): void
{
if (! isset($config['foreign_key_constraints'])) {
return;
}
$foreignKeys = $config['foreign_key_constraints'] ? 1 : 0;
$connection->prepare("pragma foreign_keys = {$foreignKeys}")->execute();
}
|
Enable or disable foreign key constraints if configured.
@param \PDO $connection
@param array $config
@return void
|
configureForeignKeyConstraints
|
php
|
illuminate/database
|
Connectors/SQLiteConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/SQLiteConnector.php
|
MIT
|
protected function configureBusyTimeout($connection, array $config): void
{
if (! isset($config['busy_timeout'])) {
return;
}
$connection->prepare("pragma busy_timeout = {$config['busy_timeout']}")->execute();
}
|
Set the busy timeout if configured.
@param \PDO $connection
@param array $config
@return void
|
configureBusyTimeout
|
php
|
illuminate/database
|
Connectors/SQLiteConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/SQLiteConnector.php
|
MIT
|
protected function configureJournalMode($connection, array $config): void
{
if (! isset($config['journal_mode'])) {
return;
}
$connection->prepare("pragma journal_mode = {$config['journal_mode']}")->execute();
}
|
Set the journal mode if configured.
@param \PDO $connection
@param array $config
@return void
|
configureJournalMode
|
php
|
illuminate/database
|
Connectors/SQLiteConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/SQLiteConnector.php
|
MIT
|
protected function configureSynchronous($connection, array $config): void
{
if (! isset($config['synchronous'])) {
return;
}
$connection->prepare("pragma synchronous = {$config['synchronous']}")->execute();
}
|
Set the synchronous mode if configured.
@param \PDO $connection
@param array $config
@return void
|
configureSynchronous
|
php
|
illuminate/database
|
Connectors/SQLiteConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/SQLiteConnector.php
|
MIT
|
public function connect(array $config)
{
$options = $this->getOptions($config);
$connection = $this->createConnection($this->getDsn($config), $config, $options);
$this->configureIsolationLevel($connection, $config);
return $connection;
}
|
Establish a database connection.
@param array $config
@return \PDO
|
connect
|
php
|
illuminate/database
|
Connectors/SqlServerConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/SqlServerConnector.php
|
MIT
|
protected function configureIsolationLevel($connection, array $config)
{
if (! isset($config['isolation_level'])) {
return;
}
$connection->prepare(
"SET TRANSACTION ISOLATION LEVEL {$config['isolation_level']}"
)->execute();
}
|
Set the connection transaction isolation level.
https://learn.microsoft.com/en-us/sql/t-sql/statements/set-transaction-isolation-level-transact-sql
@param \PDO $connection
@param array $config
@return void
|
configureIsolationLevel
|
php
|
illuminate/database
|
Connectors/SqlServerConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/SqlServerConnector.php
|
MIT
|
protected function getDsn(array $config)
{
// First we will create the basic DSN setup as well as the port if it is in
// in the configuration options. This will give us the basic DSN we will
// need to establish the PDO connections and return them back for use.
if ($this->prefersOdbc($config)) {
return $this->getOdbcDsn($config);
}
if (in_array('sqlsrv', $this->getAvailableDrivers())) {
return $this->getSqlSrvDsn($config);
} else {
return $this->getDblibDsn($config);
}
}
|
Create a DSN string from a configuration.
@param array $config
@return string
|
getDsn
|
php
|
illuminate/database
|
Connectors/SqlServerConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/SqlServerConnector.php
|
MIT
|
protected function prefersOdbc(array $config)
{
return in_array('odbc', $this->getAvailableDrivers()) &&
($config['odbc'] ?? null) === true;
}
|
Determine if the database configuration prefers ODBC.
@param array $config
@return bool
|
prefersOdbc
|
php
|
illuminate/database
|
Connectors/SqlServerConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/SqlServerConnector.php
|
MIT
|
protected function getDblibDsn(array $config)
{
return $this->buildConnectString('dblib', array_merge([
'host' => $this->buildHostString($config, ':'),
'dbname' => $config['database'],
], Arr::only($config, ['appname', 'charset', 'version'])));
}
|
Get the DSN string for a DbLib connection.
@param array $config
@return string
|
getDblibDsn
|
php
|
illuminate/database
|
Connectors/SqlServerConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/SqlServerConnector.php
|
MIT
|
protected function getOdbcDsn(array $config)
{
return isset($config['odbc_datasource_name'])
? 'odbc:'.$config['odbc_datasource_name']
: '';
}
|
Get the DSN string for an ODBC connection.
@param array $config
@return string
|
getOdbcDsn
|
php
|
illuminate/database
|
Connectors/SqlServerConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/SqlServerConnector.php
|
MIT
|
protected function getSqlSrvDsn(array $config)
{
$arguments = [
'Server' => $this->buildHostString($config, ','),
];
if (isset($config['database'])) {
$arguments['Database'] = $config['database'];
}
if (isset($config['readonly'])) {
$arguments['ApplicationIntent'] = 'ReadOnly';
}
if (isset($config['pooling']) && $config['pooling'] === false) {
$arguments['ConnectionPooling'] = '0';
}
if (isset($config['appname'])) {
$arguments['APP'] = $config['appname'];
}
if (isset($config['encrypt'])) {
$arguments['Encrypt'] = $config['encrypt'];
}
if (isset($config['trust_server_certificate'])) {
$arguments['TrustServerCertificate'] = $config['trust_server_certificate'];
}
if (isset($config['multiple_active_result_sets']) && $config['multiple_active_result_sets'] === false) {
$arguments['MultipleActiveResultSets'] = 'false';
}
if (isset($config['transaction_isolation'])) {
$arguments['TransactionIsolation'] = $config['transaction_isolation'];
}
if (isset($config['multi_subnet_failover'])) {
$arguments['MultiSubnetFailover'] = $config['multi_subnet_failover'];
}
if (isset($config['column_encryption'])) {
$arguments['ColumnEncryption'] = $config['column_encryption'];
}
if (isset($config['key_store_authentication'])) {
$arguments['KeyStoreAuthentication'] = $config['key_store_authentication'];
}
if (isset($config['key_store_principal_id'])) {
$arguments['KeyStorePrincipalId'] = $config['key_store_principal_id'];
}
if (isset($config['key_store_secret'])) {
$arguments['KeyStoreSecret'] = $config['key_store_secret'];
}
if (isset($config['login_timeout'])) {
$arguments['LoginTimeout'] = $config['login_timeout'];
}
if (isset($config['authentication'])) {
$arguments['Authentication'] = $config['authentication'];
}
return $this->buildConnectString('sqlsrv', $arguments);
}
|
Get the DSN string for a SqlSrv connection.
@param array $config
@return string
|
getSqlSrvDsn
|
php
|
illuminate/database
|
Connectors/SqlServerConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/SqlServerConnector.php
|
MIT
|
protected function buildConnectString($driver, array $arguments)
{
return $driver.':'.implode(';', array_map(function ($key) use ($arguments) {
return sprintf('%s=%s', $key, $arguments[$key]);
}, array_keys($arguments)));
}
|
Build a connection string from the given arguments.
@param string $driver
@param array $arguments
@return string
|
buildConnectString
|
php
|
illuminate/database
|
Connectors/SqlServerConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/SqlServerConnector.php
|
MIT
|
protected function buildHostString(array $config, $separator)
{
if (empty($config['port'])) {
return $config['host'];
}
return $config['host'].$separator.$config['port'];
}
|
Build a host string from the given configuration.
@param array $config
@param string $separator
@return string
|
buildHostString
|
php
|
illuminate/database
|
Connectors/SqlServerConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/SqlServerConnector.php
|
MIT
|
protected function getAvailableDrivers()
{
return PDO::getAvailableDrivers();
}
|
Get the available PDO drivers.
@return array
|
getAvailableDrivers
|
php
|
illuminate/database
|
Connectors/SqlServerConnector.php
|
https://github.com/illuminate/database/blob/master/Connectors/SqlServerConnector.php
|
MIT
|
protected function getConnectionName(ConnectionInterface $connection, $database)
{
return $connection->getDriverTitle();
}
|
Get a human-readable name for the given connection.
@param \Illuminate\Database\ConnectionInterface $connection
@param string $database
@return string
@deprecated
|
getConnectionName
|
php
|
illuminate/database
|
Console/DatabaseInspectionCommand.php
|
https://github.com/illuminate/database/blob/master/Console/DatabaseInspectionCommand.php
|
MIT
|
protected function getConnectionCount(ConnectionInterface $connection)
{
return $connection->threadCount();
}
|
Get the number of open connections for a database.
@param \Illuminate\Database\ConnectionInterface $connection
@return int|null
@deprecated
|
getConnectionCount
|
php
|
illuminate/database
|
Console/DatabaseInspectionCommand.php
|
https://github.com/illuminate/database/blob/master/Console/DatabaseInspectionCommand.php
|
MIT
|
protected function getConfigFromDatabase($database)
{
$database ??= config('database.default');
return Arr::except(config('database.connections.'.$database), ['password']);
}
|
Get the connection configuration details for the given connection.
@param string|null $database
@return array
|
getConfigFromDatabase
|
php
|
illuminate/database
|
Console/DatabaseInspectionCommand.php
|
https://github.com/illuminate/database/blob/master/Console/DatabaseInspectionCommand.php
|
MIT
|
public function handle()
{
$connection = $this->getConnection();
if (! isset($connection['host']) && $connection['driver'] !== 'sqlite') {
$this->components->error('No host specified for this database connection.');
$this->line(' Use the <options=bold>[--read]</> and <options=bold>[--write]</> options to specify a read or write connection.');
$this->newLine();
return Command::FAILURE;
}
try {
(new Process(
array_merge([$command = $this->getCommand($connection)], $this->commandArguments($connection)),
null,
$this->commandEnvironment($connection)
))->setTimeout(null)->setTty(true)->mustRun(function ($type, $buffer) {
$this->output->write($buffer);
});
} catch (ProcessFailedException $e) {
throw_unless($e->getProcess()->getExitCode() === 127, $e);
$this->error("{$command} not found in path.");
return Command::FAILURE;
}
return 0;
}
|
Execute the console command.
@return int
|
handle
|
php
|
illuminate/database
|
Console/DbCommand.php
|
https://github.com/illuminate/database/blob/master/Console/DbCommand.php
|
MIT
|
public function getConnection()
{
$connection = $this->laravel['config']['database.connections.'.
(($db = $this->argument('connection')) ?? $this->laravel['config']['database.default'])
];
if (empty($connection)) {
throw new UnexpectedValueException("Invalid database connection [{$db}].");
}
if (! empty($connection['url'])) {
$connection = (new ConfigurationUrlParser)->parseConfiguration($connection);
}
if ($this->option('read')) {
if (is_array($connection['read']['host'])) {
$connection['read']['host'] = $connection['read']['host'][0];
}
$connection = array_merge($connection, $connection['read']);
} elseif ($this->option('write')) {
if (is_array($connection['write']['host'])) {
$connection['write']['host'] = $connection['write']['host'][0];
}
$connection = array_merge($connection, $connection['write']);
}
return $connection;
}
|
Get the database connection configuration.
@return array
@throws \UnexpectedValueException
|
getConnection
|
php
|
illuminate/database
|
Console/DbCommand.php
|
https://github.com/illuminate/database/blob/master/Console/DbCommand.php
|
MIT
|
public function commandArguments(array $connection)
{
$driver = ucfirst($connection['driver']);
return $this->{"get{$driver}Arguments"}($connection);
}
|
Get the arguments for the database client command.
@param array $connection
@return array
|
commandArguments
|
php
|
illuminate/database
|
Console/DbCommand.php
|
https://github.com/illuminate/database/blob/master/Console/DbCommand.php
|
MIT
|
public function commandEnvironment(array $connection)
{
$driver = ucfirst($connection['driver']);
if (method_exists($this, "get{$driver}Environment")) {
return $this->{"get{$driver}Environment"}($connection);
}
return null;
}
|
Get the environment variables for the database client command.
@param array $connection
@return array|null
|
commandEnvironment
|
php
|
illuminate/database
|
Console/DbCommand.php
|
https://github.com/illuminate/database/blob/master/Console/DbCommand.php
|
MIT
|
public function getCommand(array $connection)
{
return [
'mysql' => 'mysql',
'mariadb' => 'mariadb',
'pgsql' => 'psql',
'sqlite' => 'sqlite3',
'sqlsrv' => 'sqlcmd',
][$connection['driver']];
}
|
Get the database client command to run.
@param array $connection
@return string
|
getCommand
|
php
|
illuminate/database
|
Console/DbCommand.php
|
https://github.com/illuminate/database/blob/master/Console/DbCommand.php
|
MIT
|
protected function getMysqlArguments(array $connection)
{
$optionalArguments = [
'password' => '--password='.$connection['password'],
'unix_socket' => '--socket='.($connection['unix_socket'] ?? ''),
'charset' => '--default-character-set='.($connection['charset'] ?? ''),
];
if (! $connection['password']) {
unset($optionalArguments['password']);
}
return array_merge([
'--host='.$connection['host'],
'--port='.$connection['port'],
'--user='.$connection['username'],
], $this->getOptionalArguments($optionalArguments, $connection), [$connection['database']]);
}
|
Get the arguments for the MySQL CLI.
@param array $connection
@return array
|
getMysqlArguments
|
php
|
illuminate/database
|
Console/DbCommand.php
|
https://github.com/illuminate/database/blob/master/Console/DbCommand.php
|
MIT
|
protected function getMariaDbArguments(array $connection)
{
return $this->getMysqlArguments($connection);
}
|
Get the arguments for the MariaDB CLI.
@param array $connection
@return array
|
getMariaDbArguments
|
php
|
illuminate/database
|
Console/DbCommand.php
|
https://github.com/illuminate/database/blob/master/Console/DbCommand.php
|
MIT
|
protected function getPgsqlArguments(array $connection)
{
return [$connection['database']];
}
|
Get the arguments for the Postgres CLI.
@param array $connection
@return array
|
getPgsqlArguments
|
php
|
illuminate/database
|
Console/DbCommand.php
|
https://github.com/illuminate/database/blob/master/Console/DbCommand.php
|
MIT
|
protected function getSqliteArguments(array $connection)
{
return [$connection['database']];
}
|
Get the arguments for the SQLite CLI.
@param array $connection
@return array
|
getSqliteArguments
|
php
|
illuminate/database
|
Console/DbCommand.php
|
https://github.com/illuminate/database/blob/master/Console/DbCommand.php
|
MIT
|
protected function getSqlsrvArguments(array $connection)
{
return array_merge(...$this->getOptionalArguments([
'database' => ['-d', $connection['database']],
'username' => ['-U', $connection['username']],
'password' => ['-P', $connection['password']],
'host' => ['-S', 'tcp:'.$connection['host']
.($connection['port'] ? ','.$connection['port'] : ''), ],
'trust_server_certificate' => ['-C'],
], $connection));
}
|
Get the arguments for the SQL Server CLI.
@param array $connection
@return array
|
getSqlsrvArguments
|
php
|
illuminate/database
|
Console/DbCommand.php
|
https://github.com/illuminate/database/blob/master/Console/DbCommand.php
|
MIT
|
protected function getPgsqlEnvironment(array $connection)
{
return array_merge(...$this->getOptionalArguments([
'username' => ['PGUSER' => $connection['username']],
'host' => ['PGHOST' => $connection['host']],
'port' => ['PGPORT' => $connection['port']],
'password' => ['PGPASSWORD' => $connection['password']],
], $connection));
}
|
Get the environment variables for the Postgres CLI.
@param array $connection
@return array|null
|
getPgsqlEnvironment
|
php
|
illuminate/database
|
Console/DbCommand.php
|
https://github.com/illuminate/database/blob/master/Console/DbCommand.php
|
MIT
|
protected function getOptionalArguments(array $args, array $connection)
{
return array_values(array_filter($args, function ($key) use ($connection) {
return ! empty($connection[$key]);
}, ARRAY_FILTER_USE_KEY));
}
|
Get the optional arguments based on the connection configuration.
@param array $args
@param array $connection
@return array
|
getOptionalArguments
|
php
|
illuminate/database
|
Console/DbCommand.php
|
https://github.com/illuminate/database/blob/master/Console/DbCommand.php
|
MIT
|
public function handle(ConnectionResolverInterface $connections, Dispatcher $dispatcher)
{
$connection = $connections->connection($database = $this->input->getOption('database'));
$this->schemaState($connection)->dump(
$connection, $path = $this->path($connection)
);
$dispatcher->dispatch(new SchemaDumped($connection, $path));
$info = 'Database schema dumped';
if ($this->option('prune')) {
(new Filesystem)->deleteDirectory(
$path = database_path('migrations'), preserve: false
);
$info .= ' and pruned';
$dispatcher->dispatch(new MigrationsPruned($connection, $path));
}
$this->components->info($info.' successfully.');
}
|
Execute the console command.
@param \Illuminate\Database\ConnectionResolverInterface $connections
@param \Illuminate\Contracts\Events\Dispatcher $dispatcher
@return void
|
handle
|
php
|
illuminate/database
|
Console/DumpCommand.php
|
https://github.com/illuminate/database/blob/master/Console/DumpCommand.php
|
MIT
|
protected function schemaState(Connection $connection)
{
$migrations = Config::get('database.migrations', 'migrations');
$migrationTable = is_array($migrations) ? ($migrations['table'] ?? 'migrations') : $migrations;
return $connection->getSchemaState()
->withMigrationTable($migrationTable)
->handleOutputUsing(function ($type, $buffer) {
$this->output->write($buffer);
});
}
|
Create a schema state instance for the given connection.
@param \Illuminate\Database\Connection $connection
@return mixed
|
schemaState
|
php
|
illuminate/database
|
Console/DumpCommand.php
|
https://github.com/illuminate/database/blob/master/Console/DumpCommand.php
|
MIT
|
protected function path(Connection $connection)
{
return tap($this->option('path') ?: database_path('schema/'.$connection->getName().'-schema.sql'), function ($path) {
(new Filesystem)->ensureDirectoryExists(dirname($path));
});
}
|
Get the path that the dump should be written to.
@param \Illuminate\Database\Connection $connection
|
path
|
php
|
illuminate/database
|
Console/DumpCommand.php
|
https://github.com/illuminate/database/blob/master/Console/DumpCommand.php
|
MIT
|
public function __construct(ConnectionResolverInterface $connection, Dispatcher $events)
{
parent::__construct();
$this->connection = $connection;
$this->events = $events;
}
|
Create a new command instance.
@param \Illuminate\Database\ConnectionResolverInterface $connection
@param \Illuminate\Contracts\Events\Dispatcher $events
|
__construct
|
php
|
illuminate/database
|
Console/MonitorCommand.php
|
https://github.com/illuminate/database/blob/master/Console/MonitorCommand.php
|
MIT
|
public function handle()
{
$databases = $this->parseDatabases($this->option('databases'));
$this->displayConnections($databases);
if ($this->option('max')) {
$this->dispatchEvents($databases);
}
}
|
Execute the console command.
@return void
|
handle
|
php
|
illuminate/database
|
Console/MonitorCommand.php
|
https://github.com/illuminate/database/blob/master/Console/MonitorCommand.php
|
MIT
|
protected function parseDatabases($databases)
{
return (new Collection(explode(',', $databases)))->map(function ($database) {
if (! $database) {
$database = $this->laravel['config']['database.default'];
}
$maxConnections = $this->option('max');
$connections = $this->connection->connection($database)->threadCount();
return [
'database' => $database,
'connections' => $connections,
'status' => $maxConnections && $connections >= $maxConnections ? '<fg=yellow;options=bold>ALERT</>' : '<fg=green;options=bold>OK</>',
];
});
}
|
Parse the database into an array of the connections.
@param string $databases
@return \Illuminate\Support\Collection
|
parseDatabases
|
php
|
illuminate/database
|
Console/MonitorCommand.php
|
https://github.com/illuminate/database/blob/master/Console/MonitorCommand.php
|
MIT
|
protected function displayConnections($databases)
{
$this->newLine();
$this->components->twoColumnDetail('<fg=gray>Database name</>', '<fg=gray>Connections</>');
$databases->each(function ($database) {
$status = '['.$database['connections'].'] '.$database['status'];
$this->components->twoColumnDetail($database['database'], $status);
});
$this->newLine();
}
|
Display the databases and their connection counts in the console.
@param \Illuminate\Support\Collection $databases
@return void
|
displayConnections
|
php
|
illuminate/database
|
Console/MonitorCommand.php
|
https://github.com/illuminate/database/blob/master/Console/MonitorCommand.php
|
MIT
|
protected function dispatchEvents($databases)
{
$databases->each(function ($database) {
if ($database['status'] === '<fg=green;options=bold>OK</>') {
return;
}
$this->events->dispatch(
new DatabaseBusy(
$database['database'],
$database['connections']
)
);
});
}
|
Dispatch the database monitoring events.
@param \Illuminate\Support\Collection $databases
@return void
|
dispatchEvents
|
php
|
illuminate/database
|
Console/MonitorCommand.php
|
https://github.com/illuminate/database/blob/master/Console/MonitorCommand.php
|
MIT
|
public function handle(Dispatcher $events)
{
$models = $this->models();
if ($models->isEmpty()) {
$this->components->info('No prunable models found.');
return;
}
if ($this->option('pretend')) {
$models->each(function ($model) {
$this->pretendToPrune($model);
});
return;
}
$pruning = [];
$events->listen(ModelsPruned::class, function ($event) use (&$pruning) {
if (! in_array($event->model, $pruning)) {
$pruning[] = $event->model;
$this->newLine();
$this->components->info(sprintf('Pruning [%s] records.', $event->model));
}
$this->components->twoColumnDetail($event->model, "{$event->count} records");
});
$events->dispatch(new ModelPruningStarting($models->all()));
$models->each(function ($model) {
$this->pruneModel($model);
});
$events->dispatch(new ModelPruningFinished($models->all()));
$events->forget(ModelsPruned::class);
}
|
Execute the console command.
@param \Illuminate\Contracts\Events\Dispatcher $events
@return void
|
handle
|
php
|
illuminate/database
|
Console/PruneCommand.php
|
https://github.com/illuminate/database/blob/master/Console/PruneCommand.php
|
MIT
|
protected function pruneModel(string $model)
{
$instance = new $model;
$chunkSize = property_exists($instance, 'prunableChunkSize')
? $instance->prunableChunkSize
: $this->option('chunk');
$total = $this->isPrunable($model)
? $instance->pruneAll($chunkSize)
: 0;
if ($total == 0) {
$this->components->info("No prunable [$model] records found.");
}
}
|
Prune the given model.
@param string $model
@return void
|
pruneModel
|
php
|
illuminate/database
|
Console/PruneCommand.php
|
https://github.com/illuminate/database/blob/master/Console/PruneCommand.php
|
MIT
|
protected function models()
{
if (! empty($models = $this->option('model'))) {
return (new Collection($models))->filter(function ($model) {
return class_exists($model);
})->values();
}
$except = $this->option('except');
if (! empty($models) && ! empty($except)) {
throw new InvalidArgumentException('The --models and --except options cannot be combined.');
}
return (new Collection(Finder::create()->in($this->getPath())->files()->name('*.php')))
->map(function ($model) {
$namespace = $this->laravel->getNamespace();
return $namespace.str_replace(
['/', '.php'],
['\\', ''],
Str::after($model->getRealPath(), realpath(app_path()).DIRECTORY_SEPARATOR)
);
})
->when(! empty($except), fn ($models) => $models->reject(fn ($model) => in_array($model, $except)))
->filter(fn ($model) => class_exists($model))
->filter(fn ($model) => $this->isPrunable($model))
->values();
}
|
Determine the models that should be pruned.
@return \Illuminate\Support\Collection
|
models
|
php
|
illuminate/database
|
Console/PruneCommand.php
|
https://github.com/illuminate/database/blob/master/Console/PruneCommand.php
|
MIT
|
protected function getPath()
{
if (! empty($path = $this->option('path'))) {
return (new Collection($path))
->map(fn ($path) => base_path($path))
->all();
}
return app_path('Models');
}
|
Get the path where models are located.
@return string[]|string
|
getPath
|
php
|
illuminate/database
|
Console/PruneCommand.php
|
https://github.com/illuminate/database/blob/master/Console/PruneCommand.php
|
MIT
|
protected function isPrunable($model)
{
$uses = class_uses_recursive($model);
return in_array(Prunable::class, $uses) || in_array(MassPrunable::class, $uses);
}
|
Determine if the given model class is prunable.
@param string $model
@return bool
|
isPrunable
|
php
|
illuminate/database
|
Console/PruneCommand.php
|
https://github.com/illuminate/database/blob/master/Console/PruneCommand.php
|
MIT
|
protected function pretendToPrune($model)
{
$instance = new $model;
$count = $instance->prunable()
->when(in_array(SoftDeletes::class, class_uses_recursive(get_class($instance))), function ($query) {
$query->withTrashed();
})->count();
if ($count === 0) {
$this->components->info("No prunable [$model] records found.");
} else {
$this->components->info("{$count} [{$model}] records will be pruned.");
}
}
|
Display how many models will be pruned.
@param string $model
@return void
|
pretendToPrune
|
php
|
illuminate/database
|
Console/PruneCommand.php
|
https://github.com/illuminate/database/blob/master/Console/PruneCommand.php
|
MIT
|
public function handle(ConnectionResolverInterface $connections)
{
$connection = $connections->connection($database = $this->input->getOption('database'));
$schema = $connection->getSchemaBuilder();
$data = [
'platform' => [
'config' => $this->getConfigFromDatabase($database),
'name' => $connection->getDriverTitle(),
'connection' => $connection->getName(),
'version' => $connection->getServerVersion(),
'open_connections' => $connection->threadCount(),
],
'tables' => $this->tables($connection, $schema),
];
if ($this->option('views')) {
$data['views'] = $this->views($connection, $schema);
}
if ($this->option('types')) {
$data['types'] = $this->types($connection, $schema);
}
$this->display($data);
return 0;
}
|
Execute the console command.
@param \Illuminate\Database\ConnectionResolverInterface $connections
@return int
|
handle
|
php
|
illuminate/database
|
Console/ShowCommand.php
|
https://github.com/illuminate/database/blob/master/Console/ShowCommand.php
|
MIT
|
protected function tables(ConnectionInterface $connection, Builder $schema)
{
return (new Collection($schema->getTables()))->map(fn ($table) => [
'table' => $table['name'],
'schema' => $table['schema'],
'schema_qualified_name' => $table['schema_qualified_name'],
'size' => $table['size'],
'rows' => $this->option('counts')
? $connection->withoutTablePrefix(fn ($connection) => $connection->table($table['schema_qualified_name'])->count())
: null,
'engine' => $table['engine'],
'collation' => $table['collation'],
'comment' => $table['comment'],
]);
}
|
Get information regarding the tables within the database.
@param \Illuminate\Database\ConnectionInterface $connection
@param \Illuminate\Database\Schema\Builder $schema
@return \Illuminate\Support\Collection
|
tables
|
php
|
illuminate/database
|
Console/ShowCommand.php
|
https://github.com/illuminate/database/blob/master/Console/ShowCommand.php
|
MIT
|
protected function views(ConnectionInterface $connection, Builder $schema)
{
return (new Collection($schema->getViews()))
->map(fn ($view) => [
'view' => $view['name'],
'schema' => $view['schema'],
'rows' => $connection->withoutTablePrefix(fn ($connection) => $connection->table($view['schema_qualified_name'])->count()),
]);
}
|
Get information regarding the views within the database.
@param \Illuminate\Database\ConnectionInterface $connection
@param \Illuminate\Database\Schema\Builder $schema
@return \Illuminate\Support\Collection
|
views
|
php
|
illuminate/database
|
Console/ShowCommand.php
|
https://github.com/illuminate/database/blob/master/Console/ShowCommand.php
|
MIT
|
protected function types(ConnectionInterface $connection, Builder $schema)
{
return (new Collection($schema->getTypes()))
->map(fn ($type) => [
'name' => $type['name'],
'schema' => $type['schema'],
'type' => $type['type'],
'category' => $type['category'],
]);
}
|
Get information regarding the user-defined types within the database.
@param \Illuminate\Database\ConnectionInterface $connection
@param \Illuminate\Database\Schema\Builder $schema
@return \Illuminate\Support\Collection
|
types
|
php
|
illuminate/database
|
Console/ShowCommand.php
|
https://github.com/illuminate/database/blob/master/Console/ShowCommand.php
|
MIT
|
protected function display(array $data)
{
$this->option('json') ? $this->displayJson($data) : $this->displayForCli($data);
}
|
Render the database information.
@param array $data
@return void
|
display
|
php
|
illuminate/database
|
Console/ShowCommand.php
|
https://github.com/illuminate/database/blob/master/Console/ShowCommand.php
|
MIT
|
protected function displayJson(array $data)
{
$this->output->writeln(json_encode($data));
}
|
Render the database information as JSON.
@param array $data
@return void
|
displayJson
|
php
|
illuminate/database
|
Console/ShowCommand.php
|
https://github.com/illuminate/database/blob/master/Console/ShowCommand.php
|
MIT
|
public function handle(ModelInspector $modelInspector)
{
try {
$info = $modelInspector->inspect(
$this->argument('model'),
$this->option('database')
);
} catch (BindingResolutionException $e) {
$this->components->error($e->getMessage());
return 1;
}
$this->display(
$info['class'],
$info['database'],
$info['table'],
$info['policy'],
$info['attributes'],
$info['relations'],
$info['events'],
$info['observers']
);
return 0;
}
|
Execute the console command.
@return int
|
handle
|
php
|
illuminate/database
|
Console/ShowModelCommand.php
|
https://github.com/illuminate/database/blob/master/Console/ShowModelCommand.php
|
MIT
|
protected function display($class, $database, $table, $policy, $attributes, $relations, $events, $observers)
{
$this->option('json')
? $this->displayJson($class, $database, $table, $policy, $attributes, $relations, $events, $observers)
: $this->displayCli($class, $database, $table, $policy, $attributes, $relations, $events, $observers);
}
|
Render the model information.
@param class-string<\Illuminate\Database\Eloquent\Model> $class
@param string $database
@param string $table
@param class-string|null $policy
@param \Illuminate\Support\Collection $attributes
@param \Illuminate\Support\Collection $relations
@param \Illuminate\Support\Collection $events
@param \Illuminate\Support\Collection $observers
@return void
|
display
|
php
|
illuminate/database
|
Console/ShowModelCommand.php
|
https://github.com/illuminate/database/blob/master/Console/ShowModelCommand.php
|
MIT
|
protected function displayJson($class, $database, $table, $policy, $attributes, $relations, $events, $observers)
{
$this->output->writeln(
(new Collection([
'class' => $class,
'database' => $database,
'table' => $table,
'policy' => $policy,
'attributes' => $attributes,
'relations' => $relations,
'events' => $events,
'observers' => $observers,
]))->toJson()
);
}
|
Render the model information as JSON.
@param class-string<\Illuminate\Database\Eloquent\Model> $class
@param string $database
@param string $table
@param class-string|null $policy
@param \Illuminate\Support\Collection $attributes
@param \Illuminate\Support\Collection $relations
@param \Illuminate\Support\Collection $events
@param \Illuminate\Support\Collection $observers
@return void
|
displayJson
|
php
|
illuminate/database
|
Console/ShowModelCommand.php
|
https://github.com/illuminate/database/blob/master/Console/ShowModelCommand.php
|
MIT
|
protected function displayCli($class, $database, $table, $policy, $attributes, $relations, $events, $observers)
{
$this->newLine();
$this->components->twoColumnDetail('<fg=green;options=bold>'.$class.'</>');
$this->components->twoColumnDetail('Database', $database);
$this->components->twoColumnDetail('Table', $table);
if ($policy) {
$this->components->twoColumnDetail('Policy', $policy);
}
$this->newLine();
$this->components->twoColumnDetail(
'<fg=green;options=bold>Attributes</>',
'type <fg=gray>/</> <fg=yellow;options=bold>cast</>',
);
foreach ($attributes as $attribute) {
$first = trim(sprintf(
'%s %s',
$attribute['name'],
(new Collection(['increments', 'unique', 'nullable', 'fillable', 'hidden', 'appended']))
->filter(fn ($property) => $attribute[$property])
->map(fn ($property) => sprintf('<fg=gray>%s</>', $property))
->implode('<fg=gray>,</> ')
));
$second = (new Collection([
$attribute['type'],
$attribute['cast'] ? '<fg=yellow;options=bold>'.$attribute['cast'].'</>' : null,
]))->filter()->implode(' <fg=gray>/</> ');
$this->components->twoColumnDetail($first, $second);
if ($attribute['default'] !== null) {
$this->components->bulletList(
[sprintf('default: %s', $attribute['default'])],
OutputInterface::VERBOSITY_VERBOSE
);
}
}
$this->newLine();
$this->components->twoColumnDetail('<fg=green;options=bold>Relations</>');
foreach ($relations as $relation) {
$this->components->twoColumnDetail(
sprintf('%s <fg=gray>%s</>', $relation['name'], $relation['type']),
$relation['related']
);
}
$this->newLine();
$this->components->twoColumnDetail('<fg=green;options=bold>Events</>');
if ($events->count()) {
foreach ($events as $event) {
$this->components->twoColumnDetail(
sprintf('%s', $event['event']),
sprintf('%s', $event['class']),
);
}
}
$this->newLine();
$this->components->twoColumnDetail('<fg=green;options=bold>Observers</>');
if ($observers->count()) {
foreach ($observers as $observer) {
$this->components->twoColumnDetail(
sprintf('%s', $observer['event']),
implode(', ', $observer['observer'])
);
}
}
$this->newLine();
}
|
Render the model information for the CLI.
@param class-string<\Illuminate\Database\Eloquent\Model> $class
@param string $database
@param string $table
@param class-string|null $policy
@param \Illuminate\Support\Collection $attributes
@param \Illuminate\Support\Collection $relations
@param \Illuminate\Support\Collection $events
@param \Illuminate\Support\Collection $observers
@return void
|
displayCli
|
php
|
illuminate/database
|
Console/ShowModelCommand.php
|
https://github.com/illuminate/database/blob/master/Console/ShowModelCommand.php
|
MIT
|
public function handle(ConnectionResolverInterface $connections)
{
$connection = $connections->connection($this->input->getOption('database'));
$tables = (new Collection($connection->getSchemaBuilder()->getTables()))
->keyBy('schema_qualified_name')->all();
$tableName = $this->argument('table') ?: select(
'Which table would you like to inspect?',
array_keys($tables)
);
$table = $tables[$tableName] ?? Arr::first($tables, fn ($table) => $table['name'] === $tableName);
if (! $table) {
$this->components->warn("Table [{$tableName}] doesn't exist.");
return 1;
}
[$columns, $indexes, $foreignKeys] = $connection->withoutTablePrefix(function ($connection) use ($table) {
$schema = $connection->getSchemaBuilder();
$tableName = $table['schema_qualified_name'];
return [
$this->columns($schema, $tableName),
$this->indexes($schema, $tableName),
$this->foreignKeys($schema, $tableName),
];
});
$data = [
'table' => [
'schema' => $table['schema'],
'name' => $table['name'],
'schema_qualified_name' => $table['schema_qualified_name'],
'columns' => count($columns),
'size' => $table['size'],
'comment' => $table['comment'],
'collation' => $table['collation'],
'engine' => $table['engine'],
],
'columns' => $columns,
'indexes' => $indexes,
'foreign_keys' => $foreignKeys,
];
$this->display($data);
return 0;
}
|
Execute the console command.
@return int
|
handle
|
php
|
illuminate/database
|
Console/TableCommand.php
|
https://github.com/illuminate/database/blob/master/Console/TableCommand.php
|
MIT
|
protected function columns(Builder $schema, string $table)
{
return (new Collection($schema->getColumns($table)))->map(fn ($column) => [
'column' => $column['name'],
'attributes' => $this->getAttributesForColumn($column),
'default' => $column['default'],
'type' => $column['type'],
]);
}
|
Get the information regarding the table's columns.
@param \Illuminate\Database\Schema\Builder $schema
@param string $table
@return \Illuminate\Support\Collection
|
columns
|
php
|
illuminate/database
|
Console/TableCommand.php
|
https://github.com/illuminate/database/blob/master/Console/TableCommand.php
|
MIT
|
protected function getAttributesForColumn($column)
{
return (new Collection([
$column['type_name'],
$column['generation'] ? $column['generation']['type'] : null,
$column['auto_increment'] ? 'autoincrement' : null,
$column['nullable'] ? 'nullable' : null,
$column['collation'],
]))->filter();
}
|
Get the attributes for a table column.
@param array $column
@return \Illuminate\Support\Collection
|
getAttributesForColumn
|
php
|
illuminate/database
|
Console/TableCommand.php
|
https://github.com/illuminate/database/blob/master/Console/TableCommand.php
|
MIT
|
protected function indexes(Builder $schema, string $table)
{
return (new Collection($schema->getIndexes($table)))->map(fn ($index) => [
'name' => $index['name'],
'columns' => new Collection($index['columns']),
'attributes' => $this->getAttributesForIndex($index),
]);
}
|
Get the information regarding the table's indexes.
@param \Illuminate\Database\Schema\Builder $schema
@param string $table
@return \Illuminate\Support\Collection
|
indexes
|
php
|
illuminate/database
|
Console/TableCommand.php
|
https://github.com/illuminate/database/blob/master/Console/TableCommand.php
|
MIT
|
protected function getAttributesForIndex($index)
{
return (new Collection([
$index['type'],
count($index['columns']) > 1 ? 'compound' : null,
$index['unique'] && ! $index['primary'] ? 'unique' : null,
$index['primary'] ? 'primary' : null,
]))->filter();
}
|
Get the attributes for a table index.
@param array $index
@return \Illuminate\Support\Collection
|
getAttributesForIndex
|
php
|
illuminate/database
|
Console/TableCommand.php
|
https://github.com/illuminate/database/blob/master/Console/TableCommand.php
|
MIT
|
protected function foreignKeys(Builder $schema, string $table)
{
return (new Collection($schema->getForeignKeys($table)))->map(fn ($foreignKey) => [
'name' => $foreignKey['name'],
'columns' => new Collection($foreignKey['columns']),
'foreign_schema' => $foreignKey['foreign_schema'],
'foreign_table' => $foreignKey['foreign_table'],
'foreign_columns' => new Collection($foreignKey['foreign_columns']),
'on_update' => $foreignKey['on_update'],
'on_delete' => $foreignKey['on_delete'],
]);
}
|
Get the information regarding the table's foreign keys.
@param \Illuminate\Database\Schema\Builder $schema
@param string $table
@return \Illuminate\Support\Collection
|
foreignKeys
|
php
|
illuminate/database
|
Console/TableCommand.php
|
https://github.com/illuminate/database/blob/master/Console/TableCommand.php
|
MIT
|
protected function display(array $data)
{
$this->option('json') ? $this->displayJson($data) : $this->displayForCli($data);
}
|
Render the table information.
@param array $data
@return void
|
display
|
php
|
illuminate/database
|
Console/TableCommand.php
|
https://github.com/illuminate/database/blob/master/Console/TableCommand.php
|
MIT
|
protected function displayJson(array $data)
{
$this->output->writeln(json_encode($data));
}
|
Render the table information as JSON.
@param array $data
@return void
|
displayJson
|
php
|
illuminate/database
|
Console/TableCommand.php
|
https://github.com/illuminate/database/blob/master/Console/TableCommand.php
|
MIT
|
protected function displayForCli(array $data)
{
[$table, $columns, $indexes, $foreignKeys] = [
$data['table'], $data['columns'], $data['indexes'], $data['foreign_keys'],
];
$this->newLine();
$this->components->twoColumnDetail('<fg=green;options=bold>'.$table['schema_qualified_name'].'</>', $table['comment'] ? '<fg=gray>'.$table['comment'].'</>' : null);
$this->components->twoColumnDetail('Columns', $table['columns']);
if (! is_null($table['size'])) {
$this->components->twoColumnDetail('Size', Number::fileSize($table['size'], 2));
}
if ($table['engine']) {
$this->components->twoColumnDetail('Engine', $table['engine']);
}
if ($table['collation']) {
$this->components->twoColumnDetail('Collation', $table['collation']);
}
$this->newLine();
if ($columns->isNotEmpty()) {
$this->components->twoColumnDetail('<fg=green;options=bold>Column</>', 'Type');
$columns->each(function ($column) {
$this->components->twoColumnDetail(
$column['column'].' <fg=gray>'.$column['attributes']->implode(', ').'</>',
(! is_null($column['default']) ? '<fg=gray>'.$column['default'].'</> ' : '').$column['type']
);
});
$this->newLine();
}
if ($indexes->isNotEmpty()) {
$this->components->twoColumnDetail('<fg=green;options=bold>Index</>');
$indexes->each(function ($index) {
$this->components->twoColumnDetail(
$index['name'].' <fg=gray>'.$index['columns']->implode(', ').'</>',
$index['attributes']->implode(', ')
);
});
$this->newLine();
}
if ($foreignKeys->isNotEmpty()) {
$this->components->twoColumnDetail('<fg=green;options=bold>Foreign Key</>', 'On Update / On Delete');
$foreignKeys->each(function ($foreignKey) {
$this->components->twoColumnDetail(
$foreignKey['name'].' <fg=gray;options=bold>'.$foreignKey['columns']->implode(', ').' references '.$foreignKey['foreign_columns']->implode(', ').' on '.$foreignKey['foreign_table'].'</>',
$foreignKey['on_update'].' / '.$foreignKey['on_delete'],
);
});
$this->newLine();
}
}
|
Render the table information formatted for the CLI.
@param array $data
@return void
|
displayForCli
|
php
|
illuminate/database
|
Console/TableCommand.php
|
https://github.com/illuminate/database/blob/master/Console/TableCommand.php
|
MIT
|
public function handle()
{
if ($this->isProhibited() ||
! $this->confirmToProceed()) {
return Command::FAILURE;
}
$database = $this->input->getOption('database');
if ($this->option('drop-views')) {
$this->dropAllViews($database);
$this->components->info('Dropped all views successfully.');
}
$this->dropAllTables($database);
$this->components->info('Dropped all tables successfully.');
if ($this->option('drop-types')) {
$this->dropAllTypes($database);
$this->components->info('Dropped all types successfully.');
}
return 0;
}
|
Execute the console command.
@return int
|
handle
|
php
|
illuminate/database
|
Console/WipeCommand.php
|
https://github.com/illuminate/database/blob/master/Console/WipeCommand.php
|
MIT
|
protected function dropAllTables($database)
{
$this->laravel['db']->connection($database)
->getSchemaBuilder()
->dropAllTables();
}
|
Drop all of the database tables.
@param string $database
@return void
|
dropAllTables
|
php
|
illuminate/database
|
Console/WipeCommand.php
|
https://github.com/illuminate/database/blob/master/Console/WipeCommand.php
|
MIT
|
protected function dropAllViews($database)
{
$this->laravel['db']->connection($database)
->getSchemaBuilder()
->dropAllViews();
}
|
Drop all of the database views.
@param string $database
@return void
|
dropAllViews
|
php
|
illuminate/database
|
Console/WipeCommand.php
|
https://github.com/illuminate/database/blob/master/Console/WipeCommand.php
|
MIT
|
protected function dropAllTypes($database)
{
$this->laravel['db']->connection($database)
->getSchemaBuilder()
->dropAllTypes();
}
|
Drop all of the database types.
@param string $database
@return void
|
dropAllTypes
|
php
|
illuminate/database
|
Console/WipeCommand.php
|
https://github.com/illuminate/database/blob/master/Console/WipeCommand.php
|
MIT
|
protected function getOptions()
{
return [
['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to use'],
['drop-views', null, InputOption::VALUE_NONE, 'Drop all tables and views'],
['drop-types', null, InputOption::VALUE_NONE, 'Drop all tables and types (Postgres only)'],
['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production'],
];
}
|
Get the console command options.
@return array
|
getOptions
|
php
|
illuminate/database
|
Console/WipeCommand.php
|
https://github.com/illuminate/database/blob/master/Console/WipeCommand.php
|
MIT
|
protected function getStub()
{
return $this->resolveStubPath('/stubs/factory.stub');
}
|
Get the stub file for the generator.
@return string
|
getStub
|
php
|
illuminate/database
|
Console/Factories/FactoryMakeCommand.php
|
https://github.com/illuminate/database/blob/master/Console/Factories/FactoryMakeCommand.php
|
MIT
|
protected function resolveStubPath($stub)
{
return file_exists($customPath = $this->laravel->basePath(trim($stub, '/')))
? $customPath
: __DIR__.$stub;
}
|
Resolve the fully-qualified path to the stub.
@param string $stub
@return string
|
resolveStubPath
|
php
|
illuminate/database
|
Console/Factories/FactoryMakeCommand.php
|
https://github.com/illuminate/database/blob/master/Console/Factories/FactoryMakeCommand.php
|
MIT
|
protected function buildClass($name)
{
$factory = class_basename(Str::ucfirst(str_replace('Factory', '', $name)));
$namespaceModel = $this->option('model')
? $this->qualifyModel($this->option('model'))
: $this->qualifyModel($this->guessModelName($name));
$model = class_basename($namespaceModel);
$namespace = $this->getNamespace(
Str::replaceFirst($this->rootNamespace(), 'Database\\Factories\\', $this->qualifyClass($this->getNameInput()))
);
$replace = [
'{{ factoryNamespace }}' => $namespace,
'NamespacedDummyModel' => $namespaceModel,
'{{ namespacedModel }}' => $namespaceModel,
'{{namespacedModel}}' => $namespaceModel,
'DummyModel' => $model,
'{{ model }}' => $model,
'{{model}}' => $model,
'{{ factory }}' => $factory,
'{{factory}}' => $factory,
];
return str_replace(
array_keys($replace), array_values($replace), parent::buildClass($name)
);
}
|
Build the class with the given name.
@param string $name
@return string
|
buildClass
|
php
|
illuminate/database
|
Console/Factories/FactoryMakeCommand.php
|
https://github.com/illuminate/database/blob/master/Console/Factories/FactoryMakeCommand.php
|
MIT
|
protected function getPath($name)
{
$name = (new Stringable($name))->replaceFirst($this->rootNamespace(), '')->finish('Factory')->value();
return $this->laravel->databasePath().'/factories/'.str_replace('\\', '/', $name).'.php';
}
|
Get the destination class path.
@param string $name
@return string
|
getPath
|
php
|
illuminate/database
|
Console/Factories/FactoryMakeCommand.php
|
https://github.com/illuminate/database/blob/master/Console/Factories/FactoryMakeCommand.php
|
MIT
|
protected function guessModelName($name)
{
if (str_ends_with($name, 'Factory')) {
$name = substr($name, 0, -7);
}
$modelName = $this->qualifyModel(Str::after($name, $this->rootNamespace()));
if (class_exists($modelName)) {
return $modelName;
}
if (is_dir(app_path('Models/'))) {
return $this->rootNamespace().'Models\Model';
}
return $this->rootNamespace().'Model';
}
|
Guess the model name from the Factory name or return a default model name.
@param string $name
@return string
|
guessModelName
|
php
|
illuminate/database
|
Console/Factories/FactoryMakeCommand.php
|
https://github.com/illuminate/database/blob/master/Console/Factories/FactoryMakeCommand.php
|
MIT
|
protected function getOptions()
{
return [
['model', 'm', InputOption::VALUE_OPTIONAL, 'The name of the model'],
];
}
|
Get the console command options.
@return array
|
getOptions
|
php
|
illuminate/database
|
Console/Factories/FactoryMakeCommand.php
|
https://github.com/illuminate/database/blob/master/Console/Factories/FactoryMakeCommand.php
|
MIT
|
protected function getMigrationPaths()
{
// Here, we will check to see if a path option has been defined. If it has we will
// use the path relative to the root of the installation folder so our database
// migrations may be run for any customized path from within the application.
if ($this->input->hasOption('path') && $this->option('path')) {
return (new Collection($this->option('path')))->map(function ($path) {
return ! $this->usingRealPath()
? $this->laravel->basePath().'/'.$path
: $path;
})->all();
}
return array_merge(
$this->migrator->paths(), [$this->getMigrationPath()]
);
}
|
Get all of the migration paths.
@return string[]
|
getMigrationPaths
|
php
|
illuminate/database
|
Console/Migrations/BaseCommand.php
|
https://github.com/illuminate/database/blob/master/Console/Migrations/BaseCommand.php
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.