Search code examples
elixirphoenix-frameworkecto

Ecto Datetime Error during insert


I am trying to put in a datetime as insert_all doesn't add created_dates automatically and I can't figure out what I am doing wrong.

currentTime = DateTime.utc_now

query = from rm in ChatApp.Roles.RoleMasters,
            join: srp in ChatApp.Servers.ServerTypeParameters,
            where: srp.parameter_role_capable_flag == "Y",
            select: %{role_master_id: rm.id, server_type_code: srp.server_type_code, parameter_namespace: srp.parameter_namespace, 
                      parameter: srp.parameter, parameter_value: srp.parameter_default_value, 
                      user_changeable_flag: "Y", description: srp.description, 
                      active_flag: "Y", created_date: ^currentTime}

roleMasterRows = ChatApp.Repo.all(query)


ChatApp.Repo.insert_all(ChatApp.Roles.RoleMasterParameters, roleMasterRows)

My error message looks like this:

value {{2017, 5, 10}, {20, 28, 42, 0}} for ChatApp.Roles.RoleMasterParameters.created_date in insert_all does not match type :utc_datetime

In the ecto.schema it turns the datetime into Tuples, but I am lost as to why it doesn't like mine.

I am stuck I went through the Ecto.Schema code and it looks like it wants tuples, but I am obviously missing something, thanks!


Solution

  • I am going to leave this here in case anyone else is having this issue.

    The issue stems from the fact that because the query is schema-less and casts the created_date to erlang time. Using:

    ^currentTime

    When I go to insert_all here:

    ChatApp.Repo.insert_all(ChatApp.Roles.RoleMasterParameters, role_master_rows)

    It then tries to cast the erlang time to elixir and fails on the insert.

    This is what I used to fix it:

    current_time = DateTime.utc_now
    
    query = from rm in ChatApp.Roles.RoleMasters,
                join: srp in ChatApp.Servers.ServerTypeParameters,
                where: srp.parameter_role_capable_flag == "Y",
                select: %{role_master_id: rm.id, server_type_code: srp.server_type_code, parameter_namespace: srp.parameter_namespace, parameter: srp.parameter, parameter_value: srp.parameter_default_value, description: srp.description}
    
    role_master_rows = query
      |> ChatApp.Repo.all
      |> Enum.map(&( Map.merge(&1, %{user_changeable_flag: "Y", active_flag: "Y", created_date: current_time})))
    
    
    ChatApp.Repo.insert_all(ChatApp.Roles.RoleMasterParameters, role_master_rows)