Quantcast
Channel: Questions / Help - Elixir Programming Language Forum
Viewing all 11447 articles
Browse latest View live

Failed to connect to mysql8.0

$
0
0

@SummerGao wrote:

G:\ElixirWorkSpace\SummerGao\summergao_phoenix>mix ecto.create

15:59:35.295 [error] GenServer #PID<0.238.0> terminating
** (ArgumentError) argument error
    (stdlib 3.12) :binary.part(<<58, 118, 25, 35, 48, 106, 121, 119, 9, 22, 98, 27, 105, 109, 52, 15, 22, 119, 61, 98>>, 0, 24)
    (myxql 0.4.0) lib/myxql/protocol/auth.ex:19: MyXQL.Protocol.Auth.encrypt_sha_password/3
    (myxql 0.4.0) lib/myxql/client.ex:434: MyXQL.Client.perform_public_key_auth/5
    (myxql 0.4.0) lib/myxql/client.ex:303: MyXQL.Client.do_handshake/2
    (myxql 0.4.0) lib/myxql/client.ex:284: MyXQL.Client.handshake/2
    (myxql 0.4.0) lib/myxql/connection.ex:32: MyXQL.Connection.connect/1
    (db_connection 2.2.1) lib/db_connection/connection.ex:69: DBConnection.Connection.connect/2
    (connection 1.0.4) lib/connection.ex:622: Connection.enter_connect/5
    (stdlib 3.12) proc_lib.erl:249: :proc_lib.init_p_do_apply/3
Last message: nil
State: MyXQL.Connection
** (Mix) The database for SummergaoPhoenix.Repo couldn't be created: %RuntimeError{message: "killed"}

Posts: 1

Participants: 1

Read full topic


Trouble composing Ecto query

$
0
0

@Leonard wrote:

Hello everyone,

I am learning Elixir and Ecto at the moment but I’m having some trouble expressing this query.
I have a Post schema and want to create an Ecto query that calculates a score for each post based on different “scorers” modules.

So far, here is what I have:

    scorers = [{PostActivityScorer, 3}]

    total_weight = Enum.map(scorers, fn {_, weight} -> weight end) |> Enum.sum()

    total_score = fn post ->
      Enum.reduce(scorers, 0, fn {scorer, weight}, current_score ->
        # Each scorer.score function would return another expression,
        # for example: fragment("CASE WHEN p.type = ? THEN 1 ELSE 0 END)", "some type")
        ^scorer.score(post) * ^weight + ^current_score
      end)
    end

    posts_with_score_query = from(p in Post, select: {p, ^total_score.(p) / ^total_weight})

Is this possible in Ecto? I have tried with dynamic() but as far as I can tell there is no way to interpolate it inside the “select” clause.

Thanks in advance.

Posts: 3

Participants: 2

Read full topic

Remove assigns in LiveView

How can I write a raw sql query?

$
0
0

@siddhant3030 wrote:

Hi,

I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw queries in phoenix. So to understand

I have created a user schema that inserts an email in a database table.

So created the changeset the like this

def changeset(user, attrs) do
user
|> cast(attrs, [:email, :password])
end

Now I have a create function that I’m using in my model. So the model will basically talk to db.

def create_user(attrs \\ %{}) do
    %User{}
    |> User.changeset(attrs)
    |> Repo.insert()
end

I have inserted an email in my database. using this
iex(1) > user = User.changeset(%User{}, %{email: “”, password: “”})

Now what I want is to find that user by his email address.
Also If I wanted to fetch through id. I would just do this

def get_user!(id), do: Repo.get!(User, id)

But what if I want to write a raw query? How do I do that?

Posts: 21

Participants: 6

Read full topic

(UndefinedFunctionError) function HTTPoison.request/5 is undefined (module HTTPoison is not available

$
0
0

@mandarvaze wrote:

I am facing a unique(?) problem.

I have unit tests and integration tests

Both call the same set of functions.

All the integration tests pass (mix test --include integration test/integration/gateways/mercadopago_test.exs)

All the unit tests fail (mix test test/gateways/mercadopago_test.exs)

For every unit test , I get the same error :

** (UndefinedFunctionError) function HTTPoison.request/5 is undefined (module HTTPoison is not available)

Stack trace points to lib/gringotts/gateways/mercadopago.ex:264: Gringotts.Gateways.Mercadopago.commit/5

Searching for module not available points to solutions that do not apply.

Most suggest including httpoison in mix.exs - which was already have (https://github.com/aviabird/gringotts/blob/mercadopago-2020/mix.exs#L40)

Other suggestion is about elixirc_paths - which also taken care of (https://github.com/aviabird/gringotts/blob/mercadopago-2020/mix.exs#L19)

BTW, I’m a n00b at elixir, so I may be overlooking something obvious.

I’ve already asked for helped in local elixir discord channel. No luck.

Thanks for any suggestions/ideas.

Posts: 6

Participants: 4

Read full topic

Something that simple really scratch my head: cannot invoke remote function :erlang.+/2 inside a match

$
0
0

@Ajaxdone wrote:

I run this :

iex(3)> 1 + 2 = 3
** (CompileError) iex:3: cannot invoke remote function :erlang.+/2 inside a match

but it works on https://repl.it/languages/elixir

Erlang/OTP 20.0
 iex
Erlang/OTP 20 [erts-9.2] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [kernel-poll:false]

Interactive Elixir (1.3.3) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> 
nil
iex(2)> 
nil
iex(3)> 1 + 2 = 3
3
iex(4)> 

Anybody any idea about this?

Posts: 5

Participants: 3

Read full topic

Keeping track of WebSocket disconnects

$
0
0

@fxn wrote:

I have a Channels application (WS only) whose clients are phone apps whose source code I control.

The application logs WS connections in the connect/3 callback, but as we know, there is no disconnect callback. I have done some searches and looks like being notified of a disconnection is not trivial (please let me know if I missed any robust solution).

However, in my local tests it seems that a channel’s terminate/2 is called when the socket is closed just fine. I guess that’s possible due to the process structure. Would it be a bad idea to track disconnections this way?

For example, a simple approach could be the following: First thing after connecting, phones would be required to join a dedicated connected channel whose only purpose is to log on join/3 and on terminate/2. Assuming the client code is correct, the join is correctly programmed, and no manual unjoin is coded, do you see drawbacks or better ways to solve this?

Posts: 20

Participants: 4

Read full topic

Creating Ecto Schemas via Macros

$
0
0

@GrantJamesPowell wrote:

I’m new to macros and I’m trying to do the following

defmodule Example do
  use Ecto.Schema

  compile_time_var = [foo: Foo, bar: Bar, baz: Baz]

  schema "my_schema" do
      # some macro magic here with `compile_time_var`
  end
end

I’d like to use macros to have the module compile as if the schema looked like this

defmodule Example do
  use Ecto.Schema

  schema "my_schema" do
    has_one :foo, Foo
    has_one :bar, Bar
    has_one :baz, Baz
  end
end

But, I can’t figure out the right combination of quote and unquote to use with the compile time variable

Posts: 2

Participants: 2

Read full topic


Struggling With Schema and Seeding Issue

$
0
0

@tnederlof wrote:

** Just edited the scrips to corrected the wrong way associations I had and tried a different approach to the seed file. The error I am getting now is…

15:50:15.441 [info] create table locations
** (Postgrex.Error) ERROR 42P01 (undefined_table) relation “stations” does not exist

After reading through some books and tutorials I have setup a Phoenix app using Ecto and am struggling with a has_one, belongs_to association. I have Stations, which each have strings I would like to use as station ids.
Each location has one or no station, but each station may have multiple locations.

When I try to seed the database I get an error “** (ArgumentError) unknown field :location_id in %TestApp.Weather.Station”

Station Schema

defmodule TestApp.Weather.Station do
  use Ecto.Schema
  import Ecto.Changeset

  @primary_key {:id, :string, []}
  @derive {Phoenix.Param, key: :id}
  @timestamps_opts [type: :utc_datetime]

  schema "stations" do
    field :latitude, :float
    field :longitude, :float
    field :name, :string

    has_many :locations, TestApp.Weather.Location

    timestamps()
  end

  def changeset(station, attrs) do
    required_fields = [:latitude, :longitude, :name]

    station
    |> cast(attrs, required_fields)
    |> validate_required(required_fields)
  end

end

Location Schema

defmodule TestApp.Weather.Location do
  use Ecto.Schema
  import Ecto.Changeset
  @timestamps_opts [type: :utc_datetime]

  schema "locations" do
    field :latitude, :float
    field :longitude, :float
    field :name, :string

    belongs_to :station, TestApp.Weather.Station

    timestamps()
  end

  def changeset(location, attrs) do
    required_fields = [:latitude, :longitude, :name]
    optional_fields = [:station_id]

    location
    |> cast(attrs, required_fields ++ optional_fields)
    |> validate_required(required_fields)
    |> assoc_constraint(:station)
  end

end

Location Migration

defmodule TestApp.Repo.Migrations.CreateLocations do
  use Ecto.Migration

   def change do
    create table(:locations) do
      add :latitude, :float, null: false
      add :longitude, :float, null: false
      add :name, :string, null: false
      add :station_id, references(:stations)

      timestamps()
    end

    create unique_index(:locations, [:name])
  end
end

Station Migration

defmodule TestApp.Repo.Migrations.CreateStations do
  use Ecto.Migration

 def change do
    create table(:stations, primary_key: false) do
      add :id, :string, primary_key: true
      add :latitude, :float, null: false
      add :longitude, :float, null: false
      add :name, :string, null: false

      timestamps()
    end

    create unique_index(:stations, [:name])
  end
end

Seed File

alias TestApp.Repo
alias TestApp.Weather.{Location, Station}

    station1 = %Station{
      id: "USC00012209",
      latitude: 34.5569,
      longitude: -86.9503,
      name: "DECATUR 5SE",
    }

    location1 = %{
      latitude: 34.7998,
      longitude: -87.6773,
      name: "Florence, AL"
    }

    %Location{}
    |> Location.changeset(location1)
    |> Ecto.Changeset.put_assoc(:station, station1)
    |> Repo.insert()


Posts: 7

Participants: 3

Read full topic

What do you think of my solution for converting integers to roman numerals?

$
0
0

@ryanzidago wrote:

What do you think of my solution for converting integers to roman numerals?

defmodule RomanNumerals do
  import IO, only: [iodata_to_binary: 1]

  @doc """
  Convert the number to a roman number.
  """
  @spec numeral(pos_integer) :: String.t()
  def numeral(0),               do: ""
  def numeral(1),               do: "I"
  def numeral(2),               do: "II"
  def numeral(3),               do: "III"
  def numeral(4),               do: "IV"
  def numeral(5),               do: "V"
  def numeral(6),               do: "VI"
  def numeral(7),               do: "VII"
  def numeral(8),               do: "VIII"
  def numeral(9),               do: "IX"
  def numeral(10),              do: "X"
  def numeral(50),              do: "L"
  def numeral(100),             do: "C"
  def numeral(500),             do: "D"
  def numeral(1000),            do: "M"
  def numeral(n) when n < 40,   do: [numeral(10), numeral(n - 10)]                  |> iodata_to_binary()
  def numeral(n) when n < 50,   do: [numeral(10), numeral(50), numeral(n - 40)]     |> iodata_to_binary()
  def numeral(n) when n < 90,   do: [numeral(50), numeral(n - 50)]                  |> iodata_to_binary()
  def numeral(n) when n < 100,  do: [numeral(10), numeral(100), numeral(n - 90)]    |> iodata_to_binary()
  def numeral(n) when n < 400,  do: [numeral(100), numeral(n - 100)]                |> iodata_to_binary()
  def numeral(n) when n < 500,  do: [numeral(100), numeral(500), numeral(n - 400)]  |> iodata_to_binary()
  def numeral(n) when n < 900,  do: [numeral(500), numeral(n - 500)]                |> iodata_to_binary()
  def numeral(n) when n < 1000, do: [numeral(100), numeral(1000), numeral(n - 900)] |> iodata_to_binary()
  def numeral(n) when n < 5000, do: [numeral(1000), numeral(n - 1000)]              |> iodata_to_binary()
end

Posts: 10

Participants: 6

Read full topic

Parse IPV4 or IPV6 bitstrings

$
0
0

@pedromvieira wrote:

Hi, I’am parsing OTPCertificates obtain with :ssl.
Some alternative names has IPV4 or IPV6 bitstrings like:

[
  iPAddress: <<1, 1, 1, 1>>,
  iPAddress: <<1, 0, 0, 1>>,
  iPAddress: <<162, 159, 132, 53>>,
  iPAddress: <<38, 6, 71, 0, 71, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17>>,
  iPAddress: <<38, 6, 71, 0, 71, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 1>>,
  iPAddress: <<38, 6, 71, 0, 71, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100>>,
  iPAddress: <<38, 6, 71, 0, 71, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0>>,
  iPAddress: <<162, 159, 36, 1>>,
  iPAddress: <<162, 159, 46, 1>>
]

I successfully translated IPV4 ones (Ex: “162.159.132.53”) with this code:

            <<162, 159, 132, 53>>
            |> :unicode.characters_to_binary(:latin1, :utf8)
            |> to_charlist()
            |> List.to_tuple()
            |> :inet_parse.ntoa()
            |> to_string()

But I couldn’t translate IPV6. Any ideas?

<<38, 6, 71, 0, 71, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17>> should translate to “2606:4700:4700:0:0:0:0:1111”

Posts: 3

Participants: 2

Read full topic

Which is the notation for functions with several arities?

$
0
0

@fxn wrote:

Is there a convention for how to refer to functions that have the same name but different arities?

For example, we have Phoenix.Socket.connect/2 and Phoenix.Socket.connect/3. If I want to make a general statement about them, like "you authorize a WS connection in Phoenix.Socket.connect/???", which notation do you use to refer to both of them at the same time?

I am tentatively writing Phoenix.Socket.connect/2,3.

Posts: 2

Participants: 2

Read full topic

Macro and :erlang.atom_to_binary error

$
0
0

@tomthestorm wrote:

Hi, I’ve got macro which returns function
@spec my_macro(atom()) :: fun()
defmacro my_macro(var1) do

end

In Repl when I invoke :

my_macro(:my_atom) ,
the result is what I expected : #Function<13.126501267/2 in :erl_eval.expr/5>

but when I invoke

my_atom_2 = :my_atom
my_macro(my_atom_2)

I’ve got error :
** (ArgumentError) argument error
:erlang.atom_to_binary({:my_atom_2, [line: 36], nil}, :utf8)

How to solve it ? I need pass variable to macro not atom explicit value

Thanks for help in advance .
TT

Posts: 7

Participants: 4

Read full topic

Can we restrict the deletion of a user from database based on the email address?

$
0
0

@rameshsharma wrote:

Can we restrict the deletion of a user from database based on his email address in Repo.delete!(changeset) condition in elixir and phoenix web development

This is right now the code which I am using. I want to restrict the deletion of two users from database during deletion:-

def delete(conn, _params, current_admin) do

    changeset = AdminUser.common_changeset(conn.assigns.admin_user, %{}, whodoneit(current_admin))

    Repo.delete!(changeset)

    msg = gettext("%{name} deleted successfully", name: gettext("Administrator"))

    conn
    |> put_flash(:success, msg)
    |> redirect(to: Routes.admin_admin_user_path(conn, :index))

end


I want to restrict the deletion of users with email ids say 'test1@gmail.com' and 'test2@gmail.com'. But I am not sure how to use this in changeset.

Posts: 12

Participants: 4

Read full topic

Handle error in ecto preload

$
0
0

@david234 wrote:

I have the below function which runs the query and returns the map

  defp fetch_uid_data(%{admin_id: admin_id, uid: uid}) do
    
    query = from(u in Uid,
                   where: u.admin_id == ^admin_id and u.uid == ^uid,
                   preload: [:products])

    uid = Repo.one(query)

    case uid do
      nil ->
        {:error, "Sorry! data not found"}
      {:error} ->
        {:error, "Data error"}
      uid ->
        {:ok, %{uid: uid.uid, scan_count: uid.scan_count, 
                  admin_id: uid.admin_id, product_id: uid.product_id,
                  no_of_scans: uid.products.no_of_scans}}
    end
  end

Query Struct will be

%Uids.Uid{
  __meta__: #Ecto.Schema.Metadata<:loaded, "uids">,
  admin_id: "6a9700b4-509c-40bf-8780-b029da872c96",
  id: 1,
  inserted_at: ~N[2020-04-11 07:08:22],
  product_id: "9a9700b4-509c-40bf-8780-b029da872c77",
  products: %Protectivv.Products.Product{
    __meta__: #Ecto.Schema.Metadata<:loaded, "products">,
    admin_id: "6a9700b4-509c-40bf-8780-b029da872c96",
    description: "Test TV",
    id: "9a9700b4-509c-40bf-8780-b029da872c77",
    images: #Ecto.Association.NotLoaded<association :images is not loaded>,
    inserted_at: ~N[2020-04-11 07:08:22],
    name: "TV",
    no_of_scans: 5,
    updated_at: ~N[2020-04-11 07:08:22],
    videos: #Ecto.Association.NotLoaded<association :videos is not loaded>
  },
  scan_count: 0,
  uid: "7a589",
  updated_at: ~N[2020-04-11 07:08:22]

As you can see I am getting the no_of_scans field from a product’s association

uid.products.no_of_scans

Sometimes the product association will be null. That time this will throw an error.

So I want to know how to improve the above coding. In order to be robust.

I tried like this

    query = from(u in Uid,
                   where: u.admin_id == ^admin_id and u.uid == ^uid,
                   preload: [:products],
                   select: %{uid: u.uid, scan_count: u.scan_count, 
                  admin_id: u.admin_id, product_id: u.product_id,
                  no_of_scans: u.products.no_of_scans})

    uid = Repo.one(query)

But it gives me the below error

** (Ecto.Query.CompileError) u.products.no_of_scans is not a valid query expression. If you want to invoke u.products.no_of_scans/0 in a query, make sure that the module u.products is required and that no_of_scans/0 is a macro

If anyone can give me insight on how to improve my coding standard that will be greatly appreciated.Thanks.

Plus is there any course or ways to improve coding standards in elixir. Please share it. That will be a great help. Thanks

Posts: 1

Participants: 1

Read full topic


Write Malformed JSON in the body Plug

$
0
0

@tanweerdev wrote:

I am trying to write a plug which will generate a custom error if the request has malformed JSON which is quite often the case in our scenarios(as we use variables in postman. eg sometimes there is no quote outside the value and it results in malformed JSON). The only help I got is https://groups.google.com/forum/#!topic/phoenix-talk/8F6upFh_lhc which isnt working of course.

defmodule PogioApi.Plug.PrepareParse do
  import Plug.Conn
  @env Application.get_env(:application_api, :env)

  def init(opts) do
    opts
  end

  def call(conn, opts) do
    %{method: method} = conn
    # TODO: check for PUT aswell
    if method in ["POST"] and not(@env in [:test]) do
      {:ok, body, _conn} = Plug.Conn.read_body(conn)
      case Jason.decode(body) do
        {:ok, _result} -> conn
        {:error, _reason} ->
          error = %{message: "Malformed JSON in the body"}
          conn
          |> put_resp_header("content-type", "application/json; charset=utf-8")
          |> send_resp(400, Jason.encode!(error))
          |> halt
      end
    else
      conn
    end
  end
end

Posts: 14

Participants: 3

Read full topic

[Elixir] How to remove "" from a string, and convert it a variable?

$
0
0

@jejuro wrote:

I have two variables:

iex(1)> i = 1  
1
iex(2)> user_1 = "Jupeter"
"Jupeter"
iex(3)> new_variable = "user_" <> "#{i}"
"user_1"
iex(4)> IO.puts new_variable
user_1
:ok

I wanna get “Jupeter” rather than user_1. Any idea will be appreciated. .

Posts: 24

Participants: 6

Read full topic

LiveView: (ArgumentError) assign @count not available in eex template.

$
0
0

@gpreston wrote:

I have a LiveView with the following code:

defmodule Webcandy2LocalWeb.CounterLive do
  use Phoenix.LiveView

  def mount(_session, socket) do
    socket = assign(socket, :count, 0)
    {:ok, socket}
  end

  def render(assigns) do
    ~L"""
    <h1>Count: <%= @count %></h1>
    <button>+</button>
    <button>-</button>
    """
  end
end

When I try to access the page for this LiveView, I get the following error:

Request: GET /counter
** (exit) an exception was raised:
    ** (ArgumentError) assign @count not available in eex template.

Please make sure all proper assigns have been set. If this
is a child template, ensure assigns are given explicitly by
the parent template as they are not automatically forwarded.

Available assigns: [:flash, :live_action, :live_module, :socket]

I don’t see why this is happening because I assign :count in the mount/2 function. Is there something I’m missing?

Posts: 2

Participants: 2

Read full topic

Recommanded way to secure liveview callback

$
0
0

@seb3s wrote:

Hi,
in the process of securing my liveview callbacks, I’m hardening my handle_event callbacks checking that actions are allowed for the user submitting it.

My question is : is it ok to use raise as in the following excerpt ?

  def handle_event("delete_board", %{"id" => id} = params, %{assigns: assigns} = socket) do
    id = to_integer(id)
    row = Enum.find(assigns.boards, & &1.id == id)
    if !row , do: raise("Access to forbidden data detected")
    if !user_rights(row, :delete_board?), do: raise("Improper right access detected")
    {:ok, res} = Repo.query("select sp_delete_board($1);", [id])
    boards = for b <- assigns.boards, b.id != id, do: b
    broadcast_from(self(), @boards_topic, "delete_board", %{id: id})
    {:noreply, assign(socket, boards: boards)}
  end

Or should I go we nested case/if returning non modified socket object so that nothing is done where action is not validated. How do you handle it in your apps ?

TIA,

Sébastien.

Posts: 1

Participants: 1

Read full topic

How to queue messages on a sender node?

$
0
0

@hangyas wrote:

I have an IoT device that sends sensor data to a server, but it isn’t always connected to the network (and/or the server might be offline). When the server is available, the IoT device is connected to its cluster.

My plan is that the IoT node saves the sensor data into a queue (preferably persisted with mnesia), and - when they are connected - the server receives the messages from this queue. So the server more or less doesn’t have to know about the queue / when the queue is empty it gets notified about the new messages the same way as it gets notified about the first item of a non-empty queue when the nodes get connected.

My question is: Does such a queue library exists?

If not: What would be the best way to implement this - particularly how to “pull” messages from the queue? My first idea is a GenServer that receives messages from the sensor and requests from the server. After a request it dispatched the first item of the queue to the server as soon its available (and probably pops it from the queue, when the server acknowledges it)

(I was also considering job processing libraries, but for obvious reasons they all assume that the server is always available, thus the messages queued on the server.)

Thanks for any suggestions

Posts: 9

Participants: 3

Read full topic

Viewing all 11447 articles
Browse latest View live