Skip to content

Commit ffb5442

Browse files
committed
insert now replaces square braces in column name with underscore, closes #341
1 parent fb9d617 commit ffb5442

File tree

2 files changed

+14
-8
lines changed

2 files changed

+14
-8
lines changed

sqlite_utils/db.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2571,6 +2571,8 @@ def insert_all(
25712571
all_columns = []
25722572
first = True
25732573
num_records_processed = 0
2574+
# Fix up any records with square braces in the column names
2575+
records = fix_square_braces(records)
25742576
# We can only handle a max of 999 variables in a SQL insert, so
25752577
# we need to adjust the batch_size down if we have too many cols
25762578
records = iter(records)
@@ -2618,7 +2620,6 @@ def insert_all(
26182620
column for column in record if column not in all_columns
26192621
]
26202622

2621-
validate_column_names(all_columns)
26222623
first = False
26232624

26242625
self.insert_chunk(
@@ -2986,3 +2987,14 @@ def validate_column_names(columns):
29862987
assert (
29872988
"[" not in column and "]" not in column
29882989
), "'[' and ']' cannot be used in column names"
2990+
2991+
2992+
def fix_square_braces(records: Iterable[Dict[str, Any]]):
2993+
for record in records:
2994+
if any("[" in key or "]" in key for key in record.keys()):
2995+
yield {
2996+
key.replace("[", "_").replace("]", "_"): value
2997+
for key, value in record.items()
2998+
}
2999+
else:
3000+
yield record

tests/test_create.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,7 @@ def test_create_table_with_not_null(fresh_db):
144144
[{"name": "memoryview", "type": "BLOB"}],
145145
),
146146
({"uuid": uuid.uuid4()}, [{"name": "uuid", "type": "TEXT"}]),
147+
({"foo[bar]": 1}, [{"name": "foo_bar_", "type": "INTEGER"}]),
147148
),
148149
)
149150
def test_create_table_from_example(fresh_db, example, expected_columns):
@@ -525,13 +526,6 @@ def test_insert_row_alter_table(
525526
]
526527

527528

528-
def test_insert_row_alter_table_invalid_column_characters(fresh_db):
529-
table = fresh_db["table"]
530-
table.insert({"foo": "bar"}).last_pk
531-
with pytest.raises(AssertionError):
532-
table.insert({"foo": "baz", "new_col[abc]": 1.2}, alter=True)
533-
534-
535529
def test_add_missing_columns_case_insensitive(fresh_db):
536530
table = fresh_db["foo"]
537531
table.insert({"id": 1, "name": "Cleo"}, pk="id")

0 commit comments

Comments
 (0)