From eb9f28f42f07c216aad9073c04f20f97f03fe86b Mon Sep 17 00:00:00 2001 From: Alex Bocharov Date: Thu, 23 Jan 2025 15:01:36 -0600 Subject: [PATCH] Fix chdb dbapi to properly escape slashes during inserts. --- chdb/dbapi/converters.py | 1 + tests/test_dbapi.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/chdb/dbapi/converters.py b/chdb/dbapi/converters.py index f5e7e7cb341..18ff6ec0b5f 100644 --- a/chdb/dbapi/converters.py +++ b/chdb/dbapi/converters.py @@ -59,6 +59,7 @@ def escape_float(value, mapping=None): _escape_table = [chr(x) for x in range(128)] _escape_table[ord("'")] = u"''" +_escape_table[ord("\\")] = "\\\\" def _escape_unicode(value, mapping=None): diff --git a/tests/test_dbapi.py b/tests/test_dbapi.py index eb16f6c7cec..2a737d3fa58 100644 --- a/tests/test_dbapi.py +++ b/tests/test_dbapi.py @@ -90,6 +90,35 @@ def test_select_chdb_version(self): self.assertEqual(ver, ".".join(ver_tuple)) self.assertRegex(ver, expected_version_pattern) + def test_insert_escape_slash(self): + # make a tmp dir context + with tempfile.TemporaryDirectory() as tmpdirname: + conn = dbapi.connect(tmpdirname) + print(conn) + cur = conn.cursor() + # cur.execute("CREATE DATABASE IF NOT EXISTS test_db ENGINE = Atomic") + # cur.execute("USE test_db") + cur.execute( + """ + CREATE TABLE tmp ( + s String + ) ENGINE = Log""" + ) + + # Insert single value + s = "hello\\'world" + print("Inserting string: ", s) + cur.execute("INSERT INTO tmp VALUES (%s)", (s)) + + # Test fetchone + cur.execute("SELECT s FROM tmp") + row1 = cur.fetchone() + self.assertEqual(row1[0], s) + + # Clean up + cur.close() + conn.close() + if __name__ == "__main__": unittest.main()