class_docstr: The Main Server controller class
class_docstr_tok: ["The","Main","Server","controller","class"]
docstr: Handle new incoming connections
  :return:
code: def handle(self):
      """
      Handle new incoming connections
      :return:
      """
      ctx.set_default()
  
      self.server.hook_before_handle()
  
      logger.debug("handle new incoming connection")
      cloud_connection = self.is_cloud_connection()
  
      ctx.company_id = cloud_connection.get("company_id")
  
      self.init_session()
      if cloud_connection["is_cloud"] is False:
          if self.handshake() is False:
              return
      else:
          ctx.user_class = cloud_connection["user_class"]
          ctx.email_confirmed = cloud_connection["email_confirmed"]
          self.client_capabilities = ClentCapabilities(
              cloud_connection["client_capabilities"]
          )
          self.session.database = cloud_connection["database"]
          self.session.username = "cloud"
          self.session.auth = True
  
      while True:
          logger.debug("Got a new packet")
          p = self.packet(CommandPacket)
  
          try:
              success = p.get()
          except Exception:
              logger.error("Session closed, on packet read error")
              logger.error(traceback.format_exc())
              return
  
          if success is False:
              logger.debug("Session closed by client")
              return
  
          logger.debug(
              "Command TYPE: {type}".format(
                  type=getConstName(COMMANDS, p.type.value)
              )
          )
  
          command_names = {
              COMMANDS.COM_QUERY: "COM_QUERY",
              COMMANDS.COM_STMT_PREPARE: "COM_STMT_PREPARE",
              COMMANDS.COM_STMT_EXECUTE: "COM_STMT_EXECUTE",
              COMMANDS.COM_STMT_FETCH: "COM_STMT_FETCH",
              COMMANDS.COM_STMT_CLOSE: "COM_STMT_CLOSE",
              COMMANDS.COM_QUIT: "COM_QUIT",
              COMMANDS.COM_INIT_DB: "COM_INIT_DB",
              COMMANDS.COM_FIELD_LIST: "COM_FIELD_LIST",
          }
  
          command_name = command_names.get(
              p.type.value, f"UNKNOWN {p.type.value}"
          )
          sql = None
          response = None
          error_type = None
          error_code = None
          error_text = None
          error_traceback = None
  
          try:
              if p.type.value == COMMANDS.COM_QUERY:
                  sql = self.decode_utf(p.sql.value)
                  sql = SqlStatementParser.clear_sql(sql)
                  logger.debug(f"COM_QUERY: {sql}")
                  profiler.set_meta(
                      query=sql,
                      api="mysql",
                      environment=Config().get("environment"),
                  )
                  with profiler.Context("mysql_query_processing"):
                      response = self.process_query(sql)
              elif p.type.value == COMMANDS.COM_STMT_PREPARE:
                  sql = self.decode_utf(p.sql.value)
                  self.answer_stmt_prepare(sql)
              elif p.type.value == COMMANDS.COM_STMT_EXECUTE:
                  self.answer_stmt_execute(
                      p.stmt_id.value, p.parameters
                  )
              elif p.type.value == COMMANDS.COM_STMT_FETCH:
                  self.answer_stmt_fetch(p.stmt_id.value, p.limit.value)
              elif p.type.value == COMMANDS.COM_STMT_CLOSE:
                  self.answer_stmt_close(p.stmt_id.value)
              elif p.type.value == COMMANDS.COM_QUIT:
                  logger.debug("Session closed, on client disconnect")
                  self.session = None
                  break
              elif p.type.value == COMMANDS.COM_INIT_DB:
                  new_database = p.database.value.decode()
  
                  executor = Executor(
                      session=self.session, sqlserver=self
                  )
                  executor.change_default_db(new_database)
  
                  response = SQLAnswer(RESPONSE_TYPE.OK)
              elif p.type.value == COMMANDS.COM_FIELD_LIST:
                  # this command is deprecated, but console client still use it.
                  response = SQLAnswer(RESPONSE_TYPE.OK)
              else:
                  logger.warning(
                      "Command has no specific handler, return OK msg"
                  )
                  logger.debug(str(p))
                  # p.pprintPacket() TODO: Make a version of print packet
                  # that sends it to debug instead
                  response = SQLAnswer(RESPONSE_TYPE.OK)
  
          except SqlApiException as e:
              # classified error
              error_type = "expected"
  
              response = SQLAnswer(
                  resp_type=RESPONSE_TYPE.ERROR,
                  error_code=e.err_code,
                  error_message=str(e),
              )
  
          except exec_exc.ExecutorException as e:
              # unclassified
              error_type = "expected"
  
              if isinstance(e, exec_exc.NotSupportedYet):
                  error_code = ERR.ER_NOT_SUPPORTED_YET
              elif isinstance(e, exec_exc.KeyColumnDoesNotExist):
                  error_code = ERR.ER_KEY_COLUMN_DOES_NOT_EXIST
              elif isinstance(e, exec_exc.TableNotExistError):
                  error_code = ERR.ER_TABLE_EXISTS_ERROR
              elif isinstance(e, exec_exc.WrongArgumentError):
                  error_code = ERR.ER_WRONG_ARGUMENTS
              elif isinstance(e, exec_exc.LogicError):
                  error_code = ERR.ER_WRONG_USAGE
              elif isinstance(
                  e, (exec_exc.BadDbError, exec_exc.BadTableError)
              ):
                  error_code = ERR.ER_BAD_DB_ERROR
              else:
                  error_code = ERR.ER_SYNTAX_ERROR
  
              response = SQLAnswer(
                  resp_type=RESPONSE_TYPE.ERROR,
                  error_code=error_code,
                  error_message=str(e),
              )
          except exec_exc.UnknownError as e:
              # unclassified
              error_type = "unexpected"
  
              response = SQLAnswer(
                  resp_type=RESPONSE_TYPE.ERROR,
                  error_code=ERR.ER_UNKNOWN_ERROR,
                  error_message=str(e),
              )
  
          except Exception as e:
              # any other exception
              error_type = "unexpected"
              error_traceback = traceback.format_exc()
              logger.error(
                  f"ERROR while executing query\n"
                  f"{error_traceback}\n"
                  f"{e}"
              )
              error_code = ERR.ER_SYNTAX_ERROR
              response = SQLAnswer(
                  resp_type=RESPONSE_TYPE.ERROR,
                  error_code=error_code,
                  error_message=str(e),
              )
  
          if response is not None:
              self.send_query_answer(response)
              if response.type == RESPONSE_TYPE.ERROR:
                  error_text = response.error_message
                  error_code = response.error_code
                  error_type = error_type or "expected"
  
          hooks.after_api_query(
              company_id=ctx.company_id,
              api="mysql",
              command=command_name,
              payload=sql,
              error_type=error_type,
              error_code=error_code,
              error_text=error_text,
              traceback=error_traceback,
          )
  
imports: import atexit
  import base64
  import os
  import select
  import socket
  import socketserver
  import ssl
  import struct
  import sys
  import tempfile
  import traceback
  from functools import partial
  from typing import Dict, List
  from numpy import dtype
  from pandas.api import types
  import mindsdb.utilities.hooks
  import mindsdb.utilities.profiler
  from mindsdb.api.mysql.mysql_proxy.classes.client_capabilities import ClentCapabilities
  from mindsdb.api.mysql.mysql_proxy.classes.server_capabilities import server_capabilities
  from mindsdb.api.mysql.mysql_proxy.classes.sql_statement_parser import SqlStatementParser
  from mindsdb.api.executor.controllers import SessionController
  from mindsdb.api.mysql.mysql_proxy.data_types.mysql_packet import Packet
  from mindsdb.api.mysql.mysql_proxy.data_types.mysql_packets import BinaryResultsetRowPacket, ColumnCountPacket, ColumnDefenitionPacket, CommandPacket, EofPacket, ErrPacket, FastAuthFail, HandshakePacket, HandshakeResponsePacket, OkPacket, PasswordAnswer, ResultsetRowPacket, STMTPrepareHeaderPacket, SwitchOutPacket, SwitchOutResponse
  from mindsdb.api.mysql.mysql_proxy.executor import Executor
  from mindsdb.api.mysql.mysql_proxy.external_libs.mysql_scramble import scramble
  from mindsdb.api.mysql.mysql_proxy.libs.constants.mysql import CAPABILITIES, CHARSET_NUMBERS, COMMANDS, DEFAULT_AUTH_METHOD, ERR, SERVER_STATUS, TYPES, getConstName
  from mindsdb.api.executor.data_types.response_type import RESPONSE_TYPE
  from mindsdb.api.mysql.mysql_proxy.utilities import ErWrongCharset, SqlApiException
  from mindsdb.api.executor import exceptions
  from mindsdb.api.mysql.mysql_proxy.utilities.lightwood_dtype import dtype
  from mindsdb.utilities import log
  from mindsdb.utilities.config import Config
  from mindsdb.utilities.context import context
  from mindsdb.utilities.wizards import make_ssl_cert
label_desc: Use image node_id 17 for calling the MysqlProxy obj's underlying member method code with example usage: obj.handle() without return types