MCPcopy Index your code
hub / github.com/dbcli/mycli / reconnect

Method reconnect

mycli/client_connection.py:291–344  ·  view source on GitHub ↗

Attempt to reconnect to the server. Return True if successful, False if unsuccessful. The "database" argument is used only to improve messages.

(self, database: str = "")

Source from the content-addressed store, hash-verified

289 sys.exit(1)
290
291 def reconnect(self, database: str = "") -> bool:
292 """
293 Attempt to reconnect to the server. Return True if successful,
294 False if unsuccessful.
295
296 The "database" argument is used only to improve messages.
297 """
298 assert self.sqlexecute is not None
299 assert self.sqlexecute.conn is not None
300
301 # First pass with ping(reconnect=False) and minimal feedback levels. This definitely
302 # works as expected, and is a good idea especially when "connect" was used as a
303 # synonym for "use".
304 try:
305 self.sqlexecute.conn.ping(reconnect=False)
306 if not database:
307 self.echo("Already connected.", fg="yellow")
308 return True
309 except pymysql.err.Error:
310 pass
311
312 # Second pass with ping(reconnect=True). It is not demonstrated that this pass ever
313 # gives the benefit it is looking for, _ie_ preserves session state. We need to test
314 # this with connection pooling.
315 try:
316 old_connection_id = self.sqlexecute.connection_id
317 self.logger.debug("Attempting to reconnect.")
318 self.echo("Reconnecting...", fg="yellow")
319 self.sqlexecute.conn.ping(reconnect=True)
320 # if a database is currently selected, set it on the conn again
321 if self.sqlexecute.dbname:
322 self.sqlexecute.conn.select_db(self.sqlexecute.dbname)
323 self.logger.debug("Reconnected successfully.")
324 self.echo("Reconnected successfully.", fg="yellow")
325 self.sqlexecute.reset_connection_id()
326 if old_connection_id != self.sqlexecute.connection_id:
327 self.echo("Any session state was reset.", fg="red")
328 return True
329 except pymysql.err.Error:
330 pass
331
332 # Third pass with sqlexecute.connect() should always work, but always resets session state.
333 try:
334 self.logger.debug("Creating new connection")
335 self.echo("Creating new connection...", fg="yellow")
336 self.sqlexecute.connect()
337 self.logger.debug("New connection created successfully.")
338 self.echo("New connection created successfully.", fg="yellow")
339 self.echo("Any session state was reset.", fg="red")
340 return True
341 except pymysql.OperationalError as e:
342 self.logger.debug("Reconnect failed. e: %r", e)
343 self.echo(str(e), err=True, fg="red")
344 return False

Callers

nothing calls this directly

Calls 6

echoMethod · 0.95
pingMethod · 0.45
debugMethod · 0.45
select_dbMethod · 0.45
reset_connection_idMethod · 0.45
connectMethod · 0.45

Tested by

no test coverage detected