diff --git a/soitool/database.py b/soitool/database.py index 45d04f94db6e9c8e09ac015b4fe809aa7d398991..72c8526b6a39f1a5b66c9df6ffd81f5fa9979d93 100644 --- a/soitool/database.py +++ b/soitool/database.py @@ -344,7 +344,7 @@ class Database: def insert_soi(self, soi): """Serialize, compress and insert SOI into database-table SOI. - If one or more SOI's with the same title exists in db, (1), (2), ... + If one or more SOI's with the same title exist in db, (1), (2), ... is added to the Title-column of the SOI to insert. Parameters @@ -352,19 +352,29 @@ class Database: soi : soitool.soi.SOI The SOI-instance to insert into database. """ - title = soi.title - date = datetime.now().strftime("%Y-%m-%d") + # Serialize and compress SOI serialized_soi = serialize_soi(soi) compressed_soi = compress(serialized_soi) - # Count SOI's with equal title + # Count SOI's in database with equal title, + # including titles ending with '(x)' + title = soi.title length = len(title) - stmt = "SELECT COUNT(*) FROM SOI WHERE substr(Title,0,?)=?" - count = self.conn.execute(stmt, (length + 1, title)).fetchone()[0] - # Add '(x)' to title if SOI with equal title exists + stmt = ( + "SELECT COUNT(*) FROM SOI " + "WHERE substr(Title,0,?)=? " + "AND (length(Title)=? OR length(Title)=?)" + ) + count = self.conn.execute( + stmt, (length + 1, title, length, length + 3) + ).fetchone()[0] + + # Add '(x)' to title if one or more SOI's with equal title exist if count > 0: title += "(" + str(count + 1) + ")" + # Insert SOI to database stmt = "INSERT INTO SOI (Title, SOI, Date) VALUES(?,?,?)" + date = datetime.now().strftime("%Y-%m-%d") self.conn.execute(stmt, (title, compressed_soi, date)) self.conn.commit() diff --git a/test/test_database.py b/test/test_database.py index 848cdd620c1029b9b85c1e11e4df8493a1dbdbbd..ef717b027183f866f291ea9f09ec4feb7a5633c8 100644 --- a/test/test_database.py +++ b/test/test_database.py @@ -8,6 +8,8 @@ from datetime import datetime from soitool.database import Database from soitool.soi import SOI from soitool.coder import get_code_length_needed +from soitool.serialize_export_import_soi import serialize_soi +from soitool.compressor import compress TESTDBNAME = "testDatabase" SOITOOL_DIR = Path(__file__).parent.parent / "soitool" @@ -310,6 +312,7 @@ class DatabaseTest(unittest.TestCase): # Assert SOI was written correctly self.assertEqual(queried[0]["Title"], test_title) self.assertEqual(queried[0]["Date"], test_date) + self.assertEqual(queried[0]["SOI"], compress(serialize_soi(soi))) # Insert same SOI again and assert '(2)' is added to title self.database.insert_soi(soi)