5

After doing some research in the link below

https://github.com/elixir-lang/ecto/tree/master/examples/simple

I am a little confused about how to use ecto in elixir.

There is always a schema declared like

defmodule Weather do
  use Ecto.Model

  schema "weather" do
    field :city, :string
    field :temp_lo, :integer
    field :temp_hi, :integer
    field :prcp, :float, default: 0.0
    timestamps
  end
end

and then in the 'Query' part

 def sample_query do
   query = from w in Weather,
      where: w.prcp > 0.0 or is_nil(w.prcp),
      select: w
   Simple.Repo.all(query)
   end
 end

ecto gona form a query using the schema declared in Weather

My question is that I just want to connect to an existing database 'TESTDB' and doing some SELECT, I don't need any new schmema to do my work. Is it possible to do it in ecto please?

When I create my own query like

query = from w in tenant

after I input the command $ mix do deps.get, compile

the error tells me function tenant/0 undefined

tenant is not function, it just a table in TESTDB that I didn't declare anywhere

I think I just lost myself in ecto

王志軍
  • 1,021
  • 1
  • 11
  • 21

2 Answers2

11

You can query any table in the database by passing a string:

from p in "posts", where: p.id > 0

In such cases, you don't need to define any schema, you can just query the table directly. Finally, you can also do a SQL query directly:

Ecto.Adapters.SQL.query(YourRepo, "SELECT $1", [1])

But then you lose most of the benefits Ecto gives you.

José Valim
  • 50,409
  • 12
  • 130
  • 115
  • 2
    This is informative!! I also figured out if I want to select multiple fields, I need to do it like `select: {p.id, p.uuid}` – 王志軍 May 14 '15 at 03:35
  • It seems that it does not work. I get the following error message: `Please specify a model or specify exactly which fields from "l0" you desire in query:`. – Martinos Apr 13 '16 at 00:18
  • I tried to add `select: p.*` and it didn't work. Is it possible to list all fields without enumerating them ? – Martinos Apr 13 '16 at 00:37
6

You need to declare the schema for your table whether you create it using Ecto or not. I don't think there's currently an option to do this automatically. So for example you can have something like:

defmodule Tenant do
  use Ecto.Model

  schema "tenant" do
    field :id, :integer
    field :name, :string
    # and so on depending on the columns in your table
  end
end

And then do query = from w in Tenant, select: w

Paweł Obrok
  • 22,568
  • 8
  • 74
  • 70