Postgrex how to define json library - json

I'm just trying to use Postgrex without any kind of ecto setup, so just the example from the documentation readme.
Here is what my module looks like:
defmodule Receive do
def start(_type, _args) do
{:ok, pid} = Postgrex.start_link(
hostname: "localhost",
username: "john",
# password: "",
database: "property_actions",
extensions: [{Postgrex.Extensions.JSON}]
)
Postgrex.query!(
pid,
"INSERT INTO actions (search_terms) VALUES ($1)",
[
%{foo: 'bar'}
]
)
end
end
when I run the code I get
** (RuntimeError) type `json` can not be handled by the types module Postgrex.DefaultTypes, it must define a `:json` library in its options to support JSON types
Is there something I'm not setting up correctly? From what I've gathered in the documentation, I shouldn't even need to have that extensions line because json is handled by default.

On Postgrex <= 0.13, you need to define your own types:
Postgrex.Types.define(MyApp.PostgrexTypes, [], json: Poison)
and then when starting Postgrex:
Postgrex.start_link(types: MyApp.PostgrexTypes)
On Postgrex >= 0.14 (currently master), it was made easier:
config :postgrex, :json_library, Poison

Related

Accessing keys when loading from JSON

I am new to Python and I can not seem to find a solution that I understand.
• When I load in the JSON file I can print out the list as a whole; but if I try to access the key I get KeyError.
• Am I right in saying that Python converts the JSON file into a Python dictionary?
• Also, how would I go about accessing keys and then checking against them?
Main Code:
JSON File:
Console Error:
Welcome to Stackoverflow Community.
JSON you have:
{
"credentials": [
{
"username": "Admin",
"password": "Password"
}
]
}
When Converted to the dictionary:
{'credentials': [{'username': 'Admin', 'password': 'Password'}]}
Understanding the output of credentials:
print(data["credentials"])
# Output:
[{'username': 'Admin', 'password': 'Password'}]
# Do observe that the output is in a list format.
# For better understanding let's assume there is more than 1 credential:
[
{'username': 'Admin', 'password': 'Password'}, # 0 of list
{'username': 'Admin1', 'password': 'Password1'} # 1 of list
]
Understanding the mistake:
# Instead of
data["username"]
# do
data["credentials"][0]["username"]
The Right way:
for i in len(data["credentials"]):
print("The username is ", data["credentials"][i]["username"])
Also, I encourage you to go through Python Tutorials before working on something.
Python is widely considered among the easiest programming languages for beginners to learn.

Elixir - JasonHelpers - How can I send a keyword list to json_map?

I have a data structure that I want to convert to json and preserve the key order.
For example:
%{ x: 1, a: 5} should be converted to "{\"x\": 1, \"a\": 5}"
Poison does it without any problem. But when I upgrade to Jason, it changes to "{\"a\": 5, \"x\": 1}".
So I use JasonHelpers json_map to preserve the order like this:
Jason.Helpers.json_map([x: 1, a: 5])
It creates a fragment with correct order.
However, when I use a variable to do this:
list = [x: 1, a: 5]
Jason.Helpers.json_map(list)
I have an error:
** (Protocol.UndefinedError) protocol Enumerable not implemented for {:list, [line: 15], nil} of type Tuple.
....
QUESTION: How can I pass a pre-calculated list into Jason.Helpers.json_map ?
The calculation is complicated, so I don't want to repeat the code just to use json_map, but use the function that returns a list.
json_map/1 is a macro, from its docs:
Encodes a JSON map from a compile-time keyword.
It is designed for compiling JSON at compile-time, which is why it doesn't work with your runtime variable.
Support for encoding keyword lists was added to the Jason library a year ago, but it looks like it hasn't been pushed to hex yet. I managed to get it work by pulling the latest code from github:
defp deps do
[{:jason, git: "https://github.com/michalmuskala/jason.git"}]
end
Then by creating a struct that implements Jason.Encoder (adapted from this solution by the Jason author):
defmodule OrderedObject do
defstruct [:value]
def new(value), do: %__MODULE__{value: value}
defimpl Jason.Encoder do
def encode(%{value: value}, opts) do
Jason.Encode.keyword(value, opts)
end
end
end
Now we can encode objects with ordered keys:
iex(1)> Jason.encode!(OrderedObject.new([x: 1, a: 5]))
"{\"x\":1,\"a\":5}"
I don't know if this is part of the public API or just an implementation detail, but it appears you have some control of the order when implementing the Jason.Encoder protocol for a struct.
Let's say you've defined an Ordered struct:
defmodule Ordered do
#derive {Jason.Encoder, only: [:a, :x]}
defstruct [:a, :x]
end
If you encode the struct, the "a" key will be before the "x" key:
iex> Jason.encode!(%Ordered{a: 5, x: 1})
"{\"a\":5,\"x\":1}"
Let's reorder the keys we pass in to the :only option:
defmodule Ordered do
#derive {Jason.Encoder, only: [:x, :a]}
defstruct [:a, :x]
end
If we now encode the struct, the "x" key will be before the "a" key:
iex> Jason.encode!(%Ordered{a: 5, x: 1})
"{\"x\":1,\"a\":5}"

How to define config file variables?

I have a configuration file with:
{path, "/mnt/test/"}.
{name, "Joe"}.
The path and the name could be changed by a user. As I know, there is a way to save those variables in a module by usage of file:consult/1 in
-define(VARIABLE, <parsing of the config file>).
Are there any better ways to read a config file when the module begins to work without making a parsing function in -define? (As I know, according to Erlang developers, it's not the best way to make a complicated functions in -define)
If you need to store config only when you start the application - you may use application config file which is defined in 'rebar.config'
{profiles, [
{local,
[{relx, [
{dev_mode, false},
{include_erts, true},
{include_src, false},
{vm_args, "config/local/vm.args"}]
{sys_config, "config/local/yourapplication.config"}]
}]
}
]}.
more info about this here: rebar3 configuration
next step to create yourapplication.config - store it in your application folder /app/config/local/yourapplication.config
this configuration should have structure like this example
[
{
yourapplicationname, [
{path, "/mnt/test/"},
{name, "Joe"}
]
}
].
so when your application is started
you can get the whole config data with
{ok, "/mnt/test/"} = application:get_env(yourapplicationname, path)
{ok, "Joe"} = application:get_env(yourapplicationname, name)
and now you may -define this variables like:
-define(VARIABLE,
case application:get_env(yourapplicationname, path) of
{ok, Data} -> Data
_ -> undefined
end
).

Elixir, using function from another module

I am extremely new to the programming and to the elixir. So I am very exited to learn as much as I can. But I've got a problem. I looking the way how to use my functions in another module. I am building the web-server which stores the key-value maps in the memory. To keep the maps temporary I've decided to use Agent. Here is the part of my code:
defmodule Storage do
use Agent
def start_link do
Agent.start_link(fn -> %{} end, name: :tmp_storage)
end
def set(key, value) do
Agent.update(:tmp_storage, fn map -> Map.put_new(map, key, value) end)
end
def get(key) do
Agent.get(:tmp_storage, fn map -> Map.get(map, key) end)
end
end
So I'm trying to put this functions to the routes of the web server:
defmodule Storage_router do
use Plug.Router
use Plug.Debugger
require Logger
plug(Plug.Logger, log: :debug)
plug(:match)
plug(:dispatch)
post "/storage/set" do
with {:ok, _} <- Storage.set(key, value) do
send_resp(conn, 200, "getting the value")
else
_ ->
send_resp(conn, 404, "nothing")
end
end
end
And I receive:
warning: variable "key" does not exist and is being expanded to "key()", please use parentheses to remove the ambiguity or change the variable name
lib/storage_route.ex:12
warning: variable "value" does not exist and is being expanded to "value()", please use parentheses to remove the ambiguity or change the variable name
lib/storage_route.ex:12
looking for any suggestions\help
I am extremly new to the programming and to the elixir.
I do not think it is wise to begin learning programming with elixir. I would start with python or ruby, and then after a year or two then I would try elixir.
The first thing you need to learn is how to post code. Search google for how to post code on stackoverflow. Then, you have to get your indenting all lined up. Are you using a computer programming text editor? If not, then you have to get one. There are many free ones. I use vim, which comes installed on Unix like computers. You can learn how to use vim by typing vimtutor in a terminal window.
Next, you have a syntax error in your code:
Agent.start_link(fn -> %{} end, name: :tmp_storage
end)
That should be:
Agent.start_link(fn -> %{} end, name: :tmp_storage)
The warning you got is because your code tries to do the equivalent of:
def show do
IO.puts x
end
Elixir and anyone else reading that code would ask, "What the heck is x?" The variable x is never assigned a value anywhere, and therefore the variable x does not exist, and you cannot output something that is non-existent. You do the same thing here:
with {:ok, _} <- Storage.set(key, value) do
send_resp(conn, 200, "getting the value")
else
_->
send_resp(conn, 404, "nothing")
end
You call the function:
Storage.set(key, value)
but the variables key and value were never assigned a value, and elixir (and anyone else reading that code) wonders, "What the heck are key and value?"
This is the way functions work:
b.ex:
defmodule MyFuncs do
def show(x, y) do
IO.puts x
IO.puts y
end
end
defmodule MyWeb do
def go do
height = 10
width = 20
MyFuncs.show(height, width)
end
end
In iex:
~/elixir_programs$ iex b.ex
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]
Interactive Elixir (1.6.6) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> MyWeb.go
10
20
:ok
iex(2)>
So, in your code you need to write something like this:
post "/storage/set" do
key = "hello"
value = 10
with {:ok, _} <- Storage.set(key, value) do
send_resp(conn, 200, "Server saved the key and value.")
else
_->
send_resp(conn, 404, "nothing")
end
end
However, that will store the same key/value for every post request. Presumably, you want to store whatever is sent in the body of the post request. Do you know the difference between a get request and a post request? A get request tacks data onto the end of the url, while a post request sends the data in the "body of the request", so there are different procedures for extracting the data depending on the type of the request.
What tutorial are you reading? This tutorial: https://www.jungledisk.com/blog/2018/03/19/tutorial-a-simple-http-server-in-elixir/, shows you how to extract the data from the body of a post request. The data in the body of a post request is just a string. If the string is in JSON format, then you can convert the string into an elixir map using Poison.decode!(), which will allow you to easily extract the values associated with the keys that you are interested in. For example:
post "/storage/set" do
{:ok, body_string, conn} = read_body(conn)
body_map = Poison.decode!(body_string)
IO.inspect(body_map) #This outputs to terminal window where server is running
message = get_in(body_map, ["message"])
send_resp(
conn,
201,
"Server received: #{message}\n"
)
end
Then you can use the following curl command in another terminal window to send a post request to that route:
$ curl -v -H 'Content-Type: application/json' "http://localhost:8085/storage/set" -d '{"message": "hello world" }'
(-v => verbose output, -H => request header, -d => data)
Now, based on what I said was wrong with your code above, you should be wondering about this line:
{:ok, body_string, conn} = read_body(conn)
That line calls:
read_body(conn)
but the variable conn is not assigned a value anywhere. However, Plug invisibly creates the conn variable and assigns a value to it.
Here is a complete example using Agent to store post request data (following the tutorial I linked above):
simple_server
config/
lib/
simple_server/
application.ex
router.ex
storage.ex
test/
An elixir convention is to have a directory in the lib/ directory with the same name as your project, in this case that would be simple_server, then you give the modules you define names that reflect the directory structure. So, in router.ex you would define a module named SimpleServer.Router and in storage.ex you would define a module named SimpleServer.Storage. However, the . in a module name means nothing special to elixir, so you will not get an error if you decide to name your module F.R.O.G.S in the file lib/rocks.ex--and your code will work just fine.
router.ex:
defmodule SimpleServer.Router do
use Plug.Router
use Plug.Debugger
require Logger
plug(Plug.Logger, log: :debug)
plug(:match)
plug(:dispatch)
get "/storage/:key" do
resp_msg = case SimpleServer.Storage.get(key) do
nil -> "The key #{key} doesn't exist!\n"
val -> "The key #{key} has value #{val}.\n"
end
send_resp(conn, 200, resp_msg)
end
post "/storage/set" do
{:ok, body_string, conn} = read_body(conn)
body_map = Poison.decode!(body_string)
IO.inspect(body_map) #This outputs to terminal window where server is running
Enum.each(
body_map,
fn {key, val} -> SimpleServer.Storage.set(key,val) end
)
send_resp(
conn,
201,
"Server stored all key-value pairs\n"
)
end
match _ do
send_resp(conn, 404, "not found")
end
end
The first thing to note in the code above is the route:
get "/storage/:key" do
That will match a path like:
/storage/x
and plug will create a variable named key and assign it the value "x", like this:
key = "x"
Also, note that when you call a function:
width = 10
height = 20
show(width, height)
elixir looks at the function definition:
def show(x, y) do
IO.puts x
IO.puts y
end
and matches the function call to the def like this:
show(width, height)
| |
V V
def show( x , y) do
...
end
and performs the assignments:
x = width
y = height
Then, inside the function you can use the x and y variables. In this line:
Enum.each(
body_map,
# | | | | |
# V V V V V
fn {key, val} -> SimpleServer.Storage.set(key,val) end
)
Elixir will call the anonymous function passing values for key and val, like this:
func("x", "10")
Therefore, in the body of the anonymous function you can use the variables key and val:
SimpleServer.Storage.set(key,val)
because the variables key and val will already have been assigned values.
storage.ex:
defmodule SimpleServer.Storage do
use Agent
def start_link(_args) do #<*** Note the change here
Agent.start_link(fn -> %{} end, name: :tmp_storage)
end
def set(key, value) do
Agent.update(
:tmp_storage,
fn(map) -> Map.put_new(map, key, value) end
)
end
def get(key) do
Agent.get(
:tmp_storage,
fn(map) -> Map.get(map, key) end
)
end
end
application.ex:
defmodule SimpleServer.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
#moduledoc false
use Application
def start(_type, _args) do
# List all child processes to be supervised
children = [
Plug.Adapters.Cowboy.child_spec(scheme: :http, plug: SimpleServer.Router, options: [port: 8085]),
{SimpleServer.Storage, []}
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: SimpleServer.Supervisor]
Supervisor.start_link(children, opts)
end
end
mix.exs:
defmodule SimpleServer.MixProject do
use Mix.Project
def project do
[
app: :simple_server,
version: "0.1.0",
elixir: "~> 1.6",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger],
mod: {SimpleServer.Application, []}
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:poison, "~> 4.0"},
{:plug_cowboy, "~> 2.0"}
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"},
]
end
end
Note, if you use the dependencies and versions specified in the tutorial you will get some warnings, including the warning:
~/elixir_programs/simple_server$ iex -S mix
...
...
12:48:57.767 [warn] Setting Ranch options together
with socket options is deprecated. Please use the new
map syntax that allows specifying socket options
separately from other options.
...which is an issue with Plug. Here are the dependencies and versions that I used to get rid of all the warnings:
{:poison, "~> 4.0"},
{:plug_cowboy, "~> 2.0"}
Also, when you list an application as a dependency, you no longer have to enter it in the :extra_applications list. Elixir will automatically start all the applications listed as dependencies before starting your application. See :applications v. :extra_applications.
Once the server has started, you can use another terminal window to send a post request with curl (or you can use some other program):
~$ curl -v -H 'Content-Type: application/json' "http://localhost:8085/storage/set" -d '{"x": "10", "y": "20" }
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8085 (#0)
> POST /storage/set HTTP/1.1
> Host: localhost:8085
> User-Agent: curl/7.58.0
> Accept: */*
> Content-Type: application/json
> Content-Length: 23
>
* upload completely sent off: 23 out of 23 bytes
< HTTP/1.1 201 Created
< server: Cowboy
< date: Fri, 30 Nov 2018 19:22:23 GMT
< content-length: 34
< cache-control: max-age=0, private, must-revalidate
<
Server stored all key-value pairs
* Connection #0 to host localhost left intact
The > lines are the request, and the < lines are the response. Also, check the output in the terminal window where the server is running.
~$ curl -v http://localhost:8085/storage/z
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8085 (#0)
> GET /storage/z HTTP/1.1
> Host: localhost:8085
> User-Agent: curl/7.58.0
> Accept: */*
>
< HTTP/1.1 200 OK
< server: Cowboy
< date: Fri, 30 Nov 2018 19:22:30 GMT
< content-length: 25
< cache-control: max-age=0, private, must-revalidate
<
The key z doesn't exist!
* Connection #0 to host localhost left intact
.
~$ curl -v http://localhost:8085/storage/x
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8085 (#0)
> GET /storage/x HTTP/1.1
> Host: localhost:8085
> User-Agent: curl/7.58.0
> Accept: */*
>
< HTTP/1.1 200 OK
< server: Cowboy
< date: Fri, 30 Nov 2018 19:22:37 GMT
< content-length: 24
< cache-control: max-age=0, private, must-revalidate
<
The key x has value 10.
* Connection #0 to host localhost left intact
I'm not entirely sure what you're trying to accomplish, but the error is telling you that the key and value that are passed to the router with statement are not defined. Elixir thinks you are trying to call a function with those arguments because they are not "bound" to a value. That is why you are seeing warning: variable "value" does not exist and is being expanded to "value()"
I suppose this is not really an answer but maybe more an explanation of the error you're seeing.
You need to pull the key/value params out of your %Plug.Conn{} object (conn). The key/value variables have not yet been defined within the scope of your route. The conn object is only available because it is injected by the post macro provided by Plug.
I am not quite aware of what type of requests you're submitting to the router, but I'll assume it's JSON as an example. You can manually parse the body in your connection by doing something like:
with {:ok, raw_body} <- Plug.Conn.read_body(conn),
{:ok, body} <- Poison.decode(raw_body) do
key = Map.get(body, "key")
value = map.get(body, "value")
# ... other logic
end
The Plug project, however, provides a nice convenience plug for you to parse request bodies in a generic way: Plug.Parsers.
To implement this in your router, you just have to add the plug to the top of your router (below Plug.Logger I think):
plug Plug.Parsers,
parsers: [:urlencoded, :json]
json_decoder: Poison,
pass: ["text/*", "application/json"]
The :urlencoded part will parse your query parameters and the :json part will parse the body of the request.
Then below in your route, you can get the key/value params from your conn object in the :params key like so:
%{params: params} = conn
key = Map.get(params, "key")
value = Map.get(params, "value")
Also, I should note that the best JSON decoder at the moment is Jason which is basically a drop-in replacement for Poison, but faster.
Anyway, reading hexdocs really helps with figuring this stuff out and the Plug project has great documentation. I think Elixir is a great language to start programming with (although it's essential to learn object-oriented paradigms as well). Happy coding!

How to setup username and password with Slick's source code generator?

Following the directions in this page: http://slick.typesafe.com/doc/2.0.0/code-generation.html
we see that something like the following segment of code is required to generate models for mysql tables
val url = "jdbc:mysql://127.0.0.1/SOME_DB_SCHEMA?characterEncoding=UTF-8&useUnicode=true"
val slickDriver = "scala.slick.driver.MySQLDriver"
val jdbcDriver = "com.mysql.jdbc.Driver"
val outputFolder = "/some/path"
val pkg = "com.pligor.server"
scala.slick.model.codegen.SourceCodeGenerator.main(
Array(slickDriver, jdbcDriver, url, outputFolder, pkg)
)
These parameteres are enough for an H2 database as the example in the link has it.
How to include username and password for the MySQL database?
From several links found in the internet and also based on the cvogt's answer this is the minimum that you need to do.
Note that this is a general solution for sbt. If you are dealing with play framework you might find it easier to perform this task with the relevant plugin
First of all you need a new sbt project because of all the library dependencies that are needed to be referenced in order for slick source generator to run.
Create the new sbt project using this tutorial: http://scalatutorials.com/beginner/2013/07/18/getting-started-with-sbt/
Preferably use the method Setup using giter8
If it happens to work with Intellij then you need to create file project/plugins.sbt and insert inside this line: addSbtPlugin("com.hanhuy.sbt" % "sbt-idea" % "1.6.0").
Execute gen-idea in sbt to generate an intellij project.
With giter8 you get an auto-generated file ProjectNameBuild.scala inside project folder. Open this and include at least these library dependencies:
libraryDependencies ++= List(
"mysql" % "mysql-connector-java" % "5.1.27",
"com.typesafe.slick" %% "slick" % "2.0.0",
"org.slf4j" % "slf4j-nop" % "1.6.4",
"org.scala-lang" % "scala-reflect" % scala_version
)
where scala version is the variable private val scala_version = "2.10.3"
Now create the custom source code generator that looks like that:
import scala.slick.model.codegen.SourceCodeGenerator
object CustomSourceCodeGenerator {
import scala.slick.driver.JdbcProfile
import scala.reflect.runtime.currentMirror
def execute(url: String,
jdbcDriver: String,
user: String,
password: String,
slickDriver: String,
outputFolder: String,
pkg: String) = {
val driver: JdbcProfile = currentMirror.reflectModule(
currentMirror.staticModule(slickDriver)
).instance.asInstanceOf[JdbcProfile]
driver.simple.Database.forURL(
url,
driver = jdbcDriver,
user = user,
password = password
).withSession {
implicit session =>
new SourceCodeGenerator(driver.createModel).writeToFile(slickDriver, outputFolder, pkg)
}
}
}
Finally you need to call this execute method inside main project object. Find the file ProjectName.scala that was auto-generated by giter8.
Inside it you will find a println call since this is merely a "hello world" application. Above println call something like that:
CustomSourceCodeGenerator.execute(
url = "jdbc:mysql://127.0.0.1/SOME_DB_SCHEMA?characterEncoding=UTF-8&useUnicode=true",
slickDriver = "scala.slick.driver.MySQLDriver",
jdbcDriver = "com.mysql.jdbc.Driver",
outputFolder = "/some/path",
pkg = "com.pligor.server",
user = "root",
password = "xxxxxyourpasswordxxxxx"
)
This way every time you execute sbt run you are going to generate the Table classes required by Slick automatically
Note that at least for 2.0.1 this is fixed. Just add username and password to the end of the Array as Strings
This has been asked and answered here: https://groups.google.com/forum/#!msg/scalaquery/UcS4_wyrJq0/obLHheIWIXEJ . Currently you need to customize the code generator. A PR for 2.0.1 is in the queue.
My solution is nearly the same as George's answer, but I'll add mine anyway. This is the entire file I use to generate code for my mysql database in an SBT project.
SlickAutoGen.scala
package mypackage
import slick.model.codegen.SourceCodeGenerator
object CodeGen {
def main(args: Array[String]) {
SourceCodeGenerator.main(
Array(
"scala.slick.driver.MySQLDriver",
"com.mysql.jdbc.Driver",
"jdbc:mysql://localhost:3306/mydb",
"src/main/scala/",
"mypackage",
"root",
"" // I don't use a password on localhost
)
)
}
}
build.sbt
// build.sbt --- Scala build tool settings
libraryDependencies ++= List(
"com.typesafe.slick" %% "slick" % "2.0.1",
"mysql" % "mysql-connector-java" % "5.1.24",
...
)
To use this, just modify settings, save in project root directory and run as follows:
$ sbt
> runMain mypackage.CodeGen