Fork me on GitHub
#sql
<
2020-11-23
>
Daniel Östling14:11:21

Hello 🙂 I’m playing around with SQLite+next.jdbc, and I wonder how to deal with SQLite PRAGMA statements. Is it possible to have them defined in the data source or something?

seancorfield18:11:07

@danielostling Can you give specific examples? (I use MySQL mainly so I don't know what sort of thing you're talking about)

Daniel Östling19:11:56

Sure! I was trying to get the foreign_keys pragma to work for SQLite, to get on delete cascade behavior, as seen here: https://www.sqlite.org/foreignkeys.html#fk_actions It works when done in a console session with the sqlite3 binary, but I was not able to make it work with jdbc/execute-one!, sql/delete! or the same wrapped in jdbc/with-transaction where I would put the pragma in a separate jdbc/execute-one! statement before the actual SQL delete

Daniel Östling19:11:14

So, one example of me not getting this to work is

(defn remove-policy
  "Remove a policy."
  [policy-id]
  (let [data-source (db-get-ds)]
    (jdbc/with-transaction [tx data-source]
      (jdbc/execute! tx ["pragma foreign_keys=on"])
      (jdbc/execute! tx ["delete from policy where id = ?" policy-id])))

Daniel Östling19:11:19

Oh, it’s actually execute!, not execute-one! I now realize. Not sure if that matters though.

seancorfield19:11:47

Under the hood, those behave the same way, but execute-one! only returns one "result" -- a hash map -- regardless of how many rows you have in the result. execute! always returns a vector of hash maps, even when the result only contains one row.

seancorfield19:11:06

(so: it doesn't matter)

seancorfield20:11:51

https://stackoverflow.com/questions/9958382/sqlite-jdbc-pragma-setting seems to suggest that you need to use a particular JDBC pooling library to make this happen?

seancorfield20:11:29

Although looking at the source of the SQLite JDBC driver suggests that you might be able to pass these as connection options, directly creating the connection...

seancorfield20:11:10

Passing :foreign_keys true in your db-spec when you make a connection might be enough to make that work @danielostling

seancorfield20:11:40

i.e., {:dbtype "sqlite" :dbname "yourdb" :foreign_keys true}

Daniel Östling20:11:49

Hm, does that replace jdbc/get-datasource or where should that be used?

seancorfield20:11:50

(or it might need to be :foreignKeys true)

seancorfield20:11:06

How are you specifying your connection details?

seancorfield20:11:19

As a hash map (recommended) or as a jdbc: string?

Daniel Östling20:11:49

“jdbc:sqlite:some-db.db”

Daniel Östling20:11:31

I’ll switch to what I should be doing, that’s my inexperience showing 🙂

Daniel Östling20:11:29

I’ll try it out a bit. Thanks for the help, I appreciate it. And thanks for next.jdbc, very useful 🙂