Connection
class Connection implements ConnectionInterface
Traits
Constants
| READ_WRITE_TYPE_CONFIG_KEY |
|
Properties
| static protected array | $macros | The registered string macros. |
from Macroable |
| protected null|PDO|PDO | $pdo | The active PDO connection. |
|
| protected null|PDO|PDO | $readPdo | The active PDO connection used for reads. |
|
| protected array | $readPdoConfig | The database connection configuration options for reading. |
|
| protected string | $database | The name of the connected database. |
|
| protected string | $tablePrefix | The table prefix for the connection. |
|
| protected array | $config | The database connection configuration options. |
|
| protected null|Connection): mixed | $reconnector | The reconnector instance for the connection. |
|
| protected Grammar | $queryGrammar | The query grammar implementation. |
|
| protected Grammar|null | $schemaGrammar | The schema grammar implementation. |
|
| protected Processor | $postProcessor | The query post processor implementation. |
|
| protected Dispatcher|null | $events | The event dispatcher instance. |
|
| protected int | $fetchMode | The default fetch mode of the connection. |
|
| protected int | $transactions | The number of active transactions. |
|
| protected DatabaseTransactionsManager|null | $transactionsManager | The transaction manager instance. |
|
| protected bool | $recordsModified | Indicates if changes have been made to the database. |
|
| protected bool | $readOnWriteConnection | Indicates if the connection should use the "write" PDO connection. |
|
| protected null|"read"|"write" | $readWriteType | The configured read / write type for derived single-role connections. |
|
| protected null|"read"|"write" | $latestPdoTypeRetrieved | The last retrieved PDO read / write type. |
|
| protected array<array{query: string, bindings: array, time: null|float}> | $queryLog | All of the queries run against the connection. |
|
| protected bool | $loggingQueries | Indicates whether queries are being logged. |
|
| protected float | $totalQueryDuration | The duration of all executed queries in milliseconds. |
|
| protected array<array{threshold: float|int, handler: callable, has_run: bool}> | $queryDurationHandlers | All of the registered query duration handlers. |
|
| protected bool | $pretending | Indicates if the connection is in a "dry run". |
|
| protected Closure[] | $beforeStartingTransaction | All of the callbacks that should be invoked before a transaction is started. |
|
| protected Closure[] | $beforeExecutingCallbacks | All of the callbacks that should be invoked before a query is executed. |
|
| protected int | $errorCount | The number of SQL execution errors on this connection. |
|
| static protected SessionConfigurator> | $sessionConfigurators | The registered database session configurators. |
|
| static protected null|PhysicalSessionState> | $physicalSessionStates | The state known for each live physical database session. |
|
| static protected Closure> | $resolvers | The connection resolvers. |
Methods
Determine if the given exception was caused by a concurrency error such as a deadlock or serialization failure.
Determine if the given exception was caused by a lost connection.
Handle an exception encountered when running a transacted statement.
Handle an exception encountered when committing a transaction.
Rollback the active database transaction.
Detach transaction records and physical connection references.
Execute the callback after a transaction commits.
Execute the callback after a transaction rolls back.
Get the number of seconds until the given DateTime.
Get the "available at" UNIX timestamp.
If the given value is an interval, convert it to a DateTime instance.
Given a start time, format the total run time for human readability.
Mix another object into the class.
Dynamically handle calls to the class.
Dynamically handle calls to the class.
Create a new database connection instance.
Set the query grammar to the default implementation.
Get the default query grammar instance.
Set the schema grammar to the default implementation.
Get the default schema grammar instance.
Set the query post processor to the default implementation.
Get the default post processor instance.
Get a schema builder instance for the connection.
Get the schema state for the connection.
Run a select statement and return a single result.
Run a select statement and return the first column of the first row.
Run a select statement against the database.
Run a select statement against the database.
Run a select statement against the database and returns all of the result sets.
Run a select statement against the database and returns a generator.
Get the PDO connection to use for a select query.
Run an insert statement against the database.
Run an update statement against the database.
Run a delete statement against the database.
Execute an SQL statement and return the boolean result.
Run an SQL statement and get the number of rows affected.
Run a raw, unprepared query against the PDO connection.
Get the number of open connections for the database.
Bind values to their parameters in the given statement.
Prepare the query bindings for execution.
Determine if the given database exception was caused by a unique constraint violation.
Extract the index and columns that caused a unique constraint violation.
Log a query in the connection's query log.
Get the elapsed time in milliseconds since a given starting point.
Register a callback to be invoked when the connection queries for longer than a given amount of time.
Allow all the query duration handlers to run again, even if they have already run.
Get the duration of all run queries in milliseconds.
Reset the duration of all run queries.
Handle a query exception.
Handle a query exception that occurred during query execution.
Reconnect to the database.
Reconnect to the database if a PDO connection is missing.
Disconnect from the underlying PDO connection.
Register a hook to be run just before a database transaction is started.
Register a hook to be run just before a database query is executed.
Clear all hooks registered to run before a database query.
Reset all wrapper state for pool release.
Get the number of SQL execution errors on this connection.
Fire an event for this connection.
Get a new raw query expression.
Escape a value for safe SQL embedding.
Escape a string value for safe SQL embedding.
Escape a boolean value for safe SQL embedding.
Escape a binary value for safe SQL embedding.
Determine if the database connection has modified any database records.
Indicate if any records have been modified.
Set the record modification state.
Reset the record modification state.
Indicate that the connection should use the write PDO connection for reads.
Get the current PDO parameter without resolving, reconnecting, or synchronizing session state.
Get the current synchronized PDO connection used for reading.
Get the current read PDO parameter without resolving, reconnecting, or synchronizing session state.
Resolve the current write PDO without synchronizing session state.
Resolve the current read PDO without synchronizing session state.
Synchronize the desired state for a physical database session.
Replace a physical session whose state can no longer be trusted.
Determine whether an open PDO has unknown session state.
Set the read PDO connection configuration.
Set the reconnect instance on the connection.
Get the database connection name.
Get an option from the configuration options.
Get the basic connection information as an array for debugging.
Get the PDO driver name.
Get a human-readable name for the given connection driver.
Get the query grammar used by the connection.
Get the schema grammar used by the connection.
Get the query post processor used by the connection.
Get the event dispatcher used by the connection.
Unset the event dispatcher for this connection.
Run the statement to start a new transaction.
Set the transaction manager instance on the connection.
Get the transaction manager instance.
Unset the transaction manager for this connection.
Determine if the connection is in a "dry run".
Get the connection query log.
Get the connection query log with embedded bindings.
Clear the query log.
Enable the query log on the connection.
Disable the query log on the connection.
Determine whether we're logging queries.
Get the name of the connected database.
Set the name of the connected database.
Retrieve the latest read / write type used.
Get the table prefix for the connection.
Set the table prefix in use by the connection.
Get the server version for the connection.
Get the connection resolver for the given driver.
Flush all static state.
Prepare the instance for cloning.
Details
in
DetectsConcurrencyErrors at line 16
protected bool
causedByConcurrencyError(Throwable $e)
Determine if the given exception was caused by a concurrency error such as a deadlock or serialization failure.
in
DetectsLostConnections at line 16
protected bool
causedByLostConnection(Throwable $e)
Determine if the given exception was caused by a lost connection.
in
ManagesTransactions at line 29
mixed
transaction(Closure $callback, int $attempts = 1)
No description
in
ManagesTransactions at line 109
protected void
handleTransactionException(Throwable $e, int $currentAttempt, int $maxAttempts)
Handle an exception encountered when running a transacted statement.
in
ManagesTransactions at line 163
void
beginTransaction()
Start a new database transaction.
in
ManagesTransactions at line 197
protected void
createTransaction()
Create a transaction within the database.
in
ManagesTransactions at line 217
protected void
createSavepoint()
Create a save point within the database.
in
ManagesTransactions at line 229
protected void
handleBeginTransactionException(Throwable $e)
Handle an exception from a transaction beginning.
in
ManagesTransactions at line 245
void
commit()
Commit the active database transaction.
in
ManagesTransactions at line 283
protected void
performCommit()
Commit the active physical transaction.
in
ManagesTransactions at line 306
protected void
handleCommitTransactionException(Throwable $e, int $currentAttempt, int $maxAttempts)
Handle an exception encountered when committing a transaction.
in
ManagesTransactions at line 340
void
rollBack(int|null $toLevel = null)
Rollback the active database transaction.
in
ManagesTransactions at line 398
protected void
performRollBack(int $toLevel, PDO $pdo)
Perform a rollback within the database.
in
ManagesTransactions at line 416
protected void
handleRollBackException(Throwable $e)
Handle an exception from a rollback.
in
ManagesTransactions at line 432
protected void
terminateTransactionState()
Detach transaction records and physical connection references.
in
ManagesTransactions at line 453
int
transactionLevel()
Get the number of active transactions.
in
ManagesTransactions at line 463
void
afterCommit(callable $callback)
Execute the callback after a transaction commits.
in
ManagesTransactions at line 479
void
afterRollBack(callable $callback)
Execute the callback after a transaction rolls back.
in
InteractsWithTime at line 17
protected int
secondsUntil(DateInterval|DateTimeInterface|int $delay)
Get the number of seconds until the given DateTime.
in
InteractsWithTime at line 29
protected int
availableAt(DateInterval|DateTimeInterface|int|null $delay = 0)
Get the "available at" UNIX timestamp.
in
InteractsWithTime at line 41
protected DateTimeInterface|int
parseDateInterval(DateInterval|DateTimeInterface|int|null $delay)
If the given value is an interval, convert it to a DateTime instance.
in
InteractsWithTime at line 57
protected int
currentTime()
Get the current system time as a UNIX timestamp.
in
InteractsWithTime at line 65
protected string
runTimeForHumans(float $startTime, float|null $endTime = null)
Given a start time, format the total run time for human readability.
in
Macroable at line 28
static void
macro(string $name, callable|object $macro)
Register a custom macro.
Boot-only. Macros persist in a static property for the worker lifetime and apply to every subsequent call on the macroable class.
in
Macroable at line 41
static void
mixin(object $mixin, bool $replace = true)
Mix another object into the class.
Boot-only. Delegates to macro() for each method; registered macros persist in a static property for the worker lifetime.
in
Macroable at line 57
static bool
hasMacro(string $name)
Check if macro is registered.
in
Macroable at line 68
static void
flushMacros()
Flush the existing macros.
Boot or tests only. Clears worker-wide macros; concurrent coroutines may resolve different methods depending on timing.
in
Macroable at line 78
static mixed
__callStatic(string $method, array $parameters)
Dynamically handle calls to the class.
in
Macroable at line 103
mixed
__call(string $method, array $parameters)
Dynamically handle calls to the class.
at line 222
__construct(PDO|Closure $pdo, string $database = '', string $tablePrefix = '', array $config = [])
Create a new database connection instance.
at line 248
void
useDefaultQueryGrammar()
Set the query grammar to the default implementation.
at line 256
protected Grammar
getDefaultQueryGrammar()
Get the default query grammar instance.
at line 264
void
useDefaultSchemaGrammar()
Set the schema grammar to the default implementation.
at line 272
protected Grammar|null
getDefaultSchemaGrammar()
Get the default schema grammar instance.
at line 280
void
useDefaultPostProcessor()
Set the query post processor to the default implementation.
at line 288
protected Processor
getDefaultPostProcessor()
Get the default post processor instance.
at line 296
Builder
getSchemaBuilder()
Get a schema builder instance for the connection.
at line 310
SchemaState
getSchemaState(Filesystem|null $files = null, callable|null $processFactory = null)
Get the schema state for the connection.
at line 318
Builder
table(Closure|Builder|UnitEnum|string $table, string|null $as = null)
Begin a fluent query against a database table.
at line 330
Builder
query()
Get a new query builder instance.
at line 342
mixed
selectOne(string $query, array $bindings = [], bool $useReadPdo = true)
Run a select statement and return a single result.
at line 354
mixed
scalar(string $query, array $bindings = [], bool $useReadPdo = true)
Run a select statement and return the first column of the first row.
at line 374
array
selectFromWriteConnection(string $query, array $bindings = [])
Run a select statement against the database.
at line 382
array
select(string $query, array $bindings = [], bool $useReadPdo = true, array $fetchUsing = [])
Run a select statement against the database.
at line 407
array
selectResultSets(string $query, array $bindings = [], bool $useReadPdo = true)
Run a select statement against the database and returns all of the result sets.
at line 437
Generator
cursor(string $query, array $bindings = [], bool $useReadPdo = true, array $fetchUsing = [])
Run a select statement against the database and returns a generator.
at line 471
protected PDOStatement
prepared(PDOStatement $statement)
Configure the PDO prepared statement.
at line 483
protected PDO
getPdoForSelect(bool $useReadPdo = true)
Get the PDO connection to use for a select query.
at line 491
bool
insert(string $query, array $bindings = [])
Run an insert statement against the database.
at line 499
int
update(string $query, array $bindings = [])
Run an update statement against the database.
at line 507
int
delete(string $query, array $bindings = [])
Run a delete statement against the database.
at line 515
bool
statement(string $query, array $bindings = [])
Execute an SQL statement and return the boolean result.
at line 535
int
affectingStatement(string $query, array $bindings = [])
Run an SQL statement and get the number of rows affected.
at line 562
bool
unprepared(string $query)
Run a raw, unprepared query against the PDO connection.
at line 580
int|null
threadCount()
Get the number of open connections for the database.
at line 593
array
pretend(Closure $callback)
Execute the given callback in "dry run" mode.
at line 619
mixed
withoutPretending(Closure $callback)
Execute the given callback without "pretending".
at line 639
protected array
withFreshQueryLog(Closure $callback)
Execute the given callback in "dry run" mode.
at line 663
void
bindValues(PDOStatement $statement, array $bindings)
Bind values to their parameters in the given statement.
at line 681
array
prepareBindings(array $bindings)
Prepare the query bindings for execution.
at line 704
protected mixed
run(string $query, array $bindings, Closure $callback)
Run a SQL statement and log its execution context.
at line 745
protected mixed
runQueryCallback(string $query, array $bindings, Closure $callback)
Run a SQL statement.
at line 786
protected bool
isUniqueConstraintError(Exception $exception)
Determine if the given database exception was caused by a unique constraint violation.
at line 796
protected array
parseUniqueConstraintViolation(Exception $exception)
Extract the index and columns that caused a unique constraint violation.
at line 804
void
logQuery(string $query, array $bindings, float|null $time = null)
Log a query in the connection's query log.
at line 845
protected float
getElapsedTime(float $start)
Get the elapsed time in milliseconds since a given starting point.
at line 853
void
whenQueryingForLongerThan(DateTimeInterface|CarbonInterval|float|int $threshold, callable $handler)
Register a callback to be invoked when the connection queries for longer than a given amount of time.
at line 873
void
allowQueryDurationHandlersToRunAgain()
Allow all the query duration handlers to run again, even if they have already run.
at line 883
float
totalQueryDuration()
Get the duration of all run queries in milliseconds.
at line 891
void
resetTotalQueryDuration()
Reset the duration of all run queries.
at line 901
protected mixed
handleQueryException(QueryException $e, string $query, array $bindings, Closure $callback)
Handle a query exception.
at line 920
protected mixed
tryAgainIfCausedByLostConnection(QueryException $e, string $query, array $bindings, Closure $callback)
Handle a query exception that occurred during query execution.
at line 936
mixed
reconnect()
Reconnect to the database.
at line 948
void
reconnectIfMissingConnection()
Reconnect to the database if a PDO connection is missing.
at line 958
void
disconnect()
Disconnect from the underlying PDO connection.
at line 990
Connection
beforeStartingTransaction(Closure $callback)
Register a hook to be run just before a database transaction is started.
at line 1000
Connection
beforeExecuting(Closure $callback)
Register a hook to be run just before a database query is executed.
at line 1012
void
clearBeforeExecutingCallbacks()
Clear all hooks registered to run before a database query.
Used by connection pooling to prevent callback leaks between requests.
at line 1023
void
resetForPool()
Reset all wrapper state for pool release.
Physical database session state is preserved and synchronized against the next coroutine's desired state when the PDO is handed out again.
at line 1055
int
getErrorCount()
Get the number of SQL execution errors on this connection.
Used by connection pooling to detect stale connections.
at line 1063
void
listen(Closure $callback)
Register a database query listener with the connection.
at line 1071
protected void
fireConnectionEvent(string $event)
Fire an event for this connection.
at line 1100
protected void
event(string $eventClass, Closure $event)
Fire the given event if listeners are registered.
at line 1110
Expression
raw(mixed $value)
Get a new raw query expression.
at line 1120
string
escape(mixed $value, bool $binary = false)
Escape a value for safe SQL embedding.
at line 1151
protected string
escapeString(string $value)
Escape a string value for safe SQL embedding.
at line 1159
protected string
escapeBool(bool $value)
Escape a boolean value for safe SQL embedding.
at line 1169
protected string
escapeBinary(string $value)
Escape a binary value for safe SQL embedding.
at line 1177
bool
hasModifiedRecords()
Determine if the database connection has modified any database records.
at line 1185
void
recordsHaveBeenModified(bool $value = true)
Indicate if any records have been modified.
at line 1195
Connection
setRecordModificationState(bool $value)
Set the record modification state.
at line 1205
void
forgetRecordModificationState()
Reset the record modification state.
at line 1213
Connection
useWriteConnectionWhenReading(bool $value = true)
Indicate that the connection should use the write PDO connection for reads.
at line 1223
PDO
getPdo()
Get the current synchronized PDO connection.
at line 1236
PDO|Closure|null
getRawPdo()
Get the current PDO parameter without resolving, reconnecting, or synchronizing session state.
at line 1244
PDO
getReadPdo()
Get the current synchronized PDO connection used for reading.
at line 1266
PDO|Closure|null
getRawReadPdo()
Get the current read PDO parameter without resolving, reconnecting, or synchronizing session state.
at line 1274
protected PDO
resolvePdo()
Resolve the current write PDO without synchronizing session state.
at line 1286
protected PDO
resolveReadPdo()
Resolve the current read PDO without synchronizing session state.
at line 1304
protected PDO
synchronizeSession(PDO $pdo, bool $read)
Synchronize the desired state for a physical database session.
at line 1372
protected PDO
replaceUnknownSession(bool $read)
Replace a physical session whose state can no longer be trusted.
at line 1394
static protected PhysicalSessionState
physicalSessionState(PDO $pdo)
Get the state holder for a physical database session.
at line 1404
static protected bool
sessionStateIsUnknown(PDO $pdo)
Determine whether a physical database session has unknown state.
at line 1414
protected void
invalidateSessionState(PDO $pdo)
Invalidate the states remembered for a physical database session.
at line 1425
protected void
markSessionStateUnknown(PDO $pdo)
Mark a physical database session's state as unknown.
at line 1441
bool
hasUnknownSessionState()
| internal |
Determine whether an open PDO has unknown session state.
at line 1463
Connection
setPdo(PDO|Closure|null $pdo)
Set the PDO connection.
at line 1475
Connection
setReadPdo(PDO|Closure|null $pdo)
Set the PDO connection used for reading.
at line 1485
Connection
setReadPdoConfig(array $config)
Set the read PDO connection configuration.
at line 1495
Connection
setReconnector(callable $reconnector)
Set the reconnect instance on the connection.
at line 1505
string|null
getName()
Get the database connection name.
at line 1513
mixed
getConfig(string|null $option = null)
Get an option from the configuration options.
at line 1521
protected array
getConnectionDetails()
Get the basic connection information as an array for debugging.
at line 1540
string
getDriverName()
Get the PDO driver name.
at line 1548
string
getDriverTitle()
Get a human-readable name for the given connection driver.
at line 1556
Grammar
getQueryGrammar()
Get the query grammar used by the connection.
at line 1564
Connection
setQueryGrammar(Grammar $grammar)
Set the query grammar used by the connection.
at line 1574
Grammar|null
getSchemaGrammar()
Get the schema grammar used by the connection.
at line 1582
Connection
setSchemaGrammar(Grammar $grammar)
Set the schema grammar used by the connection.
at line 1592
Processor
getPostProcessor()
Get the query post processor used by the connection.
at line 1600
Connection
setPostProcessor(Processor $processor)
Set the query post processor used by the connection.
at line 1610
Dispatcher|null
getEventDispatcher()
Get the event dispatcher used by the connection.
at line 1618
Connection
setEventDispatcher(Dispatcher $events)
Set the event dispatcher instance on the connection.
at line 1628
void
unsetEventDispatcher()
Unset the event dispatcher for this connection.
at line 1636
protected void
executeBeginTransactionStatement()
Run the statement to start a new transaction.
at line 1644
Connection
setTransactionManager(DatabaseTransactionsManager $manager)
Set the transaction manager instance on the connection.
at line 1654
DatabaseTransactionsManager|null
getTransactionManager()
Get the transaction manager instance.
at line 1662
void
unsetTransactionManager()
Unset the transaction manager for this connection.
at line 1670
bool
pretending()
Determine if the connection is in a "dry run".
at line 1680
array
getQueryLog()
Get the connection query log.
at line 1688
array
getRawQueryLog()
Get the connection query log with embedded bindings.
at line 1702
void
flushQueryLog()
Clear the query log.
at line 1710
void
enableQueryLog()
Enable the query log on the connection.
at line 1718
void
disableQueryLog()
Disable the query log on the connection.
at line 1726
bool
logging()
Determine whether we're logging queries.
at line 1734
string
getDatabaseName()
Get the name of the connected database.
at line 1742
Connection
setDatabaseName(string $database)
Set the name of the connected database.
at line 1754
protected string|null
latestReadWriteTypeUsed()
Retrieve the latest read / write type used.
at line 1762
string
getTablePrefix()
Get the table prefix for the connection.
at line 1770
Connection
setTablePrefix(string $prefix)
Set the table prefix in use by the connection.
at line 1785
mixed
withoutTablePrefix(Closure $callback)
Execute the given callback without table prefix.
at line 1801
string
getServerVersion()
Get the server version for the connection.
at line 1813
static void
configureSessionUsing(SessionConfigurator $configurator)
Register a database session configurator.
Boot-only. The configurator persists in a static property for the worker lifetime and runs on every subsequent synchronized PDO hand-out across all coroutines.
at line 1825
static void
resolverFor(string $driver, Closure $callback)
Register a connection resolver.
Boot-only. The resolver persists in a static property for the worker lifetime and runs on every subsequent Connection construction for the given driver across all coroutines.
at line 1833
static Closure|null
getResolver(string $driver)
Get the connection resolver for the given driver.
at line 1841
static void
flushState()
Flush all static state.
at line 1852
void
__clone()
Prepare the instance for cloning.