From c934649b91b81a47b7cfe95b79d73cc208c0044c Mon Sep 17 00:00:00 2001 From: SimonLab Date: Wed, 6 Mar 2019 13:09:54 +0000 Subject: [PATCH] use regex instead of String.split to match query terms, https://github.com/dwyl/alog/issues/40#issuecomment-470015373 --- config/test.exs | 4 ++-- lib/alog/connection.ex | 25 +++++++++++++++++++++++-- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/config/test.exs b/config/test.exs index cead70a..47d1f1b 100644 --- a/config/test.exs +++ b/config/test.exs @@ -2,8 +2,8 @@ use Mix.Config config :alog, Alog.Repo, username: "postgres", - password: "postgres", - database: "test_app_dev", + password: "docker", + database: "routinedb", hostname: "localhost", pool: Ecto.Adapters.SQL.Sandbox, priv: "priv/repo/test_app/" diff --git a/lib/alog/connection.ex b/lib/alog/connection.ex index 59b4209..167008f 100644 --- a/lib/alog/connection.ex +++ b/lib/alog/connection.ex @@ -68,8 +68,29 @@ defmodule Alog.Connection do query end - defp distinct_entry_id("SELECT " <> query) do - IO.iodata_to_binary(["SELECT ", "DISTINCT ON (\"entry_id\" ) ", query]) + # defp distinct_entry_id("SELECT " <> fields <> " FROM " <> table_name <> " AS " <> table_as <> " " <> rest_query) do + # + # IO.iodata_to_binary(["SELECT ", "DISTINCT ON (#{table_as}\".entry_id\" ) ", query]) + # end + + defp distinct_entry_id(query) do + query_data = get_query_data(query) + if (query_data["table_name"] == "\"schema_migrations\"") do + query + else + IO.iodata_to_binary( + [ "SELECT DISTINCT ON (#{query_data["table_as"]}.\"entry_id\" ) ", + query_data["fields"], + " FROM ", + query_data["table_name"], " AS ", query_data["table_as"], + query_data["rest_query"] + ] + ) + end + end + + defp get_query_data(query) do + Regex.named_captures(~r/(\bSELECT\b)\s(?.*)\sFROM\s(?.*)\sas\s(?.*)(?.*)/i, query) end @impl true