How can I make a Clojure program that interfaces with a PostgreSQL database?
- User
How can I make a Clojure program that interfaces with a PostgreSQL database?
- Assistant
To interface with a PostgreSQL database from a Clojure program, you can use the
clojure.java.jdbclibrary, which provides a simple interface to interact with relational databases, or thenext.jdbclibrary, which is the successor to clojure.java.jdbc. Here, we'll focus on usingnext.jdbcas it's the recommended way to go as of my knowledge cutoff in 2023.First, you need to add the necessary dependencies to your
project.cljfile if you're using Leiningen, or to yourdeps.ednfile if you're using Clojure CLI tools.For Leiningen:
(defproject your-project "0.1.0-SNAPSHOT" :dependencies [ [org.clojure/clojure "1.10.3"] [seancorfield/next.jdbc "1.3.8"] ;; Check for the latest version [org.postgresql/postgresql "42.5.0"] ;; Check for the latest PostgreSQL JDBC driver ])For Clojure CLI (
deps.edn):{:deps {org.clojure/clojure {:mvn/version "1.10.3"} seancorfield/next.jdbc {:mvn/version "1.3.8"} org.postgresql/postgresql {:mvn/version "42.5.0"}}}Next, you can write Clojure code to connect to your PostgreSQL database and perform various operations.
Here's an example of how you might set up a Clojure program that interfaces with a PostgreSQL database:
(ns your-project.db.core (:require [next.jdbc :as jdbc])) ;; Define the database connection details (def db-spec {:dbtype "postgresql" :dbname "your_db_name" :user "your_username" :password "your_password" :host "localhost" ;; or another host if the database is remote :port 5432}) ;; Function to connect and perform a simple query (defn fetch-users [] (jdbc/with-connection db-spec (jdbc/with-open [r (jdbc/execute! db-spec ["SELECT * FROM users"])] (jdbc/result-set r)))) ;; Function to insert a new user (defn insert-user [user-name email] (jdbc/with-transaction [tx db-spec] (jdbc/execute! tx ["INSERT INTO users (name, email) VALUES (?, ?)" user-name email]))) ;; You might also want to create a utility function for connection pooling ;; using `hikari-cp` or a similar library for pooling connections in productionMake sure you replace
your_db_name,your_username, andyour_passwordwith the actual details of your PostgreSQL database, and modify the SQL queries to match your schema and tables.To run the code you've written, you'll typically do so as part of a larger application or by invoking the Clojure REPL and loading the namespace where your code resides.
Please note that this example uses raw SQL queries. In more complex scenarios, you may want to consider using an ORM (Object-Relational Mapping) library or DSL (Domain-Specific Language) for SQL, like HoneySQL, which provides a more Clojure-like way of constructing SQL queries.
Always remember to manage your database resources properly. Use connection pooling in production settings to handle concurrent connections efficiently. Libraries like
hikari-cpcan be used in conjunction withnext.jdbcfor connection pooling. - User
Here is the code I plan on interfacing with the database so far.
(ns assignments.PAUL-OMAKI.game-core (:require [clojure.pprint] [clojure.string :as str] [compojure.coercions :refer [as-int]] [compojure.core :refer [ANY defroutes GET POST]] [ring.adapter.jetty :refer [run-jetty]] [ring.middleware.defaults :as middleware] [ring.middleware.cookies :as cookies] [ring.middleware.multipart-params :as multi] [ring.util.response :as ring :refer [not-found redirect response status]] [assignments.PAUL-OMAKI.simple-game :as game] [assignments.PAUL-OMAKI.db-core :as db] [byte-transforms :as transforms]))
(defn set-session-cookie [response username] (ring/set-cookie response "token" (transforms/hash username :crc32) {:max-age 3600})) ; Set cookie with a maximum age of 1 hour
(defn get-session-cookie [request] (get-in request [:cookies "token" :value]))
(defn new-game-handler [request] (when (game/new-game! (get-session-cookie request)) (response (str "OK - start guessing at /guess/?guess=N"))))
(defn form-sanitizer [input] (str/lower-case (str/trim input)))
(defn valid-login? [token password] ;; placeholder login logic... (or (and (= token "foo") (= password "bar")) (and (= token "admin") (= password "123")) (and (= token "user") (= password "pass")) (and (= token "egg") (= password "man")) (and (= token "test") (= password "test"))))
;; tried to combine these functions but the login page is very fragile (defn login-page-handler [] (response (slurp "res/login.html"))) ;; (defn guess-page-handler [] ;; (response (slurp "res/guess.html")))
(defn login-handler [request] (let [params (:form-params request) username (form-sanitizer (get params "username")) password (get params "password")] (if (valid-login? username password) (-> (redirect "/new-game") (set-session-cookie username)) ;; (redirect (str "/new-game/" token)) (response "Invalid login. Try again."))))
(defn guess-handler [guess user-hash] (condp = (game/guess-answer guess user-hash) nil (-> (response "You need to supply a guess with /guess?guess=N") (status 400)) :game-win (response (str "Congratulations! You win!")) :game-over (response "Too bad! You ran out of tries!") :too-low (response (str "Too low! " (get-in @game/games-in-progress [user-hash :remaining-tries]) " tries remaining!")) :too-high (response (str "Too high! " (get-in @game/games-in-progress [user-hash :remaining-tries]) " tries remaining!"))))
(defroutes site-routes (GET "/login" [] (login-page-handler)) (POST "/login" request (login-handler request))
(GET "/new-game" request (new-game-handler request)) ;; (GET "/guess:token" [token] (guess-page-handler token)) (GET "/guess" [guess :<< as-int :as request] (guess-handler guess (get-session-cookie request))) (ANY "*" [] (not-found (str "Sorry, no such URI on this server!\n\n Navigate to /new-game to start the guessing game.\n If you're in the middle of a game, go to /guess/?guess=N instead."))))
(defn add-content-type-htmltext-header [handler] (fn [request] (let [response (handler request)] (-> response (ring/header "Content-Type" "text/html")))))
(defn redirect-to-login-middleware "If a login cookie (at present, can be anything) is not found, redirects user to the login page." [handler] (fn [request] (let [token (get-session-cookie request)] (clojure.pprint/pprint request) (if (nil? token) (-> (handler (assoc request :uri "/login")) ; Redirect to /login (ring/header "Content-Type" "text/html")) (handler request)))))
(def handler (-> site-routes (redirect-to-login-middleware) (middleware/wrap-defaults middleware/api-defaults) (add-content-type-htmltext-header) (multi/wrap-multipart-params) (cookies/wrap-cookies)))
(defonce server (future (run-jetty #'handler {:port 3000 :join? false})))
(ns assignments.PAUL-OMAKI.simple-game)
(defonce games-in-progress (atom nil))
(defn new-game! [user-hash] ;; Make our new game:
(swap! games-in-progress assoc user-hash {:secret-num (+ 1 (rand-int 10)) :remaining-tries 6}) @games-in-progress :ok)(defn reset-game [user-hashcode] (swap! games-in-progress dissoc user-hashcode)) (defn failed-attempt [user-code] (swap! games-in-progress update-in user-code :remaining-tries dec)) (defn get-remaining-tries [user-code] (get-in @games-in-progress [user-code :remaining-tries])) (defn get-secret-num [user-code] (get-in @games-in-progress [user-code :secret-num]))
(defn guess-answer [guess user-hash] @games-in-progress (let [user user-hash] (cond (nil? guess) nil
(= guess (get-secret-num user)) (and (reset-game user) :game-win) (= 0 (get-remaining-tries user)) (and (reset-game user) :game-over) (< guess (get-secret-num user)) (and (failed-attempt user) :too-low) (> guess (get-secret-num user)) (and (failed-attempt user) :too-high))))(ns assignments.PAUL-OMAKI.db-core (:require [camel-snake-kebab.core :as csk] [cheshire.core :as json] [clj-http.client :as client] [medley.core :as m] [clojure.java.jdbc :as jdbc]))
(def db-conn {:dbtype "postgresql" :host "localhost" :dbname "postgres" :user "postgres" :password "postgres" :port 5432})
(defn insert-player [hash secret-num] (jdbc/execute! db-conn ["INSERT INTO games-in-progress (id, num, tries) VALUES ("hash", "secret-num", 6)"]))
(insert-player 23323 5) ;; test ; Execution error (PSQLException) at org.postgresql.core.v3.SimpleParameterList/bind (SimpleParameterList.java:70). ; The column index is out of range: 1, number of columns: 0.
- Assistant
You've got the right idea with interfacing with the PostgreSQL database using Clojure's
clojure.java.jdbclibrary, but there are some syntax issues in theinsert-playerfunction that need to be addressed. Specifically, the SQL query isn't correctly parameterized, which is why you're getting the error about the column index being out of range.Here are the necessary changes with the correct parameterization and some minor refactorings:
Update
assignments.PAUL-OMAKI.db-corenamespace to use next.jdbc instead of the deprecated clojure.java.jdbc:(ns assignments.PAUL-OMAKI.db-core (:require [next.jdbc :as jdbc]))Define the
db-specordb-connusing the correct PostgreSQL database details:(def db-spec {:dbtype "postgresql" :host "localhost" :dbname "yourdatabase" ; Replace with your database name :user "youruser" ; Replace with your database user :password "yourpassword" ; Replace with your database password :port 5432})For the
insert-playerfunction, ensure you're using parameterized SQL:(defn insert-player [hash secret-num] (jdbc/execute! db-spec ["INSERT INTO games_in_progress (id, num, tries) VALUES (?, ?, 6)" hash secret-num]))Now, you can call
insert-playerwith the correct parameters:(insert-player 23323 5) ;; Call with the actual values you want to insert.Please note the following:
- Use
?placeholders in your SQL query to ensure that you're not vulnerable to SQL injection attacks and that Clojure's JDBC library can correctly bind the variableshashandsecret-numto your SQL statement. - JDBC expects parameters in vectors when using
?placeholders in SQL queries. - Make sure your database schema matches the SQL queries. For example, the table
games_in_progressshould exist with the columnsid,num, andtriesdefined in the database. - The
defdb-specordb-connshould contain the correct credentials to access your PostgreSQL server. - The
insert-playerfunction definition doesn't need to surround parameter valueshashandsecret-numwith quotes within the vector, as they are parameter placeholders for the actual values.
With these changes, your Clojure code should correctly interface with the PostgreSQL database and insert a new player into the
games_in_progresstable. - Use
- User
Okay, it is working now. I want to replace the atom usage in the simple-game namespace with database calls to the games_in_progress table to create, update game state by decrementing tries, and delete users.
- Assistant
To replace the atom usage in the
simple-gamenamespace with database calls to thegames_in_progresstable, you'll need to implement database operations for creating, updating, and deleting game states. Here are the equivalent database functions for each of those actions:Creating a New Game:
(ns assignments.PAUL-OMAKI.simple-game (:require [next.jdbc :as jdbc] [assignments.PAUL-OMAKI.db-core :as db])) (defn new-game! [user-hash] ;; Delete any existing game for the user before starting a new one (jdbc/execute! db/db-spec ["DELETE FROM games_in_progress WHERE id = ?" user-hash]) ;; Insert a new game with user's hash, a random secret number, and initial tries count (jdbc/execute! db/db-spec ["INSERT INTO games_in_progress (id, secret_num, remaining_tries) VALUES (?, ?, 6)" user-hash (+ 1 (rand-int 10))]))Updating Game State (Decrementing Tries):
(defn failed-attempt [user-hash] (jdbc/execute! db/db-spec ["UPDATE games_in_progress SET remaining_tries = remaining_tries - 1 WHERE id = ?" user-hash]))Deleting a User's Game State:
(defn reset-game [user-hash] (jdbc/execute! db/db-spec ["DELETE FROM games_in_progress WHERE id = ?" user-hash]))Fetching Remaining Tries for a User:
(defn get-remaining-tries [user-hash] (first (jdbc/execute! db/db-spec ["SELECT remaining_tries FROM games_in_progress WHERE id = ?" user-hash] {:result-set-fn :one})))Fetching Secret Number for a User:
(defn get-secret-num [user-hash] (first (jdbc/execute! db/db-spec ["SELECT secret_num FROM games_in_progress WHERE id = ?" user-hash] {:result-set-fn :one})))With these functions, you should update the
guess-answerfunction (and any other parts of your code that interact with thegames-in-progressstate) to use these new database functions instead of the atom.(defn guess-answer [guess user-hash] (let [remaining-tries (get-remaining-tries user-hash) secret-num (get-secret-num user-hash)] (cond (nil? guess) nil (= guess secret-num) (do (reset-game user-hash) :game-win) (= 0 remaining-tries) (do (reset-game user-hash) :game-over) (< guess secret-num) (do (failed-attempt user-hash) :too-low) (> guess secret-num) (do (failed-attempt user-hash) :too-high))))Keep in mind:
- You might need to parse integers from the database results since JDBC will return them as generic
Objects. - The
:result-set-fnoption is used to control how the result set is processed. In the aboveget-remaining-triesandget-secret-numfunctions, I used:oneto get a single integer value directly. - Ensure to handle any potential database exceptions that could be thrown when executing these operations.
- The database operations are synchronous and will block until they complete, so in a production system, you might want to consider using a connection pool and possibly asynchronous handling of database operations to prevent blocking the main thread.
- You might need to parse integers from the database results since JDBC will return them as generic
- User
How can I protect this code from erroring with IF EXISTS? (defn reset-game [user-code] (jdbc/execute! db-conn ["DELETE FROM games_in_progress WHERE id = ?" user-code]))
- Assistant
The
IF EXISTSsyntax is generally used withDROP TABLE,DROP INDEX, and similar statements to avoid errors when the specified database object does not exist. It does not apply toDELETEstatements.When using
DELETE, if theWHEREcondition does not match any rows in the table, the statement will complete without error but will not affect any rows. In other words, trying to delete a row that doesn't exist will not cause an error in SQL—it will simply result in a no-op.If you want to check whether the deletion actually removed any rows (for example, to provide feedback to the user), you can do so by checking the count of affected rows, which next.jdbc provides as the return value of
execute!. Here's how you might modify yourreset-gamefunction to track whether a deletion occurred:(defn reset-game [user-code] (let [result (jdbc/execute! db-conn ["DELETE FROM games_in_progress WHERE id = ?" user-code] {:return-keys true :return-count true})] (if (> (:count result) 0) true ; Indicates that one or more rows were deleted false))) ; Indicates that no rows were deletedIn this updated
reset-gamefunction,:return-keysand:return-countoptions are used to ask for extra metadata about the operation. In particular,:countwill contain the number of rows affected by theDELETEstatement. The function now returnstrueif any rows were deleted, andfalseif no rows were deleted.However, as of the time of my knowledge cut-off in 2023,
:return-countis not a valid option in next.jdbc (it was valid in clojure.java.jdbc). Instead, you can check the affected row count in the following way:(defn reset-game [user-code] (let [result (jdbc/execute! db-conn ["DELETE FROM games_in_progress WHERE id = ?" user-code])] (if (pos? (:update-count result)) true ; Indicates that one or more rows were deleted false))) ; Indicates that no rows were deletedIf you're merely looking to prevent errors when trying to delete a game that might not exist, there's no need to do anything special—the SQL
DELETEstatement already handles that situation gracefully. - User
However, when accessing the page in question, it throws this error:
Problem accessing /new-game. Reason:
Batch entry 0 DELETE FROM games_in_progress WHERE id = '2356372769' was aborted: ERROR: operator does not exist: integer = character varyingHint: No operator matches the given name and argument types. You might need to add explicit type casts. Position: 69 Call getNextException to see other errors in the batch.
- Assistant
The error message you're encountering indicates there's a mismatch between the data types in your SQL query. Specifically, the
idcolumn in thegames_in_progresstable is an integer type, but the query is providing a character varying (string) type.When you use a
?placeholder within an SQL query, the arguments you pass to fill those placeholders must match the column types defined in your database schema. If you're passing a string to match against an integer column, you'll get a type mismatch error.There are a few ways to handle this issue:
-
Ensure the argument type matches the column type: Make sure that when you call
reset-game, you pass an integer if theidcolumn in the database is anintegertype. For example, ifuser-codeis a string containing a number, you should convert it to an integer:(defn reset-game [user-code] (jdbc/execute! db-conn ["DELETE FROM games_in_progress WHERE id = ?" (Integer/parseInt user-code)])) -
Use explicit type casting in the SQL query: If you have control over the SQL and are sure that you want to pass a string, you could do an explicit type cast in the SQL statement. However, this is not the preferred method because it introduces the potential risk of SQL injection if done improperly. It's usually better to ensure that the data types match in your application code.
Here's how you would modify the
reset-gamefunction to avoid the type mismatch error, assuming thatuser-codeis actually an integer captured as a string:(defn reset-game [user-code] ;; Assuming user-code is a string representation of an integer: (let [user-code-int (Integer/parseInt user-code)] ; Convert string to integer (jdbc/execute! db-conn ["DELETE FROM games_in_progress WHERE id = ?" user-code-int])))Make sure to add exception handling around
Integer/parseIntto catch any potentialNumberFormatExceptionwhen the provideduser-codeisn't a valid integer string.Another approach would be to ensure that
user-codeis passed as the correct type all the way through your system, from where it's originally captured (e.g., from a form or URL parameter), so that no conversion is needed at the point wherereset-gameis called. -
- User
I used Integer/parseInt as follows but I'm still getting:
Problem accessing /new-game. Reason:
For input string: "2356372769"The code currently is:
ns simple-server.simple-game (:require [clojure.java.jdbc :as jdbc]))
(def db-conn {:dbtype "postgresql" :host "localhost" :dbname "postgres" :user "postgres" :password "postgres" :port 5432})
(defn insert-player [user-code secret-num] (jdbc/execute! db-conn ["INSERT INTO games_in_progress (id, num, tries) VALUES (?, ?, 6)" (Integer/parseInt user-code) secret-num]))
(defn failed-attempt [user-code] (jdbc/execute! db-conn ["UPDATE games_in_progress SET tries = tries - 1 WHERE id = ?" (Integer/parseInt user-code)]))
(defn reset-game [user-code] (jdbc/execute! db-conn ["DELETE FROM games_in_progress WHERE id = ?" (Integer/parseInt user-code)]))
(defn get-remaining-tries [user-code] (first (jdbc/execute! db-conn ["SELECT remaining_tries FROM games_in_progress WHERE id = ?" (Integer/parseInt user-code)] {:result-set-fn :one})))
(defn get-secret-num [user-code] (first (jdbc/execute! db-conn ["SELECT secret_num FROM games_in_progress WHERE id = ?" (Integer/parseInt user-code)] {:result-set-fn :one})))
;; Make our new game:
(defn new-game! [user-code] (reset-game user-code) ; Delete any existing game for the user before starting a new one (insert-player user-code ; Insert a new game with user’s hash, a random secret number, and initial tries count (+ 1 (rand-int 10))))(defn guess-answer [guess user-hash] ;; @games-in-progress (let [user user-hash] (cond (nil? guess) nil
(= guess (get-secret-num user)) (and (reset-game user) :game-win) (= 0 (get-remaining-tries user)) (and (reset-game user) :game-over) (< guess (get-secret-num user)) (and (failed-attempt user) :too-low) (> guess (get-secret-num user)) (and (failed-attempt user) :too-high)))) - Assistant
The error message
For input string: "2356372769"suggests thatInteger/parseIntis unable to parse the string as an integer. However, the number "2356372769" is too large to be represented as anintin Java (which has a maximum value of2147483647). Ifuser-codeneeds to handle integers of that size, you should use alongtype instead ofint.To parse a
longvalue from a string, you should useLong/parseLong:(defn insert-player [user-code secret-num] (jdbc/execute! db-conn ["INSERT INTO games_in_progress (id, num, tries) VALUES (?, ?, 6)" (Long/parseLong user-code) secret-num])) (defn failed-attempt [user-code] (jdbc/execute! db-conn ["UPDATE games_in_progress SET tries = tries - 1 WHERE id = ?" (Long/parseLong user-code)])) (defn reset-game [user-code] (jdbc/execute! db-conn ["DELETE FROM games_in_progress WHERE id = ?" (Long/parseLong user-code)])) (defn get-remaining-tries [user-code] (first (jdbc/query db-conn ["SELECT remaining_tries FROM games_in_progress WHERE id = ?" (Long/parseLong user-code)]))) (defn get-secret-num [user-code] (first (jdbc/query db-conn ["SELECT secret_num FROM games_in_progress WHERE id = ?" (Long/parseLong user-code)])))Please note a couple of changes:
jdbc/queryis used instead ofjdbc/execute!forSELECTstatements. This function returns the results rather than execution metadata.- Each occurrence of
Integer/parseInthas been changed toLong/parseLong.
Additionally, you need to ensure that the
idcolumn in yourgames_in_progressdatabase table is of typebigintto store large integers properly:CREATE TABLE games_in_progress ( id bigint PRIMARY KEY, num integer, tries integer, ... );With these changes, your code should be able to parse and handle large integers that represent user codes. Always handle this operation in a
tryblock to catch potentialNumberFormatExceptionexceptions and act accordingly in case of invalid inputs. - User
It's almost working, but on the guess page I'm getting this error:
HTTP ERROR: 500
Problem accessing /guess. Reason:
Cannot invoke "Object.getClass()" because "x" is null - Assistant
The error message "Cannot invoke 'Object.getClass()' because 'x' is null" suggests that somewhere in your
/guesshandling code, there is an attempt to call a method on anullobject reference. Without seeing the exact part of the code that is triggering the error, diagnosing the issue involves some educated guesswork.Given your earlier code, the issue is likely happening within the
guess-handleror somewhere down the line where a database operation might be returningnull(for example, if a user is not found in thegames_in_progresstable).Here is a general approach to troubleshooting this issue:
-
Check for null values: Make sure that any database call or part of the code that could return
nullis being checked before you attempt to access methods or fields on the result. -
Use
some?ornil?checks: Before calling a method on an object, verify that the object is notnull.
For example, in your
get-secret-numandget-remaining-triesfunctions:(defn get-remaining-tries [user-code] (when-let [result (first (jdbc/query db-conn ["SELECT remaining_tries FROM games_in_progress WHERE id = ?" (Long/parseLong user-code)]))] (:remaining_tries result))) (defn get-secret-num [user-code] (when-let [result (first (jdbc/query db-conn ["SELECT secret_num FROM games_in_progress WHERE id = ?" (Long/parseLong user-code)]))] (:secret_num result)))In these functions,
when-letis used to ensure thatresultis notnullbefore attempting to get the values out of it. Ifresultisnull, the functions will returnnilinstead of causing an error.- Update the
guess-handler: Ensure that theguess-handlerfunction is getting valid data and theget-secret-numandget-remaining-triesfunctions are not returningnullwhen you expect a value. You should handle the cases where the game state is not found (i.e., theiddoes not exist in the table):
(defn guess-handler [guess user-hash] (if-let [secret-num (get-secret-num user-hash)] ;; Proceed only if get-secret-num returns a valid number (let [remaining-tries (get-remaining-tries user-hash)] (cond (nil? guess) (response "You need to supply a guess with /guess?guess=N") (= guess secret-num) (and (reset-game user-hash) (response "Congratulations! You win!")) ;; Other conditions... )) (response "Invalid game or game not found.")))-
Double-check for typos: Sometimes, a simple typo in the variable names or in the keys used to access map entries can cause a null-related error.
-
Examine stack trace and logs: Look at the detailed stack trace provided in the error output to see which line number is causing the issue, as this will guide you to the exact place in the code where the
nullreference is being incorrectly used.
By following these steps and adding appropriate
nilchecks throughout your code, you should be able to address the "Cannot invoke 'Object.getClass()' because 'x' is null" error. If you need more targeted assistance, please provide the full stack trace and any additional code that may be relevant. -
- User
I made some progress debugging the error. The problematic code was this:
(defn get-remaining-tries [user-code] (first (jdbc/query db-conn ["SELECT tries_left FROM games_in_progress WHERE user_id = ?" (user-code)] {:result-set-fn :one})))
It was giving the following error when called manually: ; Execution error (ClassCastException) at simple-server.simple-game/get-remaining-tries (simple_game.clj:29). ; class java.lang.Long cannot be cast to class java.lang.String (java.lang.Long and java.lang.String are in module java.base of loader 'bootstrap')
- Assistant
The error message indicates that a
Longis being cast to aString, which is not valid in Java. This is likely caused by the(user-code)expression within your SQL query vector.(user-code)is being interpreted as a function call, but sinceuser-codeis expected to be a numeric ID rather than a function, it causes aClassCastException. You should not use parentheses arounduser-codewhen passing it as a parameter.Instead, you should make sure that
user-codeis a number and pass it directly as a parameter:(defn get-remaining-tries [user-code] (first (jdbc/query db-conn ["SELECT tries_left FROM games_in_progress WHERE user_id = ?" (Long/parseLong user-code)] {:result-set-fn :one})))In this case,
(Long/parseLong user-code)is used to safely convert theuser-codeto aLong. However, ifuser-codeis already guaranteed to be aLongor an appropriately-typed number, there is no need to parse it, and you can simply useuser-codedirectly:(defn get-remaining-tries [user-code] (first (jdbc/query db-conn ["SELECT tries_left FROM games_in_progress WHERE user_id = ?" user-code] ; No need to parse if user-code is already a Long. {:result-set-fn :one})))Moreover, the
:result-set-fn :onekeyword will attempt to convert the first row of the result set into a map, so you have to extract thetries_leftfield from the map it returns (assuming thattries_leftis the name of the column in your database):(defn get-remaining-tries [user-code] (let [result (jdbc/query db-conn ["SELECT tries_left FROM games_in_progress WHERE user_id = ?" user-code] {:result-set-fn :one})] (:tries_left result)))Make sure that
user-codeis indeed the correct type matching your database schema (bigintforuser_id, if it's a large number), and carefully remove any unnecessary parentheses that might cause the Clojure compiler to interpret literals as function calls.