Skip to content
Snippets Groups Projects
Commit 65255953 authored by Anders H. Rebner's avatar Anders H. Rebner
Browse files

#40 Forbedret funksjonen insert_soi

parent a45783be
No related branches found
No related tags found
1 merge request!59#40 Lagre SOI i database
Pipeline #79478 failed
......@@ -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()
......@@ -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)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment