Skip to content

Commit 2180e0f

Browse files
authored
feat: support split_with_parser (#1)
1 parent d4ffea2 commit 2180e0f

6 files changed

Lines changed: 662 additions & 17 deletions

File tree

lib/sql_parser.ex

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ defmodule SQLParser do
33
An SQL parser that uses [sqlparser](https://github.com/sqlparser-rs/sqlparser-rs.git) underneath.
44
"""
55

6-
@typep ast() :: map()
6+
@type ast() :: map()
7+
@type statement() :: binary()
78

89
@spec parse(sql :: binary(), dialect :: binary()) :: {:ok, [ast()]} | {:error, binary()}
910
def parse(sql, dialect \\ "postgres") when dialect in ["bigquery", "postgres"] do
@@ -20,4 +21,27 @@ defmodule SQLParser do
2021
|> Jason.encode!()
2122
|> SQLParser.Native.to_sql()
2223
end
24+
25+
@doc """
26+
Splits the given SQL string into a list of statements using the pg_query library.
27+
28+
## Examples
29+
30+
iex> SQLParser.split_with_parser("SELECT 1; SELECT 2;")
31+
{:ok, ["SELECT 1;", "SELECT 2;"]}
32+
"""
33+
@spec split_with_parser(sql :: binary()) ::
34+
{:ok, [statement()]} | {:error, binary()}
35+
def split_with_parser(sql) do
36+
with {:ok, statements} <- SQLParser.Native.split_with_parser(sql) do
37+
statements =
38+
Enum.map(statements, fn statement ->
39+
statement
40+
|> String.trim()
41+
|> Kernel.<>(";")
42+
end)
43+
44+
{:ok, statements}
45+
end
46+
end
2347
end

lib/sql_parser/native.ex

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,7 @@ defmodule SQLParser.Native do
1717
def parse(_sql, _dialect), do: :erlang.nif_error(:nif_not_loaded)
1818

1919
def to_sql(_ast), do: :erlang.nif_error(:nif_not_loaded)
20+
21+
@spec split_with_parser(binary()) :: {:ok, [binary()]} | {:error, binary()}
22+
def split_with_parser(_sql), do: :erlang.nif_error(:nif_not_loaded)
2023
end

0 commit comments

Comments
 (0)