简体   繁体   中英

Catching a specific exception on a drop column CQL statement in Clojure

I want to run a drop-column CQL statement on a table that may or may not have that column exist. Ideally I would like to do a if-exists then drop column, but I do not believe CQL supports that.

My work around is to catch an invalid query exception, but that is not working and I cannot figure out why. In the following code, the generic Except will hit giving the message " com.datastax.driver.core.exceptions.InvalidQueryException: Column my_col was not found in table my_table ". I have no idea why my InvalidQueryException is not hitting.

(ns my-namespace
  (:require [qbits
              [alia :as alia]
              [hayt :as hayt]]))

(defn prepared-statement
  [session]
  (try
     (alia/execute session
                   (hayt/alter-table :my_table
                                     (hayt/drop-column :my_col)))
     (catch com.datastax.driver.core.exceptions.InvalidQueryException ie
       (prn "your column doesn't exist"))
     (catch Exception e
       (prn (ex-data e)))))

Look at the source for alia/execute . As you can see, it already contains its own try catch block with only Exception .

So, you have to call execute method of CqlSession (and use hayt/->raw to create query string):

(:import (com.datastax.oss.driver.api.core.servererrors InvalidQueryException))

(defn prepared-statement
  [session]
  (try (.execute session
              (hayt/->raw (hayt/alter-table :my_table
                                            (hayt/drop-column :my_col))))
    (catch InvalidQueryException ie
      (prn "your column doesn't exist"))
    (catch Exception e
      (prn (ex-data e)))))

Test:

(prepared-statement s)
"your column doesn't exist"
=> nil

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM