MCPcopy Create free account
hub / github.com/PyMySQL/PyMySQL / _read_packet

Method _read_packet

pymysql/connections.py:773–821  ·  view source on GitHub ↗

Read an entire "mysql packet" in its entirety from the network and return a MysqlPacket type that represents the results. :raise OperationalError: If the connection to the MySQL server is lost. :raise InternalError: If the packet sequence number is wrong.

(self, packet_type=MysqlPacket)

Source from the content-addressed store, hash-verified

771 self._next_seq_id = (self._next_seq_id + 1) % 256
772
773 def _read_packet(self, packet_type=MysqlPacket):
774 """Read an entire "mysql packet" in its entirety from the network
775 and return a MysqlPacket type that represents the results.
776
777 :raise OperationalError: If the connection to the MySQL server is lost.
778 :raise InternalError: If the packet sequence number is wrong.
779 """
780 # Although `socket.settimeout()` may appear fast, it temporarily releases
781 # the GIL, which can hurt performance in multithreaded applications.
782 # Avoid calling it repeatedly at high frequency.
783 if self._current_timeout != self._read_timeout:
784 self._sock.settimeout(self._read_timeout)
785 self._current_timeout = self._read_timeout
786
787 buff = []
788 while True:
789 packet_header = self._read_bytes(4)
790 # if DEBUG: dump_packet(packet_header)
791
792 btrl, btrh, packet_number = struct.unpack("<HBB", packet_header)
793 bytes_to_read = btrl + (btrh << 16)
794 if packet_number != self._next_seq_id:
795 self._force_close()
796 if packet_number == 0:
797 # MariaDB sends error packet with seqno==0 when shutdown
798 raise err.OperationalError(
799 CR.CR_SERVER_LOST,
800 "Lost connection to MySQL server during query",
801 )
802 raise err.InternalError(
803 "Packet sequence number wrong - got %d expected %d"
804 % (packet_number, self._next_seq_id)
805 )
806 self._next_seq_id = (self._next_seq_id + 1) % 256
807
808 recv_data = self._read_bytes(bytes_to_read)
809 if DEBUG:
810 dump_packet(recv_data)
811 buff.append(recv_data)
812 # https://dev.mysql.com/doc/internals/en/sending-more-than-16mbyte.html
813 if bytes_to_read < MAX_PACKET_LEN:
814 break
815
816 packet = packet_type(b"".join(buff), self.encoding)
817 if packet.is_error_packet():
818 if self._result is not None and self._result.unbuffered_active is True:
819 self._result.unbuffered_active = False
820 packet.raise_for_error()
821 return packet
822
823 def _read_bytes(self, num_bytes):
824 # NOTE: caller should call self._sock.settimeout(self._read_timeout)

Callers 15

_read_ok_packetMethod · 0.95
set_character_setMethod · 0.95
_process_authMethod · 0.95
_roundtripFunction · 0.80
readMethod · 0.80
init_unbuffered_queryMethod · 0.80

Calls 5

_read_bytesMethod · 0.95
_force_closeMethod · 0.95
dump_packetFunction · 0.85
is_error_packetMethod · 0.80
raise_for_errorMethod · 0.80

Tested by 4

authenticateMethod · 0.64
authenticateMethod · 0.64
authenticateMethod · 0.64
authenticateMethod · 0.64