Guest User

Untitled

a guest
Sep 25th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. defmodule PhxAdmin do
  2. {:ok, _} = Application.ensure_all_started(:postgrex)
  3.  
  4. {:ok, pid} =
  5. Postgrex.start_link(
  6. hostname: "localhost",
  7. username: "postgres",
  8. password: "postgres",
  9. database: "phx_admin_dev"
  10. )
  11.  
  12. tables_query = """
  13. select table_name from information_schema.tables
  14. where table_schema != 'pg_catalog'
  15. and table_schema != 'information_schema'
  16. and table_name != 'schema_migrations'
  17. """
  18.  
  19. %{rows: tables} =
  20. Postgrex.query!(
  21. pid,
  22. tables_query,
  23. []
  24. )
  25.  
  26. relations =
  27. Enum.map(tables, fn [table_name] ->
  28. module_name = ("Elixir.Relations." <> Macro.camelize(table_name)) |> String.to_atom()
  29.  
  30. columns_query = """
  31. select column_name, data_type
  32. from information_schema.columns
  33. where table_name = $1
  34. order by ordinal_position
  35. """
  36.  
  37. %{rows: columns} = Postgrex.query!(pid, columns_query, [table_name])
  38.  
  39. fields =
  40. Enum.map(columns, fn
  41. ["id", "bigint"] ->
  42. nil
  43.  
  44. [column_name, "character varying"] ->
  45. {column_name, "string"}
  46.  
  47. _ ->
  48. nil
  49. end)
  50. |> Enum.filter(& &1)
  51.  
  52. module = """
  53. defmodule module_name do
  54. use Ecto.Schema
  55. schema table_name do
  56. <%= for {column_name, column_type} <- fields do %>
  57. field :<%= column_name %>, :<%= column_type %>
  58. <% end %>
  59. end
  60. end
  61. """
  62.  
  63. module
  64. |> EEx.eval_string(fields: fields)
  65. |> Code.eval_string(module_name: module_name, table_name: table_name)
  66.  
  67. module_name
  68. end)
  69.  
  70. @relations relations
  71.  
  72. def relations(), do: @relations
  73. end
Add Comment
Please, Sign In to add comment