Skip to content

Commit

Permalink
feat: add pk information in x-electric-schema header (#235)
Browse files Browse the repository at this point in the history
Addresses #229
  • Loading branch information
kevin-dp authored Aug 1, 2024
1 parent 819f499 commit 358e0ab
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 1 deletion.
6 changes: 6 additions & 0 deletions .changeset/nasty-birds-tease.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@core/sync-service": patch
---

Add PK index of column is part of the PK in the column information that is part of the schema information returned in the x-electric-schema
HTTP header.
8 changes: 8 additions & 0 deletions packages/sync-service/lib/electric/schema.ex
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ defmodule Electric.Schema do
@type schema :: %{
:type => type_name(),
optional(:dims) => non_neg_integer(),
optional(:pk_index) => non_neg_integer(),
optional(:max_length) => String.t(),
optional(:length) => String.t(),
optional(:precision) => String.t(),
Expand Down Expand Up @@ -49,6 +50,7 @@ defmodule Electric.Schema do
defp schema(col_info) do
%{type: type(col_info)}
|> add_dims(col_info)
|> add_pk(col_info)
|> add_modifier(col_info)
end

Expand All @@ -61,6 +63,12 @@ defmodule Electric.Schema do
Map.put(schema, :dims, array_dimensions)
end

defp add_pk(schema, %{pk_position: nil}), do: schema

defp add_pk(schema, %{pk_position: idx}) do
Map.put(schema, :pk_index, idx)
end

defp add_modifier(%{type: type} = schema, %{type_mod: type_mod})
when type_mod > 0 and type in @variable_length_character_types do
Map.put(schema, :max_length, type_mod - 4)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ defmodule Electric.Plug.ServeShapePlugTest do
|> ServeShapePlug.call([])

assert Plug.Conn.get_resp_header(conn, "x-electric-schema") == [
~s|{"id":{"type":"int8"}}|
~s|{"id":{"type":"int8","pk_index":0}}|
]
end

Expand Down
24 changes: 24 additions & 0 deletions packages/sync-service/test/electric/schema_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -495,5 +495,29 @@ defmodule Electric.SchemaTest do
assert schema == unquote(Macro.escape(expected_schema))
end
end

test "returns the correct schema for a table with a composite primary key", %{db_conn: conn} do
Postgrex.query!(
conn,
"""
CREATE TABLE items (
i INTEGER,
name VARCHAR,
value BOOLEAN,
PRIMARY KEY (i, value)
)
""",
[]
)

{:ok, column_info} = DirectInspector.load_column_info({"public", "items"}, conn)

%{"i" => i_schema, "name" => name_schema, "value" => value_schema} =
Schema.from_column_info(column_info)

assert i_schema == %{type: "int4", pk_index: 0}
assert name_schema == %{type: "varchar"}
assert value_schema == %{type: "bool", pk_index: 1}
end
end
end

0 comments on commit 358e0ab

Please sign in to comment.