Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def __init__(self, unix_sock=None, host=None, port=5432, socket_timeout=60, ssl=False):
self._client_encoding = "ascii"
if unix_sock == None and host != None:
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
elif unix_sock != None:
self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
else:
raise ProgrammingError("one of host or unix_sock must be provided")
if unix_sock == None and host != None:
self._sock.connect((host, port))
elif unix_sock != None:
self._sock.connect(unix_sock)
if ssl:
self._send(Protocol.SSLRequest())
resp = self._sock.recv(1)
if resp == 'S':
self._sock = Protocol.SSLWrapper(socket.ssl(self._sock))
else:
raise InterfaceError("server refuses SSL")
else:
# settimeout causes ssl failure, on windows. Python bug 1462352.
self._sock.settimeout(socket_timeout)
self._state = "noauth"
self._backend_key_data = None
self._sock_lock = threading.Lock()
def __init__(self, name):
Protocol.Close.__init__(self, "P", name)
def bind(self, portal, statement, params, parse_data):
self.verifyState("ready")
self._sock_lock.acquire()
try:
row_desc, param_fc = parse_data
if row_desc == None:
# no data coming out
output_fc = ()
else:
# We've got row_desc that allows us to identify what we're going to
# get back from this statement.
output_fc = [Types.py_type_info(f) for f in row_desc.fields]
self._send(Protocol.Bind(portal, statement, param_fc, params, output_fc, self._client_encoding))
# We need to describe the portal after bind, since the return
# format codes will be different (hopefully, always what we
# requested).
self._send(Protocol.DescribePortal(portal))
self._send(Protocol.Flush())
while 1:
msg = self._read_message()
if isinstance(msg, Protocol.BindComplete):
# good news everybody!
pass
elif isinstance(msg, Protocol.NoData):
# No data means we should execute this command right away.
self._send(Protocol.Execute(portal, 0))
self._send(Protocol.Sync())
exc = None
while 1:
if row_desc == None:
# no data coming out
output_fc = ()
else:
# We've got row_desc that allows us to identify what we're going to
# get back from this statement.
output_fc = [Types.py_type_info(f) for f in row_desc.fields]
self._send(Protocol.Bind(portal, statement, param_fc, params, output_fc, self._client_encoding))
# We need to describe the portal after bind, since the return
# format codes will be different (hopefully, always what we
# requested).
self._send(Protocol.DescribePortal(portal))
self._send(Protocol.Flush())
while 1:
msg = self._read_message()
if isinstance(msg, Protocol.BindComplete):
# good news everybody!
pass
elif isinstance(msg, Protocol.NoData):
# No data means we should execute this command right away.
self._send(Protocol.Execute(portal, 0))
self._send(Protocol.Sync())
exc = None
while 1:
msg = self._read_message()
if isinstance(msg, Protocol.CommandComplete):
# more good news!
pass
elif isinstance(msg, Protocol.ReadyForQuery):
if exc != None:
raise exc
break
def createFromData(data):
count = struct.unpack("!h", data[:2])[0]
data = data[2:]
fields = []
for i in range(count):
val_len = struct.unpack("!i", data[:4])[0]
data = data[4:]
if val_len == -1:
fields.append(None)
else:
fields.append(data[:val_len])
data = data[val_len:]
return Protocol.DataRow(fields)
createFromData = staticmethod(createFromData)
if isinstance(msg, Protocol.ParseComplete):
# ok, good.
pass
elif isinstance(msg, Protocol.ParameterDescription):
# well, we don't really care -- we're going to send whatever
# we want and let the database deal with it. But thanks
# anyways!
pass
elif isinstance(msg, Protocol.NoData):
# We're not waiting for a row description. Return
# something destinctive to let bind know that there is no
# output.
return (None, param_fc)
elif isinstance(msg, Protocol.RowDescription):
return (msg, param_fc)
elif isinstance(msg, Protocol.ErrorResponse):
raise msg.createException()
else:
raise InternalError("Unexpected response msg %r" % (msg))
finally:
self._sock_lock.release()
self.verifyState("ready")
self._sock_lock.acquire()
try:
row_desc, param_fc = parse_data
if row_desc == None:
# no data coming out
output_fc = ()
else:
# We've got row_desc that allows us to identify what we're going to
# get back from this statement.
output_fc = [Types.py_type_info(f) for f in row_desc.fields]
self._send(Protocol.Bind(portal, statement, param_fc, params, output_fc, self._client_encoding))
# We need to describe the portal after bind, since the return
# format codes will be different (hopefully, always what we
# requested).
self._send(Protocol.DescribePortal(portal))
self._send(Protocol.Flush())
while 1:
msg = self._read_message()
if isinstance(msg, Protocol.BindComplete):
# good news everybody!
pass
elif isinstance(msg, Protocol.NoData):
# No data means we should execute this command right away.
self._send(Protocol.Execute(portal, 0))
self._send(Protocol.Sync())
exc = None
while 1:
msg = self._read_message()
if isinstance(msg, Protocol.CommandComplete):
# more good news!
pass
def fetch_rows(self, portal, row_count, row_desc):
self.verifyState("ready")
self._sock_lock.acquire()
try:
self._send(Protocol.Execute(portal, row_count))
self._send(Protocol.Flush())
rows = []
end_of_data = False
while 1:
msg = self._read_message()
if isinstance(msg, Protocol.DataRow):
rows.append(
[Types.py_value(msg.fields[i], row_desc.fields[i], client_encoding=self._client_encoding)
for i in range(len(msg.fields))]
)
elif isinstance(msg, Protocol.PortalSuspended):
# got all the rows we asked for, but not all that exist
break
elif isinstance(msg, Protocol.CommandComplete):
self._send(Protocol.ClosePortal(portal))
self._send(Protocol.Sync())
while 1:
def __init__(self, user, host=None, unix_sock=None, port=5432, database=None, password=None, socket_timeout=60, ssl=False):
self._row_desc = None
try:
self.c = Protocol.Connection(unix_sock=unix_sock, host=host, port=port, socket_timeout=socket_timeout, ssl=ssl)
#self.c.connect()
self.c.authenticate(user, password=password, database=database)
except socket.error, e:
print repr(e)
print dir(e)
print str(e)
raise InterfaceError("communication error", e)
Cursor.__init__(self, self)
self._begin = PreparedStatement(self, "BEGIN TRANSACTION")
self._commit = PreparedStatement(self, "COMMIT TRANSACTION")
self._rollback = PreparedStatement(self, "ROLLBACK TRANSACTION")
def authenticate(self, user, **kwargs):
self.verifyState("noauth")
self._send(Protocol.StartupMessage(user, database=kwargs.get("database",None)))
msg = self._read_message()
if isinstance(msg, Protocol.AuthenticationRequest):
if msg.ok(self, user, **kwargs):
self._state = "auth"
while 1:
msg = self._read_message()
if isinstance(msg, Protocol.ReadyForQuery):
# done reading messages
self._state = "ready"
break
elif isinstance(msg, Protocol.ParameterStatus):
if msg.key == "client_encoding":
self._client_encoding = msg.value
elif isinstance(msg, Protocol.BackendKeyData):
self._backend_key_data = msg
elif isinstance(msg, Protocol.ErrorResponse):
raise msg.createException()
else:
raise InternalError("unexpected msg %r" % msg)
else:
raise InterfaceError("authentication method %s failed" % msg.__class__.__name__)
else:
raise InternalError("StartupMessage was responded to with non-AuthenticationRequest msg %r" % msg)