Skip to content

Commit b1a8830

Browse files
authored
fix: Table column name escape (#69)
1 parent c6198b5 commit b1a8830

5 files changed

Lines changed: 61 additions & 19 deletions

File tree

‎arbalister/adbc.py‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import adbc_driver_sqlite.dbapi as adbc_sqlite
66
import pyarrow as pa
77

8+
from . import utils as utils
9+
810

911
def write_sqlite(
1012
table: pa.Table,
@@ -57,7 +59,7 @@ def read_sqlite(cls, context: Any, path: pathlib.Path | str, table_name: str | N
5759

5860
with adbc_sqlite.connect(str(path)) as connection:
5961
with connection.cursor() as cursor:
60-
cursor.execute(f'SELECT COUNT(*) FROM "{table_name}"')
62+
cursor.execute(f"SELECT COUNT(*) FROM {utils.escape(table_name)}")
6163
num_rows = cursor.fetchone()[0] # type: ignore[index]
6264

6365
schema = connection.adbc_get_table_schema(table_name)
@@ -88,13 +90,9 @@ def to_arrow_table(self) -> pa.Table:
8890
else ""
8991
)
9092

91-
# Escape column names or default to wildcard
92-
if self._select is not None:
93-
columns = ",".join(f'"{c}"' for c in self._select)
94-
else:
95-
columns = "*"
93+
columns = ",".join(self._select) if self._select is not None else "*"
9694

9795
with adbc_sqlite.connect(self._path) as connection:
9896
with connection.cursor() as cursor:
99-
cursor.execute(f'SELECT {columns} FROM "{self._table_name}" {limit}')
97+
cursor.execute(f"SELECT {columns} FROM {utils.escape(self._table_name)} {limit}")
10098
return cursor.fetch_arrow_table()

‎arbalister/routes.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from . import arrow as abw
1515
from . import file_format as ff
1616
from . import params as params
17+
from . import utils as utils
1718

1819

1920
@dataclasses.dataclass(frozen=True, slots=True)
@@ -104,8 +105,8 @@ async def get(self, path: str) -> None:
104105
df = df.limit(count=count, offset=offset)
105106

106107
if params.start_col is not None and params.end_col is not None:
107-
col_names = df.schema().names
108-
df = df.select(*col_names[params.start_col : params.end_col])
108+
col_names = df.schema().names[params.start_col : params.end_col]
109+
df = df.select(*(utils.escape(c) for c in col_names))
109110

110111
table: pa.Table = df.to_arrow_table()
111112

@@ -158,7 +159,7 @@ async def get(self, path: str) -> None:
158159
# No dedicated exception type coming from DataFusion
159160
if str(e).startswith("DataFusion"):
160161
first_col: str = schema.names[0]
161-
batches = df.aggregate([], [dnf.count(dn.col(first_col))]).collect()
162+
batches = df.aggregate([], [dnf.count(dn.col(utils.escape(first_col)))]).collect()
162163
num_rows = batches[0].column(0)[0].as_py()
163164

164165
# Create a zero-row IPC stream with the table schema

‎arbalister/tests/test_routes.py‎

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,25 @@ def dummy_table_1(num_rows: int = 10) -> pa.Table:
5959
"""Generate a table with fake data."""
6060
data = {
6161
"lower": random.choices(string.ascii_lowercase, k=num_rows),
62-
"sequence": list(range(num_rows)),
63-
"upper": random.choices(string.ascii_uppercase, k=num_rows),
64-
"number": [random.random() for _ in range(num_rows)],
62+
"some sequence": list(range(num_rows)),
63+
"UPPER": random.choices(string.ascii_uppercase, k=num_rows),
64+
"number 💯": [random.random() for _ in range(num_rows)],
65+
}
66+
table = pa.table(data)
67+
return table
68+
69+
70+
@pytest.fixture(scope="module")
71+
def avro_table(num_rows: int = 10) -> pa.Table:
72+
"""Generate a table with fake data and Avro compatible column names.
73+
74+
Avro field names are restricted to ``[A-Za-z_][A-Za-z0-9_]*``.
75+
"""
76+
data = {
77+
"lower": random.choices(string.ascii_lowercase, k=num_rows),
78+
"some_sequence": list(range(num_rows)),
79+
"UPPER": random.choices(string.ascii_uppercase, k=num_rows),
80+
"number_": [random.random() for _ in range(num_rows)],
6581
}
6682
table = pa.table(data)
6783
return table
@@ -82,9 +98,17 @@ def dummy_table_2(num_rows: int = 13) -> pa.Table:
8298

8399

84100
@pytest.fixture(scope="module")
85-
def full_table(file_params: ff.FileFormat, dummy_table_1: pa.Table, dummy_table_2: pa.Table) -> pa.Table:
101+
def full_table(
102+
file_format: ff.FileFormat,
103+
file_params: arb.routes.FileReadOptions,
104+
dummy_table_1: pa.Table,
105+
dummy_table_2: pa.Table,
106+
avro_table: pa.Table,
107+
) -> pa.Table:
86108
"""Return the full table on which we are executed queries."""
87-
if isinstance(file_params, arb.routes.SqliteReadOptions):
109+
if file_format == ff.FileFormat.Avro:
110+
return avro_table
111+
if isinstance(file_params, arb.routes.SqliteReadOptions) and file_params.table_name:
88112
return {
89113
"dummy_table_1": dummy_table_1,
90114
"dummy_table_2": dummy_table_2,
@@ -97,6 +121,7 @@ def table_file(
97121
jp_root_dir: pathlib.Path,
98122
dummy_table_1: pa.Table,
99123
dummy_table_2: pa.Table,
124+
avro_table: pa.Table,
100125
file_format: ff.FileFormat,
101126
file_params: arb.routes.FileReadOptions,
102127
) -> pathlib.Path:
@@ -105,6 +130,8 @@ def table_file(
105130
table_path = jp_root_dir / f"test.{str(file_format).lower()}"
106131

107132
match file_format:
133+
case ff.FileFormat.Avro:
134+
write_table(avro_table, table_path)
108135
case ff.FileFormat.Csv:
109136
write_table(dummy_table_1, table_path, delimiter=getattr(file_params, "delimiter", ","))
110137
case ff.FileFormat.Sqlite:

‎arbalister/utils.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
def escape(name: str) -> str:
2+
"""Quote a SQL identifier so that it is taken verbatim.
3+
4+
Unquoted identifiers are lowercased and dots are read as qualifiers.
5+
"""
6+
escaped = name.replace('"', '""')
7+
return f'"{escaped}"'

‎data/generate.py‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import argparse
22
import pathlib
33
import random
4+
import re
45

56
import datafusion as dn
67
import datafusion.functions as dnf
@@ -33,10 +34,10 @@ def generate_table(num_rows: int) -> pa.Table:
3334

3435
gen = faker.Faker()
3536
data = {
36-
"name": [gen.name() for _ in range(num_rows)],
37-
"address": [gen.address().replace("\n", ", ") for _ in range(num_rows)],
38-
"age": [gen.random_number(digits=2) for _ in range(num_rows)],
39-
"id": [gen.uuid4() for _ in range(num_rows)],
37+
"Name": [gen.name() for _ in range(num_rows)],
38+
"Address 🏠": [gen.address().replace("\n", ", ") for _ in range(num_rows)],
39+
'"Age"': [gen.random_number(digits=2) for _ in range(num_rows)],
40+
"__id": [gen.uuid4() for _ in range(num_rows)],
4041
}
4142
return pa.table(data)
4243

@@ -150,8 +151,16 @@ def shuffle_table(table: pa.Table, seed: int | None = None) -> pa.Table:
150151
return table.select(col_order).take(row_indices)
151152

152153

154+
def avro_compatible(table: pa.Table) -> pa.Table:
155+
"""Rename the columns to comply with Avro field names ``[A-Za-z_][A-Za-z0-9_]*``."""
156+
names = [re.sub(r"[^A-Za-z0-9_]", "_", name) for name in table.column_names]
157+
return table.rename_columns([n if re.match(r"[A-Za-z_]", n) else f"_{n}" for n in names])
158+
159+
153160
def save_table(table: pa.Table, path: pathlib.Path, file_type: ff.FileFormat) -> None:
154161
"""Save a table to file with the given file type."""
162+
if file_type == ff.FileFormat.Avro:
163+
table = avro_compatible(table)
155164
path.parent.mkdir(exist_ok=True, parents=True)
156165
write_table = aa.get_table_writer(file_type)
157166
write_table(table, str(path))

0 commit comments

Comments
 (0)