Elixir: PostgreSQL のデータを読む (Read)

Julia のプログラムを、ChatGPT と Gemini に渡して得られた結果です。

## Julia のプログラム

```jl:postgre_read.jl
#
#	postgre_read.jl
#
#						Mar/16/2024
# --------------------------------------------------------------------
using LibPQ
using DotEnv
# --------------------------------------------------------------------
println("*** 開始 ***")
cfg=DotEnv.config()
user=cfg["user"]
password=cfg["password"]
data_base=cfg["data_base"]

str_connect = "dbname= " * data_base * " host=127.0.0.1 user=scott password=tiger123 port=5432"
conn = LibPQ.Connection(str_connect)
command = "select * from cities"
results = execute(conn, command)
for row in results
	print(row[1],'\t',row[2],'\t')
	println(row[3],'\t',row[4])
end
#
close(conn)
#
println("*** 終了 ***")
# --------------------------------------------------------------------
```

## ChatGPT が作成したプログラム

```exs:lib/postgre_read.ex
defmodule PostgreRead do
  alias Ecto.Adapters.Postgres

  def run do
    IO.puts("*** 開始 ***")
    {:ok, _} = Dotenv.load()

    user = System.get_env("user")
    password = System.get_env("password")
    data_base = System.get_env("data_base")

    str_connect = "postgres://#{user}:#{password}@localhost/#{data_base}"
    {:ok, conn} = Postgres.connect(url: str_connect)

    command = "select * from cities"
    {:ok, result} = Postgres.query(conn, command)

    Enum.each(result.rows, fn row ->
      [id, name, population, date_mod] = row
      IO.puts("#{id}\t#{name}\t#{population}\t#{date_mod}")
    end)

    Postgres.stop(conn)
    IO.puts("*** 終了 ***")
  end
end

# Usage
PostgreRead.run()
```

```exs:mix.exs
（省略）
	{:ecto, "~> 3.11"},
    {:dotenv, "~> 3.1"},
（省略）
```

実行結果

```text
$ mix run
Compiling 1 file (.ex)
*** 開始 ***

== Compilation error in file lib/postgre_read.ex ==
** (MatchError) no match of right hand side value: %Dotenv.Env{paths: ["/home/uchida/lang/elixir/chatgpt/postgre/crud/read/chatgpt/postgre_read/.env"], values: %{"data_base" => "city", "password" => "tiger123", "user" => "scott"}}
    lib/postgre_read.ex:6: PostgreRead.run/0
    lib/postgre_read.ex:29: (file)
    (elixir 1.16.2) lib/kernel/parallel_compiler.ex:428: anonymous fn/5 in Kernel.ParallelCompiler.spawn_workers/8
```

## Gemini が作成したプログラム

```exs:lib/postgre_read.ex
# 必要なライブラリの読み込み
defmodule MyApp do
  use Ecto.Query
  use Ecto.Adapters.Postgres

  # ... (その他の必要なライブラリ)
end

def main do
  # 環境変数から設定を読み込み
  config = DotEnv.config()
  database = config["data_base"]
  username = config["user"]
  password = config["password"]

  # データベース接続
  conn = connect(database, username, password)

  # クエリ実行
  results = from c in "cities" do
    select c
  end

  # 結果処理
  Enum.each(results, fn row ->
    IO.puts "#{row.id}\t#{row.name}\t#{row.population}\t#{row.date_mod}"
  end)

  # 接続を閉じる
  disconnect(conn)

  # 終了メッセージ
  IO.puts "*** 終了 ***"
end

# 起動
main()
```

```exs:mix.exs
（省略）
	{:ecto, "~> 3.11"},
    {:dotenv, "~> 3.1"},
（省略）
```

実行結果

```text
$ mix run
Compiling 1 file (.ex)

== Compilation error in file lib/postgre_read.ex ==
** (ArgumentError) cannot invoke def/2 outside module
    (elixir 1.16.2) lib/kernel.ex:6556: Kernel.assert_module_scope/3
    (elixir 1.16.2) lib/kernel.ex:5180: Kernel.define/4
    (elixir 1.16.2) expanding macro: Kernel.def/2
    lib/postgre_read.ex:9: (file)
```

## 私が作成したプログラム

```exs:lib/lib/postgre_read.ex
defmodule PostgreRead do
  @moduledoc """
  Documentation for `PostgreRead`.
  """

  @doc """
  Hello world.

  ## Examples

      iex> PostgreRead.hello()
      :world

  """
  def hello do
    :world
  end

  def main([]) do
    IO.puts "*** 開始 ***"
#
    {:ok, pid} = Postgrex.start_link(hostname: "localhost", 
	username: "scott", password: "tiger123", database: "city")
    aa = Postgrex.query!(pid, "SELECT * FROM cities", [])
#
    IO.inspect aa
#
    IO.puts "*** 終了 ***"
  end

end
```

```exs:mix.exs
（省略）
	{:postgrex, "~> 0.17.5"},
（省略）
```

実行結果

```text
$ mix run -e "PostgreRead.main([])"
*** 開始 ***
%Postgrex.Result{
  command: :select,
  columns: ["id", "name", "population", "date_mod"],
  rows: [
    ["t3461", "広島", 32561, ~D[2013-04-30]],
    ["t3462", "福山", 81295, ~D[2013-08-10]],
    ["t3463", "東広島", 28674, ~D[2013-03-14]],
    ["t3464", "呉", 73612, ~D[2013-02-09]],
    ["t3465", "尾道", 52391, ~D[2013-08-04]],
    ["t3466", "竹原", 95187, ~D[2013-01-21]],
    ["t3467", "三次", 31246, ~D[2013-07-23]],
    ["t3468", "大竹", 85791, ~D[2013-11-26]],
    ["t3469", "府中", 24139, ~D[2013-10-15]]
  ],
  num_rows: 9,
  connection_id: 32227,
  messages: []
}
*** 終了 ***
```