17
17
use Doctrine \DBAL \Exception \ConnectionLost ;
18
18
use Doctrine \DBAL \Exception \DriverException ;
19
19
use Doctrine \DBAL \Exception \InvalidArgumentException ;
20
+ use Doctrine \DBAL \Exception as DBALException ;
20
21
use Doctrine \DBAL \Platforms \AbstractPlatform ;
21
22
use Doctrine \DBAL \Query \Expression \ExpressionBuilder ;
22
23
use Doctrine \DBAL \Query \QueryBuilder ;
29
30
use Doctrine \Deprecations \Deprecation ;
30
31
use LogicException ;
31
32
use SensitiveParameter ;
33
+ use Symfony \Bridge \Doctrine \ConnectionLossAwareHandler ;
32
34
use Throwable ;
33
35
use Traversable ;
34
36
@@ -166,6 +168,12 @@ class Connection
166
168
167
169
private SchemaManagerFactory $ schemaManagerFactory ;
168
170
171
+ private static bool $ isChecking = false ;
172
+
173
+ private static ?int $ lastCheckedAt = null ;
174
+
175
+ private ?int $ checkFrequency ;
176
+
169
177
/**
170
178
* Initializes a new instance of the Connection class.
171
179
*
@@ -186,6 +194,7 @@ public function __construct(
186
194
?Configuration $ config = null ,
187
195
?EventManager $ eventManager = null
188
196
) {
197
+ $ this ->checkFrequency = $ params ['check_connection_frequency ' ] ?? null ;
189
198
$ this ->_driver = $ driver ;
190
199
$ this ->params = $ params ;
191
200
@@ -371,6 +380,21 @@ public function connect()
371
380
);
372
381
373
382
if ($ this ->_conn !== null ) {
383
+ if (null === $ this ->checkFrequency ) {
384
+ return false ;
385
+ }
386
+
387
+ if (! self ::$ isChecking ) {
388
+ if (null === self ::$ lastCheckedAt || time () - self ::$ lastCheckedAt >= $ this ->checkFrequency ) {
389
+ self ::$ isChecking = true ;
390
+
391
+ $ this ->reconnectOnFailure ();
392
+
393
+ self ::$ lastCheckedAt = time ();
394
+ self ::$ isChecking = false ;
395
+ }
396
+ }
397
+
374
398
return false ;
375
399
}
376
400
@@ -2002,4 +2026,15 @@ public function exec(string $sql): int
2002
2026
2003
2027
return $ this ->executeStatement ($ sql );
2004
2028
}
2029
+
2030
+ private function reconnectOnFailure ()
2031
+ {
2032
+ try {
2033
+ $ this ->executeQuery ($ this ->getDatabasePlatform ($ this )->getDummySelectSQL ());
2034
+ } catch (DBALException ) {
2035
+ $ this ->close ();
2036
+ // Attempt to reestablish the lazy connection by sending another query.
2037
+ $ this ->executeQuery ($ this ->getDatabasePlatform ($ this )->getDummySelectSQL ());
2038
+ }
2039
+ }
2005
2040
}
0 commit comments