exxeleron / qPython

interprocess communication between Python and kdb+
http://www.devnet.de
Apache License 2.0
152 stars 89 forks source link

Trouble executing commands using conn.query() #31

Closed lcota closed 8 years ago

lcota commented 8 years ago

Sample code:

qc = QConnection(host='localhost', port=5000).open()
# this does not work. tbl is not created as an empty table on the server
qc.query(MessageType.SYNC, "tbl: ([] col1: (); col2: ())") 

# this one does work, and creates x on the server
qc.query(MessageType.SYNC, "x: 12345") 
maciejlach commented 8 years ago

QConnection.query() is a low level method, which does sent a query to q process, but doesn't read the result. Thus it requires manual call to the QConnection.receive() method to read the response from q process.

For details, please refer to the implementation of QConnection.sync() method:

def sync(self, query, *parameters, **options):
    self.query(MessageType.SYNC, query, *parameters, **options)
    response = self.receive(data_only = False, **options)

    if response.type == MessageType.RESPONSE:
        return response.data
    else:
        self._writer.write(QException('nyi: qPython expected response message'), MessageType.ASYNC if response.type == MessageType.ASYNC else MessageType.RESPONSE)
        raise QReaderException('Received message of type: %s where response was expected')

Here is a modified code sample from your use case. It uses pair query() & receive() calls, as well as shortened syntax via sync() call:

with qconnection.QConnection(host='localhost', port=5000, single_char_strings = True) as q:
    print 'Query result: ', q.sync('t1: ([] col1: (); col2: ())')
    print 'Table: ', q('t1')

    q.query(MessageType.SYNC, 't2: flip `name`iq!(`Dent`Beeblebrox`Prefect;98 42 126)')
    print 'Query result: ', q.receive()
    print 'Table: ', q('t2')

Which produces following output:

Query result:  None
Table:  []
Query result:  None
Table:  [('Dent', 98L) ('Beeblebrox', 42L) ('Prefect', 126L)]

Note that response from q process to the table creation is an generic q null.

Tables are also accessible via q interpreter:

q)t1
col1 col2
---------
q)t2
name       iq
--------------
Dent       98
Beeblebrox 42
Prefect    126