I am working on a web service that needs to talk to a database, so I am tooling up my basic libraries to give me access to postgres on my desktop.
Jun 5, 2013 1:27:46 PM com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask run
WARNING: com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask#15c313da -- Acquisition
Attempt Failed!!! Clearing pending acquires.
While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30).
Last acquisition attempt exception:
java.sql.SQLException: No suitable driver
at java.sql.DriverManager.getDriver(DriverManager.java:264)
In my db library I have the following
(ns myapp.db
(:import [com.mchange.v2.c3p0 ComboPooledDataSource]))
(def specification {
:classname "postgresql"
:subprotocol "org.postgresql.Driver"
:subname "//localhost:5432;database=test"
})
(defn pooled-data-source [specification]
(let [datasource (ComboPooledDataSource.)]
(.setDriverClass datasource (:classname specification))
(.setJdbcUrl datasource (str "jdbc:" (:subprotocol specification) ":" (:subname specification)))
(.setUser datasource (:user specification))
(.setPassword datasource (:password specification))
(.setMaxIdleTimeExcessConnections datasource (* 30 60))
(.setMaxIdleTime datasource (* 3 60 60))
{:datasource datasource}))
(def connection-pool
(delay
(pooled-data-source specification)))
(defn connection [] #connection-pool)
Then in my unit test:
(ns myapp.db-test
(:use clojure.test)
(:require [myapp.db]
[clojure.java.jdbc :as jdbc]))
(let [db (myapp.db/connection)]
(jdbc/with-connection db)
(jdbc/with-query-results rs ["select * from foo"]
(doseq [row rs]
(println row)))))
However this does work in the REPL so at least I know the database is up and accepting connections:
user=> (require '[clojure.java.jdbc :as sql])
user=> (sql/with-connection "postgresql://localhost:5432/test"
(sql/with-query-results results ["select * from foo"]
(doseq [result results] (println result))))
{:y 2, :x 1}
nil
user=>
Help with this is greatly appreciated!
My project.clj is as follows
(defproject myapp "0.1.0"
:description "myapp"
:dependencies [
[org.clojure/clojure "1.5.1"]
[org.clojure/java.jdbc "0.3.0-alpha4"]
[postgresql "9.1-901.jdbc4"]
[c3p0/c3p0 "0.9.1.2"]])
I'd suggest to fix your specification
(def specification {
:subprotocol "postgresql"
:classname "org.postgresql.Driver"
:subname "//localhost:5432/test"})
there might be other issues as well (i'm very much a clojure novice), but you definitely have :classname and :subprotocol inverted in your specification. :classname should be "org.postgresql.Driver". :subprotocol should be "postgresql".
Related
I've been getting the following exception when trying to setup a new ecto repo. Currently only using it for testing (since i am just setting this up).
** (RuntimeError) could not lookup Ecto repo Lipwig.AnnotatedUnit.Repo because it was not started or it does not exist
This happens when my tests use Lipwig.AnnotatedUnit.DataCase. However, when i use Lipwig.DataCase (which references the Lipwig.Repo`), the tests run fine.
I have the following setup in the project.
defmodule Lipwig.Repo do
use Ecto.Repo,
otp_app: :lipwig,
adapter: Ecto.Adapters.Postgres
end
defmodule Lipwig.AnnotatedUnit.Repo do
use Ecto.Repo,
otp_app: :lipwig,
adapter: Ecto.Adapters.Postgres
end
This here is my test setup
defmodule Lipwig.DataCase do
use ExUnit.CaseTemplate
using do
quote do
alias Lipwig.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
import Lipwig.DataCase
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Lipwig.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Lipwig.Repo, {:shared, self()})
end
:ok
end
def errors_on(changeset) do
Ecto.Changeset.traverse_errors(changeset, fn {message, opts} ->
Regex.replace(~r"%{(\w+)}", message, fn _, key ->
opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string()
end)
end)
end
end
defmodule Lipwig.AnnotatedUnit.DataCase do
use ExUnit.CaseTemplate
using do
quote do
alias Lipwig.AnnotatedUnit.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
import Lipwig.AnnotatedUnit.DataCase
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Lipwig.AnnotatedUnit.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Lipwig.AnnotatedUnit.Repo, {:shared, self()})
end
:ok
end
def errors_on(changeset) do
Ecto.Changeset.traverse_errors(changeset, fn {message, opts} ->
Regex.replace(~r"%{(\w+)}", message, fn _, key ->
opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string()
end)
end)
end
end
My other datacase for Lipwig.Repo is almost identical, just referencing the other repo.
My config.exs config defines
config :lipwig,
ecto_repos: [Lipwig.Repo, Lipwig.AnnotatedUnit.Repo]
My test.exs config is
config :lipwig, Lipwig.Repo,
username: "postgres",
password: "postgres",
database: "lipwig_test",
hostname: "localhost",
pool: Ecto.Adapters.SQL.Sandbox
config :lipwig, Lipwig.AnnotatedUnit.Repo,
username: "postgres",
password: "postgres",
database: "lipwig_test",
hostname: "localhost",
pool: Ecto.Adapters.SQL.Sandbox
As per my knowledge, the configurations seem fine. As the error suggests, I think the issue might be because you are not starting the Lipwig.AnnotatedUnit.Repo in with you application.
Look for the application.ex file in the /lib/lipwig_web folder and make sure that Lipwig.AnnotatedUnit.Repo is added in the children array.
Hope this resolves 🥂
I am trying to make a grid with ag-grid and activate sortable and filter, but it doesn't work towards localhost. In the columndefinition, I use
''':sortable true'''
''':filter true''''
But nothing happens. Does anyone know what is wrong?
(ns reagent-ag-grid-ex.core
(:require
[reagent.core :as r]
[cljsjs.ag-grid-react]
[reagent-ag-grid-ex.state :as state]))
;; -------------------------
;; Views
(def ag-adapter (r/adapt-react-class (.-AgGridReact js/agGridReact) ))
;;(defn get-cols [entry]
;; (into [] (map #(hash-map :headerName (-> % key name) :field (-> % key name)) entry)))
;;columnDefs: [ {headerName: "Make", field: "make"}, {headerName: "Model", field: "model"}, {headerName: "Price", field: "price"} ]
;;rowData: [ {make: "Toyota", model: "Celica", price: 35000}, {make: "Ford", model: "Mondeo", price: 32000}, {make: "Porsche", model: "Boxter", price: 72000}]
(def deafult-col-w 200)
(defn width-helper [lst]
(+ (* deafult-col-w (count lst)) 2))
(defn home-page []
[:div [:h2 "Ekspono tag-model"]
[:p "My portfolio / Top Index " [:a {:style {:background-color "#C0C0C0" :float "right" :color "black"}
:href "https://www.google.com" :target "_blank"} "Show problems"]]
[:div {:className "ag-theme-balham" :style {:height 200 :width (width-helper state/cols) :color "purple"}}
[ag-adapter {"columnDefs" state/cols
"rowData" state/rows
"defaultColDef" {:sortable true
:width deafult-col-w}}]]
[:div [:a {:href "https://www.tabyenskilda.se/fredrik-cumlin/" :target "_blank"}
"#copyright Fredrik Cumlin"]]])
;; -------------------------
;; Initialize app
(defn mount-root []
(r/render [home-page] (.getElementById js/document "app")))
(defn init! []
(mount-root))
Upgrade to latest ag-grid-react cljsjs distribution (21.0.1-1) - e.g. using lein project.clj switch dep to [cljsjs/ag-grid-react "21.0.1-1"]. Should work on this version.
Also as a side note, no need to specify prop keys with strings, you can use keywords - it's a bit more idiomatic.
I'm making a task that get an json in an api and insert in MongoDb. I'm using phoenix and Mongodb_Ecto.
I have a model Group and this code in a controller works like a charm:
HTTPoison.start
group = %Group{ param1: "value", param2: "value" } |> Repo.insert!
But,in a task I don't have the Repo defmodule. I tried to make this:
HTTPoison.start
group = %Group{ param1: "value", param2: "value"} |> MyApp.Repo.insert!
Using MyApp.Repo instead of only Repo.
I'm receiving this error:
** (exit) exited in: :gen_server.call(MyApp.Repo.Pool, {:checkout, #Reference<0.0.1.11>, true}, 5000)
** (EXIT) no process
:erlang.send(MyApp.Repo.Pool, {:"$gen_cast", {:cancel_waiting, #Reference<0.0.1.11>}}, [:noconnect])
(stdlib) gen_server.erl:416: :gen_server.do_send/2
(stdlib) gen_server.erl:232: :gen_server.do_cast/2
src/poolboy.erl:58: :poolboy.checkout/3
(stdlib) timer.erl:197: :timer.tc/3
lib/mongo/pool/poolboy.ex:33: Mongo.Pool.Poolboy.run/2
lib/mongo/pool.ex:142: Mongo.Pool.run_with_log/5
lib/mongo.ex:220: Mongo.insert_one/4
lib/mongo_ecto/connection.ex:124: Mongo.Ecto.Connection.catch_constraint_errors/1
lib/mongo_ecto.ex:522: Mongo.Ecto.insert/6
lib/ecto/repo/model.ex:253: Ecto.Repo.Model.apply/4
lib/ecto/repo/model.ex:83: anonymous fn/10 in Ecto.Repo.Model.do_insert/4
lib/ecto/repo/model.ex:14: Ecto.Repo.Model.insert!/4
How can I access Repo.insert in the correct way to save my data in mongoDb?
Thanks for this.
Your application (and therefore your database pool) is not started automatically in a Mix task. You can start it manually by adding the following:
:application.ensure_all_started(:my_app)
If :httpoison is listed in your Mixfile's :applications, you don't need to do HTTPoison.start anymore as the above line will ensure :httpoison is started before :my_app.
I have the following docker-compose rules...
catalog-service:
build: ./services/catalog
ports:
- "2000:3000"
depends_on:
- catalog-datastore
restart: always
catalog-datastore:
image: mongo:3.0
command: mongod --smallfiles --quiet --logpath=/dev/null
ports:
- "27017:27017"
The following Dockerfile for the clojure app...
FROM clojure
COPY . /usr/src/app
WORKDIR /usr/src/app
CMD ["lein", "ring", "server"]
And the following connection code in my app...
(ns catalog.handler
(:import com.mchange.v2.c3p0.ComboPooledDataSource)
(:use compojure.core)
(:use cheshire.core)
(:use ring.util.response)
(:require [compojure.handler :as handler]
[ring.middleware.json :as middleware]
[clojure.java.jdbc :as sql]
[compojure.route :as route]
[somnium.congomongo :as m]))
(def conn
(m/make-connection "catalog"
:host "catalog-datastore"
:port 27017))
(defn get-all []
(m/fetch :catalog))
(defn get-single [id]
(m/fetch-one
:catalog
:where{:_id (Long/parseLong id)}))
(defroutes app-routes
(context "/catalog" [] (defroutes catalog-routes
(GET "/" [] (get-all))
(GET "/:id", [id] (get-single)))))
(def app
(-> (handler/api app-routes)
(middleware/wrap-json-body)
(middleware/wrap-json-response)))
When I try to run the app I get the error...
java.lang.AssertionError
Assert failed: (connection? conn)
From the docs:
set the connection globally
(m/set-connection! conn)
or locally
(m/with-mongo conn
(m/insert! :robots {:name "robby"}))
Looks like you missed that bit. :p
I have just started using Elixir, so I figure I have some basic misunderstanding going on here. Here is the code...
defmodule Mdb do
def connect(collection, this_db \\ "db-test") do
{:ok, mongo} = Mongo.connect("db-test.some-mongo-server.com", 12345)
db = mongo |> Mongo.db(this_db)
db |> Mongo.auth("user", "secretpassword")
db
end
end
I start with iex -S mix
and when I try db = Mdb.connect("users") I get
** (UndefinedFunctionError) undefined function: Mongo.auth/3
Mongo.auth(%Mongo.Db{auth: nil, mongo: %Mongo.Server{host: 'db-test.some-mongo-server.com', id_prefix: 12641, mode: :passive, opts: %{}, port: 12345, socket: #Port<0.5732>, timeout: 6000}, name: "db-stage", opts: %{mode: :passive, timeout: 6000}}, "user", "secretpassword")
(mdb_play) lib/mdb.ex:7: Mdb.connect/2
I looks like Mongo.auth/3 is undefined, but that makes no sense to me. Can any one point me towards my error?
thanks for the help
I just played around it, and faced the same error. As in the error message, Mongo.auth seems not defined, and it might be Mongo.Db.auth instead. However, I faced another error (ArgumentError) on Mongo.Db.auth too. It may be certain issue in the library.
** (ArgumentError) argument error
:erlang.byte_size
...
(mongo) lib/mongo_request.ex:43: Mongo.Request.cmd/3
(mongo) lib/mongo_db.ex:44: Mongo.Db.auth/1
I'm not familiar with the library, but after small change in Mongo.Db.auth, normal call seems started working.
I tried with the following sequence.
mongo = Mongo.connect!(server, port)
db = mongo |> Mongo.db(db_name)
db |> Mongo.Db.auth(user_name, password)
collection = db |> Mongo.Db.collection(collection_name)
collection |> Mongo.Collection.count()
The change I tried is in the following fork-repo.
https://github.com/parroty/elixir-mongo