Skip to content

Instantly share code, notes, and snippets.

Created March 31, 2022 13:56
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
(defn generate-auth-token
"Create an authorization token used to connect to a database that uses RDS IAM
authentication. Use this token as the DB password when connecting with `user`.
To use IAM authentication, the user must be granted the rds_iam role. e.g.,
`GRANT rds_iam TO db_userx;`
See also:"
(.getAuthToken (.build (doto (RdsIamAuthTokenGenerator/builder)
(.credentials (DefaultAWSCredentialsProviderChain.))
(.region (.getRegion (DefaultAwsRegionProviderChain.)))))
(doto (GetIamAuthTokenRequest/builder)
(.hostname (:host db-spec))
(.port 5432)
(.userName (:user db-spec))))))
(defn new-data-source
"Returns an uninitialized Hikari DataSource. To initialize the pool, call
`getConnection` on the returned datasource."
[db-url db-spec]
(let [init-props (doto (java.util.Properties.)
;; Any regular JDBC connection parameters can be added here.
(.putAll (cond-> {}
(:user db-spec) (assoc "user" (:user db-spec)))))
get-conn (fn get-conn
(get-conn {"password" (generate-auth-token db-spec)}))
(java.sql.DriverManager/getConnection db-url
(doto init-props
(.putAll props)))))
*login-timeout (atom nil)
base-datasource (reify DataSource
(getConnection [_] (get-conn))
(getConnection [_ user password]
(get-conn {"user" user "password" password}))
(getLoginTimeout [_] (or @*login-timeout 0))
(setLoginTimeout [_ seconds] (reset! *login-timeout seconds))
(toString [_] db-url))]
(doto (HikariDataSource.)
(.setDataSource base-datasource)
;; Optionally set Hikari specific properties here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment