Read an entire "mysql packet" in its entirety from the network
        and return a MysqlPacket type that represents the results.
355432
async def _read_packet(self, packet_type=MysqlPacket):
        
        buff = b''
        while True:
            try:
                packet_header = await self._read_bytes(4)
            except asyncio.CancelledError:
                self._close_on_cancel()
                raise

            btrl, btrh, packet_number = struct.unpack(
                '<HBB', packet_header)
            bytes_to_read = btrl + (btrh << 16)

            # Outbound and inbound packets are numbered sequentialy, so
            # we increment in both write_packet and read_packet. The count
            # is reset at new COMMAND PHASE.
            if packet_number != self._next_seq_id:
                raise InternalError(
                    "Packet sequence number wrong - got %d expected %d" %
                    (packet_number, self._next_seq_id))
            self._next_seq_id = (self._next_seq_id + 1) % 256

            try:
                recv_data = await self._read_bytes(bytes_to_read)
            except asyncio.CancelledError:
                self._close_on_cancel()
                raise

            buff += recv_data
            # https://dev.mysql.com/doc/internals/en/sending-more-than-16mbyte.html
            if bytes_to_read == 0xffffff:
                continue
            if bytes_to_read < MAX_PACKET_LEN:
                break

        packet = packet_type(buff, self._encoding)
        packet.check_error()
        return packet
344886
def _sense_packet_to_data(packet):
        """"""
        data = bytearray(0)
        last = 0
        i = 1
        while (i < len(packet)):
            if not (last == 2 and packet[i] == 0):
                data.append(packet[i])
            last = packet[i]
            i += 1

        return data
1236672
def decode_network_packet(buf):
    
    off = 0
    blen = len(buf)

    while off < blen:
        ptype, plen = header.unpack_from(buf, off)

        if plen > blen - off:
            raise ValueError("Packet longer than amount of data in buffer")

        if ptype not in _decoders:
            raise ValueError("Message type %i not recognized" % ptype)

        yield ptype, _decoders[ptype](ptype, plen, buf[off:])
        off += plen
431232
public static MySQLCommandPacket newInstance(final MySQLCommandPacketType commandPacketType, final MySQLPacketPayload payload) throws SQLException {
        switch (commandPacketType) {
            case COM_QUIT:
                return new MySQLComQuitPacket();
            case COM_INIT_DB:
                return new MySQLComInitDbPacket(payload);
            case COM_FIELD_LIST:
                return new MySQLComFieldListPacket(payload);
            case COM_QUERY:
                return new MySQLComQueryPacket(payload);
            case COM_STMT_PREPARE:
                return new MySQLComStmtPreparePacket(payload);
            case COM_STMT_EXECUTE:
                return new MySQLComStmtExecutePacket(payload);
            case COM_STMT_CLOSE:
                return new MySQLComStmtClosePacket(payload);
            case COM_PING:
                return new MySQLComPingPacket();
            default:
                return new MySQLUnsupportedCommandPacket(commandPacketType);
        }
    }
797395
def read(self, length, dummy=None):
    """"""
    assert not self.closed
    data = self.expected_read_data.pop(0)
    if length < len(data):
      raise ValueError(
          'Overflow packet length. Read %d bytes, got %d bytes: %s',
          length, len(data), self._dotify(data))
    return data
1254883
def _parse(self, e):
        """"""

        # MySQL
        matches = re.search(r"^\(_mysql_exceptions\.OperationalError\) \(\d+, \"(.+)\"\)$", str(e))
        if matches:
            return matches.group(1)

        # PostgreSQL
        matches = re.search(r"^\(psycopg2\.OperationalError\) (.+)$", str(e))
        if matches:
            return matches.group(1)

        # SQLite
        matches = re.search(r"^\(sqlite3\.OperationalError\) (.+)$", str(e))
        if matches:
            return matches.group(1)

        # Default
        return str(e)
589060
private int readPacket(byte[] packet, int offset, int psize)
            throws IOException {
        int length = 0;
        try {
            while (length < psize) {
                int len = stream.read(packet, offset + length, psize - length);
                if (len == -1) {
                    return length;
                }
                length += len;
            }
            return length;
        } catch (Exception e) {
        	logger.error(e);
        }
        return length;
    }
1191559
public static function load()
    {
        if (!extension_loaded('opencensus')) {
            trigger_error('opencensus extension required to load mysqli integrations.', E_USER_WARNING);
            return;
        }

        // mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
        opencensus_trace_function('mysqli_query', function ($mysqli, $query) {
            return [
                'attributes' => ['query' => $query],
                'kind' => Span::KIND_CLIENT
            ];
        });

        // mysqli_stmt mysqli_prepare ( mysqli $link , string $query )
        opencensus_trace_function('mysqli_prepare', function ($mysqli, $query) {
            return [
                'attributes' => ['query' => $query],
                'kind' => Span::KIND_CLIENT
            ];
        });

        // bool mysqli_commit ( mysqli $link [, int $flags [, string $name ]] )
        opencensus_trace_function('mysqli_commit', function ($mysqli) {
            if (func_num_args() > 2) {
                return [
                    'attributes' => [
                        'name' => func_get_arg(2)
                    ],
                    'kind' => Span::KIND_CLIENT
                ];
            } else {
                return ['kind' => Span::KIND_CLIENT];
            }
        });

        // mysqli mysqli_connect ([ string $host = ini_get("mysqli.default_host")
        //      [, string $username = ini_get("mysqli.default_user")
        //      [, string $passwd = ini_get("mysqli.default_pw")
        //      [, string $dbname = ""
        //      [, int $port = ini_get("mysqli.default_port")
        //      [, string $socket = ini_get("mysqli.default_socket") ]]]]]] )
        opencensus_trace_function('mysqli_connect', function ($host) {
            return [
                'attributes' => ['host' => $host],
                'kind' => Span::KIND_CLIENT
            ];
        });

        // bool mysqli_stmt_execute ( mysqli_stmt $stmt )
        opencensus_trace_function('mysqli_stmt_execute', function () {
            return ['kind' => Span::KIND_CLIENT];
        });

        // mixed mysqli::query ( string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
        opencensus_trace_method('mysqli', 'query', function ($mysqli, $query) {
            return [
                'attributes' => ['query' => $query],
                'kind' => Span::KIND_CLIENT
            ];
        });

        // mysqli_stmt mysqli::prepare ( string $query )
        opencensus_trace_method('mysqli', 'prepare', function ($mysqli, $query) {
            return [
                'attributes' => ['query' => $query],
                'kind' => Span::KIND_CLIENT
            ];
        });

        // bool mysqli::commit ([ int $flags [, string $name ]] )
        opencensus_trace_method('mysqli', 'commit', function ($mysqli) {
            if (func_num_args() > 1) {
                return [
                    'attributes' => [
                        'name' => func_get_arg(1)
                    ],
                    'kind' => Span::KIND_CLIENT
                ];
            } else {
                return ['kind' => Span::KIND_CLIENT];
            }
        });

        // mysqli::__construct ([ string $host = ini_get("mysqli.default_host")
        //      [, string $username = ini_get("mysqli.default_user")
        //      [, string $passwd = ini_get("mysqli.default_pw")
        //      [, string $dbname = ""
        //      [, int $port = ini_get("mysqli.default_port")
        //      [, string $socket = ini_get("mysqli.default_socket") ]]]]]] )
        opencensus_trace_method('mysqli', '__construct', function ($mysqli, $host) {
            return [
                'attributes' => ['host' => $host],
                'kind' => Span::KIND_CLIENT
            ];
        });

        // bool mysqli_stmt::execute ( void )
        opencensus_trace_method('mysqli_stmt', 'execute', function () {
            return ['kind' => Span::KIND_CLIENT];
        });
    }
774914
def from_bytes(self, raw):
        ''''''
        if len(raw) < Ethernet._MINLEN:
            raise NotEnoughDataError("Not enough bytes ({}) to reconstruct an "
                "Ethernet object".format(len(raw)))
        dst,src,ethertype = struct.unpack(Ethernet._PACKFMT, 
            raw[:Ethernet._MINLEN])
        self.src = src
        self.dst = dst
        if ethertype <= 1500:
            self.ethertype = EtherType.NoType
        else:
            self.ethertype = ethertype
        return raw[Ethernet._MINLEN:]
615228
def full_datatype_to_mysql(d: str) -> str:
    """"""
    d = d.upper()
    (s, length) = split_long_sqltype(d)
    if d in ["VARCHAR(MAX)", "NVARCHAR(MAX)"]:
        # http://wiki.ispirer.com/sqlways/mysql/data-types/longtext
        return "LONGTEXT"
    elif d in ["VARBINARY(MAX)"] or s in ["IMAGE"]:
        # http://wiki.ispirer.com/sqlways/mysql/data-types/varbinary
        return "LONGBLOB"
    else:
        return d
727652
static function read($key)
	{
		$conn	= ADODB_Session::_conn();
		$filter	= ADODB_Session::filter();
		$table	= ADODB_Session::table();

		if (!$conn) {
			return '';
		}

		//assert('$table');

		$binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : '';

		global $ADODB_SESSION_SELECT_FIELDS;
		if (!isset($ADODB_SESSION_SELECT_FIELDS)) $ADODB_SESSION_SELECT_FIELDS = 'sessdata';
		$sql = "SELECT $ADODB_SESSION_SELECT_FIELDS FROM $table WHERE sesskey = $binary ".$conn->Param(0)." AND expiry >= " . $conn->sysTimeStamp;

		/* Lock code does not work as it needs to hold transaction within whole page, and we don't know if
		  developer has commited elsewhere... :(
		 */
		#if (ADODB_Session::Lock())
		#	$rs = $conn->RowLock($table, "$binary sesskey = $qkey AND expiry >= " . time(), sessdata);
		#else
			$rs = $conn->Execute($sql, array($key));
		//ADODB_Session::_dumprs($rs);
		if ($rs) {
			if ($rs->EOF) {
				$v = '';
			} else {
				$v = reset($rs->fields);
				$filter = array_reverse($filter);
				foreach ($filter as $f) {
					if (is_object($f)) {
						$v = $f->read($v, ADODB_Session::_sessionKey());
					}
				}
				$v = rawurldecode($v);
			}

			$rs->Close();

			ADODB_Session::_crc(strlen($v) . crc32($v));
			return $v;
		}

		return '';
	}
1176612
def read_all(self):
        
        result = self._cursor.execute("SELECT * FROM {}".format(self.table_name)).fetchall()
        return (SqliteReader._assemble_message(frame) for frame in result)
1340919
def read_all(socket)
      total_bytes = socket.recv(4).unpack("V")[0]
      if total_bytes and total_bytes > 0
        socket.recv(total_bytes)
      else
        ''
      end
    end
329347
def read(self):
        
        """
        # Read until we have a \0 in our buffer.
        while b'\0' not in self._recv_buffer:
            self._recv_buffer += yield From(_read_chunk_from_socket(self.socket))

        # Split on the first separator.
        pos = self._recv_buffer.index(b'\0')

        packet = self._recv_buffer[:pos]
        self._recv_buffer = self._recv_buffer[pos + 1:]

        raise Return(packet)
574096
def __read_single_query_result(rs, field_names):
    '''
    
    '''

    rf = StringIO.StringIO(rs)

    def readline():
        l = rf.readline()
        if not l.endswith('\n'):
            raise EOFError()
        return l.strip()

    result = Result()

    try:
        l = readline()
        assert l.startswith('# BLAST')

        l = readline()
        assert l.startswith('# Query: ')
        query_str = l[len('# Query: '):].strip()
        if query_str:
            if ' ' in query_str:
                result.id, result.description = [
                    s.strip() for s in query_str.split(' ', 1)]
            else:
                result.id = query_str

        l = readline()
        assert l.startswith('# Database: ')

        l = readline()
        if l.startswith('# Fields: '):
            fns = l[len('# Fields: '):].split(', ')
            assert len(field_names) == len(fns)
            l = readline()

        assert l.endswith(' hits found')
        nhits = int(l[len('# '):-1 * len(' hits found')])

        while nhits > 0:
            l = readline()
            field_vals = l.split('\t')
            assert len(field_vals) == len(field_names)

            fields = dict(zip(field_names, field_vals))
            result.hits.append(Hit(fields))
            nhits -= 1

        return result, rf.read()
    except EOFError:
        return None, rs
1964
function read($session_id)
    {

        // get the lock name, associated with the current session
        $this->session_lock = $this->_mysql_real_escape_string('session_' . $session_id);

        // try to obtain a lock with the given name and timeout
        $result = $this->_mysql_query('SELECT GET_LOCK("' . $this->session_lock . '", ' . $this->_mysql_real_escape_string($this->lock_timeout) . ')');

        // if there was an error
        // stop execution
        if (!is_object($result) || strtolower(get_class($result)) != 'mysqli_result' || @mysqli_num_rows($result) != 1 || !($row = mysqli_fetch_array($result)) || $row[0] != 1) die('Session Worker: Could not obtain session lock!');

        //  reads session data associated with a session id, but only if
        //  -   the session ID exists;
        //  -   the session has not expired;
        //  -   if lock_to_user_agent is TRUE and the HTTP_USER_AGENT is the same as the one who had previously been associated with this particular session;
        //  -   if lock_to_ip is TRUE and the host is the same as the one who had previously been associated with this particular session;
        $hash = '';

        // if we need to identify sessions by also checking the user agent
        if ($this->lock_to_user_agent && isset($_SERVER['HTTP_USER_AGENT']))

            $hash .= $_SERVER['HTTP_USER_AGENT'];

        // if we need to identify sessions by also checking the host
        if ($this->lock_to_ip && isset($_SERVER['REMOTE_ADDR']))

            $hash .= $_SERVER['REMOTE_ADDR'];

        // append this to the end
        $hash .= $this->security_code;

        $result = $this->_mysql_query('

            SELECT
                session_data
            FROM
                ' . $this->table_name . '
            WHERE
                session_id = "' . $this->_mysql_real_escape_string($session_id) . '" AND
                session_expire > "' . time() . '" AND
                hash = "' . $this->_mysql_real_escape_string(md5($hash)) . '"
            LIMIT 1

        ') or die($this->_mysql_error());

        // if anything was found
        if (is_object($result) && strtolower(get_class($result)) == 'mysqli_result' && @mysqli_num_rows($result) > 0) {

            // return found data
            $fields = @mysqli_fetch_assoc($result);

            // don't bother with the unserialization - PHP handles this automatically
            return $fields['session_data'];

        }

        $this->regenerate_id();

        // on error return an empty string - this HAS to be an empty string
        return '';

    }
263037
def read_whole_packet(self):
        
        self._read_packet()
        return readall(self, self._size - _header.size)