Skip to content

Commit c940f0a

Browse files
author
Hugo Osvaldo Barrera
committed
Use sqlite3's adapters and converters
1 parent 8edf297 commit c940f0a

File tree

1 file changed

+24
-16
lines changed

1 file changed

+24
-16
lines changed

todoman/model.py

Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,16 @@
2222
LOCAL_TIMEZONE = tzlocal()
2323

2424

25+
def register_adapters_and_converters():
26+
sqlite3.register_converter(
27+
'timestamp',
28+
lambda d: datetime.fromtimestamp(float(d), LOCAL_TIMEZONE)
29+
)
30+
31+
32+
register_adapters_and_converters()
33+
34+
2535
class cached_property: # noqa
2636
'''A read-only @property that is only evaluated once. Only usable on class
2737
instances' methods.
@@ -383,7 +393,10 @@ def __init__(self, path):
383393
self.cache_path = str(path)
384394
os.makedirs(os.path.dirname(self.cache_path), exist_ok=True)
385395

386-
self._conn = sqlite3.connect(self.cache_path)
396+
self._conn = sqlite3.connect(
397+
str(self.cache_path),
398+
detect_types=sqlite3.PARSE_DECLTYPES,
399+
)
387400
self._conn.row_factory = sqlite3.Row
388401
self._conn.execute("PRAGMA foreign_keys = ON")
389402

@@ -453,13 +466,13 @@ def create_tables(self):
453466
"id" INTEGER PRIMARY KEY,
454467
"uid" TEXT,
455468
"summary" TEXT,
456-
"due" INTEGER,
457-
"start" INTEGER,
469+
"due" timestamp,
470+
"start" timestamp,
458471
"priority" INTEGER,
459-
"created_at" INTEGER,
460-
"completed_at" INTEGER,
472+
"created_at" timestamp,
473+
"completed_at" timestamp,
461474
"percent_complete" INTEGER,
462-
"dtstamp" INTEGER,
475+
"dtstamp" timestamp,
463476
"status" TEXT,
464477
"description" TEXT,
465478
"location" TEXT,
@@ -758,22 +771,17 @@ def todos(
758771
seen_paths.add(path)
759772
yield todo
760773

761-
def _dt_from_db(self, dt):
762-
if dt:
763-
return datetime.fromtimestamp(dt, LOCAL_TIMEZONE)
764-
return None
765-
766774
def _todo_from_db(self, row):
767775
todo = Todo()
768776
todo.id = row['id']
769777
todo.uid = row['uid']
770778
todo.summary = row['summary']
771-
todo.due = self._dt_from_db(row['due'])
772-
todo.start = self._dt_from_db(row['start'])
779+
todo.due = row['due']
780+
todo.start = row['start']
773781
todo.priority = row['priority']
774-
todo.created_at = self._dt_from_db(row['created_at'])
775-
todo.completed_at = self._dt_from_db(row['completed_at'])
776-
todo.dtstamp = self._dt_from_db(row['dtstamp'])
782+
todo.created_at = row['created_at']
783+
todo.completed_at = row['completed_at']
784+
todo.dtstamp = row['dtstamp']
777785
todo.percent_complete = row['percent_complete']
778786
todo.status = row['status']
779787
todo.description = row['description']

0 commit comments

Comments
 (0)