Cassandra Python executing multiple statement from string using python drive?

993 views Asked by At

I want to execute multiple cql statements (2 or much more) using python driver.

I try such simple code but it lead to error if query contains more then one statement. I do not want to split statements or format it (to single statements). I just want to execute whole CQL.

How to do it with python driver for Cassandra - is it possible?

I use ; as statement split.

from cassandra.cluster import Cluster


def main():
    cluster = Cluster(contact_points=['cassandra-1.', 'cassandra-2.', 'cassandra-3.', 'cassandra-4.'])
    session = cluster.connect()
    session.execute('drop keyspace if exists test')
    session.execute('''
        create keyspace test
        with durable_writes = true
        and replication = {
            'class' : 'SimpleStrategy',
            'replication_factor' : 3
        };    
    ''')
    session.set_keyspace('test')

    # two statements or more and there is error
    # how to execute all in one call?
    query = '''\
    create table x1 (
        name text,
        
        primary key ((name))
    );

    create table x2 (
        name text,
        
        primary key ((name))
    );
    '''

    result_set = session.execute(query)
    print(result_set)


if __name__ == '__main__':
    main()

It generates such error:

Traceback (most recent call last):
  File "C:\Users\Cezary Wagner\PycharmProjects\medptr-v2\sandbox\cassandra_scheme\04_execute_multiple_statements.py", line 39, in <module>
    main()
  File "C:\Users\Cezary Wagner\PycharmProjects\medptr-v2\sandbox\cassandra_scheme\04_execute_multiple_statements.py", line 34, in main
    result_set = session.execute(query)
  File "cassandra\cluster.py", line 2618, in cassandra.cluster.Session.execute
  File "cassandra\cluster.py", line 4894, in cassandra.cluster.ResponseFuture.result
cassandra.protocol.SyntaxException: <Error from server: code=2000 [Syntax error in CQL query] message="line 7:4 mismatched input 'create' expecting EOF (... ((name))    );    [create]...)">
1

There are 1 answers

9
Alex Ott On

Each statement should be separate. Just split text on ; using your Python code, and execute them separately. Also, please take into account that programmatic schema modifications like yours are potentially dangerous - you may get so-called schema disagreement that will require to fix it by rolling restart of the cluster.