@@ -382,18 +382,23 @@ def drop_table(self, table: str) -> None:
382382 raise
383383
384384 @override
385- def insert (self , table : str , data : dict [str , Any ], ttl : int | None = None ) -> None :
385+ def insert (self , table : str , data : dict [str , Any ], ttl : int | None = None , if_not_exists : bool = False ) -> None :
386386 """Insert data into a table.
387387
388388 Args:
389389 table (str): The name of the table.
390390 data (dict[str, Any]): Key-value pairs representing column names and values.
391391 ttl (int | None): Time to live in seconds. If None, data persists indefinitely.
392+ if_not_exists (bool): If True, use lightweight transaction (INSERT ... IF NOT EXISTS).
393+ This prevents errors on duplicate primary keys but is slow
392394 """
393395 columns = ", " .join (data .keys ())
394396 placeholders = ", " .join (["%s" for _ in data .keys ()])
395397 query = f"INSERT INTO { table } ({ columns } ) VALUES ({ placeholders } )"
396398
399+ if if_not_exists :
400+ query += " IF NOT EXISTS"
401+
397402 if ttl is not None :
398403 query += f" USING TTL { ttl } "
399404
@@ -961,18 +966,29 @@ async def drop_table(self, table: str) -> None:
961966 raise
962967
963968 @override
964- async def insert (self , table : str , data : dict [str , Any ], ttl : int | None = None ) -> None :
969+ async def insert (
970+ self ,
971+ table : str ,
972+ data : dict [str , Any ],
973+ ttl : int | None = None ,
974+ if_not_exists : bool = False ,
975+ ) -> None :
965976 """Insert data into a table asynchronously.
966977
967978 Args:
968979 table (str): The name of the table.
969980 data (dict[str, Any]): Key-value pairs representing column names and values.
970981 ttl (int | None): Time to live in seconds. If None, data persists indefinitely.
982+ if_not_exists (bool): If True, use lightweight transaction (INSERT ... IF NOT EXISTS).
983+ This prevents errors on duplicate primary keys but is slow
971984 """
972985 columns = ", " .join (data .keys ())
973986 placeholders = ", " .join (["%s" for _ in data .keys ()])
974987 query = f"INSERT INTO { table } ({ columns } ) VALUES ({ placeholders } )"
975988
989+ if if_not_exists :
990+ query += " IF NOT EXISTS"
991+
976992 if ttl is not None :
977993 query += f" USING TTL { ttl } "
978994
0 commit comments