Elixir: PostgreSQL のデータを作成 (Create)

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

## Julia のプログラム

```jl:postgre_create.jl
#
#	postgre_create.jl
#
#						Mar/16/2024
# --------------------------------------------------------------------
using LibPQ
using DotEnv

# --------------------------------------------------------------------
function dict_append_proc(dict_aa,key,name,population,date_mod)
    K = ["name","population","date_mod"]
    V = [name,population,date_mod]
#   unit_aa = Dict(K,V)
    unit_aa = Dict("name" => name,"population" => population, "date_mod" => date_mod)
    dict_aa[key] = unit_aa
#
    return  dict_aa
end
# --------------------------------------------------------------------
function data_prepare_proc()
	dict_aa = Dict()
#
	dict_aa = dict_append_proc(dict_aa,"t3461","広島",32561,"2013-4-30")
	dict_aa = dict_append_proc(dict_aa,"t3462","福山",81295,"2013-8-10")
	dict_aa = dict_append_proc(dict_aa,"t3463","東広島",28674,"2013-3-14")
	dict_aa = dict_append_proc(dict_aa,"t3464","呉",73612,"2013-2-9")
	dict_aa = dict_append_proc(dict_aa,"t3465","尾道",52391,"2013-8-4")
	dict_aa = dict_append_proc(dict_aa,"t3466","竹原",95187,"2013-1-21")
	dict_aa = dict_append_proc(dict_aa,"t3467","三次",31246,"2013-7-23")
	dict_aa = dict_append_proc(dict_aa,"t3468","大竹",85791,"2013-11-26")
	dict_aa = dict_append_proc(dict_aa,"t3469","府中",24139,"2013-10-15")
#
	return	dict_aa
end
# --------------------------------------------------------------------
function create_table_proc(conn)
	sql_str = "drop table cities"
	println(sql_str)
	aa = execute(conn,sql_str)
	println(aa)
#
	sql_str = "create table cities (id varchar(10) primary key, name text, population int, date_mod date)"
	println(sql_str)
	aa = execute(conn,sql_str)
	println(aa)
#
end
# --------------------------------------------------------------------
function insert_proc(conn,dict_aa)
	for key in sort(collect(keys(dict_aa)))
		print(key, '\t', dict_aa[key]["name"])
		print('\t', dict_aa[key]["population"])
		println('\t', dict_aa[key]["date_mod"])
		ft_aa = "insert into cities (id,name,population,date_mod) values ("
		ft_bb = "'" * key * "','" * dict_aa[key]["name"] * "',"
		ft_cc = "'" * string(dict_aa[key]["population"]) * "',"
		ft_dd = "'" * dict_aa[key]["date_mod"] * "')"
		sql_str = ft_aa * ft_bb * ft_cc * ft_dd
		println(sql_str)
		aa = execute(conn,sql_str)
		println(aa)
	end
#
end
# --------------------------------------------------------------------
println("*** 開始 ***")
cfg=DotEnv.config()
user=cfg["user"]
password=cfg["password"]
data_base=cfg["data_base"]

dict_aa = data_prepare_proc()

str_connect = "dbname= " * data_base * " host=127.0.0.1 user=scott password=tiger123 port=5432"
conn = LibPQ.Connection(str_connect)
create_table_proc(conn)
insert_proc(conn,dict_aa)

#
close(conn)
#
println("*** 終了 ***")
# --------------------------------------------------------------------
```

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

```exs:lib/postgre_create.ex
defmodule PostgreCreate do
  alias Ecto.Adapters.Postgres
  alias PostgreCreate.Dict

  defmodule Dict do
    defstruct name: nil, population: nil, date_mod: nil
  end

  defp dict_append(dict_aa, key, name, population, date_mod) do
    unit_aa = %Dict{name: name, population: population, date_mod: date_mod}
    Map.put(dict_aa, key, unit_aa)
  end

  def data_prepare do
    dict_aa = %{}

    dict_aa = dict_append(dict_aa, "t3461", "広島", 32561, "2013-4-30")
    dict_aa = dict_append(dict_aa, "t3462", "福山", 81295, "2013-8-10")
    dict_aa = dict_append(dict_aa, "t3463", "東広島", 28674, "2013-3-14")
    dict_aa = dict_append(dict_aa, "t3464", "呉", 73612, "2013-2-9")
    dict_aa = dict_append(dict_aa, "t3465", "尾道", 52391, "2013-8-4")
    dict_aa = dict_append(dict_aa, "t3466", "竹原", 95187, "2013-1-21")
    dict_aa = dict_append(dict_aa, "t3467", "三次", 31246, "2013-7-23")
    dict_aa = dict_append(dict_aa, "t3468", "大竹", 85791, "2013-11-26")
    dict_aa = dict_append(dict_aa, "t3469", "府中", 24139, "2013-10-15")

    dict_aa
  end

  def create_table(conn) do
    sql_str = "drop table cities"
    IO.puts(sql_str)
    :ok = Postgres.query(conn, sql_str)

    sql_str = "create table cities (id varchar(10) primary key, name text, population int, date_mod date)"
    IO.puts(sql_str)
    :ok = Postgres.query(conn, sql_str)
  end

  def insert(conn, dict_aa) do
    for {key, value} <- Enum.sort(Map.to_list(dict_aa)) do
      IO.puts("#{key}\t#{value.name}\t#{value.population}\t#{value.date_mod}")
      sql_str = "insert into cities (id, name, population, date_mod) values ($1, $2, $3, $4)"
      params = [key, value.name, value.population, value.date_mod]
      IO.puts(sql_str)
      :ok = Postgres.query(conn, sql_str, params)
    end
  end

  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")

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

    create_table(conn)
    insert(conn, dict_aa)

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

# Usage
PostgreCreate.run()
```

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

実行結果

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

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

## Gemini の回答

```text
I can't directly convert the entire Julia program to Elixir
due to some library and syntax differences.
However, I can provide an Elixir equivalent that achieves
the same functionality using similar concepts.
Here's the breakdown:
```

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/179446/7962d2f6-b613-2b13-e76a-3cfbe59845b3.png)