dbrew5
dbrew5

Reputation: 49

Execute CQL queries from file using the datastax Python Cassandra driver

What I'm trying to do is load a CQL file to re-initialize (drop and create) all the tables in a keyspace.

I've search through the documentation at https://datastax.github.io/python-driver/ but didn't find any immediate way of accomplishing this.

SOURCE doesn't work since it's a cqlsh command. I've tried reading the file in as input and running that, but encounter errors because execute() only runs a single line. My last option would be to parse the file and run each CQL command, but that's a lot of hassle for a simple request.

Currently, the closest I've gotten is executing the file during a read, as shown below. This is where I get issues with EOL due to the semi-colons.

with app.open_resource('schema.cql', mode='r') as f:
    db.execute(f.read())

Upvotes: 3

Views: 2151

Answers (1)

Alex Ott
Alex Ott

Reputation: 87259

You can read file as a whole, and then split on ; character as in following code. The drawback of this solution is that it's very primitive - it doesn't handle ; character that could exist in comments, etc. But for simple cases this could be ok (imho)...

with open('create_schema.cql', mode='r') as f:
    txt = f.read()
    stmts = txt.split(r';')
    for i in stmts:
        stmt = i.strip()
        if stmt != '':
            print('Executing "' + stmt + '"')
            session.execute(stmt)

Update: if you're using this to execute schema change statements (create/delete/alter), then you need to check for schema agreement after execution of every statement it

Upvotes: 3

Related Questions