Anki/anki/facts.py
Damien Elmes 2f27133705 drop sqlalchemy; massive refactor
SQLAlchemy is a great tool, but it wasn't a great fit for Anki:
- We often had to drop down to raw SQL for performance reasons.
- The DB cursors and results were wrapped, which incurred a
  sizable performance hit due to introspection. Operations like fetching 50k
  records from a hot cache were taking more than twice as long to complete.
- We take advantage of sqlite-specific features, so SQL language abstraction
  is useless to us.
- The anki schema is quite small, so manually saving and loading objects is
  not a big burden.

In the process of porting to DBAPI, I've refactored the database schema:
- App configuration data that we don't need in joins or bulk updates has been
  moved into JSON objects. This simplifies serializing, and means we won't
  need DB schema changes to store extra options in the future. This change
  obsoletes the deckVars table.
- Renamed tables:
-- fieldModels -> fields
-- cardModels -> templates
-- fields -> fdata
- a number of attribute names have been shortened

Classes like Card, Fact & Model remain. They maintain a reference to the deck.
To write their state to the DB, call .flush().

Objects no longer have their modification time manually updated. Instead, the
modification time is updated when they are flushed. This also applies to the
deck.

Decks will now save on close, because various operations that were done at
deck load will be moved into deck close instead. Operations like undoing
buried card are cheap on a hot cache, but expensive on startup.
Programmatically you can call .close(save=False) to avoid a save and a
modification bump. This will be useful for generating due counts.

Because of the new saving behaviour, the save and save as options will be
removed from the GUI in the future.

The q/a cache and field cache generating has been centralized. Facts will
automatically rebuild the cache on flush; models can do so with
model.updateCache().

Media handling has also been reworked. It has moved into a MediaRegistry
object, which the deck holds. Refcounting has been dropped - it meant we had
to compare old and new value every time facts or models were changed, and
existed for the sole purpose of not showing errors on a missing media
download. Instead we just media.registerText(q+a) when it's updated. The
download function will be expanded to ask the user if they want to continue
after a certain number of files have failed to download, which should be an
adequate alternative. And we now add the file into the media DB when it's
copied to th emedia directory, not when the card is commited. This fixes
duplicates a user would get if they added the same media to a card twice
without adding the card.

The old DeckStorage object had its upgrade code split in a previous commit;
the opening and upgrading code has been merged back together, and put in a
separate storage.py file. The correct way to open a deck now is import anki; d
= anki.Deck(path).

deck.getCard() -> deck.sched.getCard()
same with answerCard
deck.getCard(id) returns a Card object now.

And the DB wrapper has had a few changes:
- sql statements are a more standard DBAPI:
 - statement() -> execute()
 - statements() -> executemany()
- called like execute(sql, 1, 2, 3) or execute(sql, a=1, b=2, c=3)
- column0 -> list
2011-04-28 09:23:53 +09:00

128 lines
3.9 KiB
Python

# -*- coding: utf-8 -*-
# Copyright: Damien Elmes <anki@ichi2.net>
# License: GNU GPL, version 3 or later; http://www.gnu.org/copyleft/gpl.html
import time
from anki.errors import AnkiError
from anki.utils import genID, stripHTMLMedia, fieldChecksum, intTime, \
addTags, deleteTags, parseTags
class Fact(object):
def __init__(self, deck, model=None, id=None):
assert not (model and id)
self.deck = deck
if id:
self.id = id
self.load()
else:
self.id = genID()
self.model = model
self.mid = model.id
self.mod = intTime()
self.tags = ""
self.cache = ""
self._fields = [""] * len(self.model.fields)
self._fmap = self.model.fieldMap()
def load(self):
(self.mid,
self.mod,
self.pos,
self.tags) = self.deck.db.first("""
select mid, mod, pos, tags from facts where id = ?""", self.id)
self._fields = self.deck.db.list("""
select value from fdata where fid = ? order by ordinal""", self.id)
self.model = self.deck.getModel(self.mid)
def flush(self):
self.mod = intTime()
# facts table
self.cache = stripHTMLMedia(u" ".join(self._fields))
self.deck.db.execute("""
insert or replace into facts values (?, ?, ?, ?, ?, ?)""",
self.id, self.mid, self.mod,
self.pos, self.tags, self.cache)
# fdata table
self.deck.db.execute("delete from fdata where fid = ?", self.id)
d = []
for (fmid, ord, conf) in self._fmap.values():
val = self._fields[ord]
d.append(dict(fid=self.id, fmid=fmid, ord=ord,
val=val))
self.deck.db.executemany("""
insert into fdata values (:fid, :fmid, :ord, :val, '')""", d)
# media and caches
self.deck.updateCache([self.id], "fact")
def cards(self):
return [self.deck.getCard(id) for id in self.deck.db.list(
"select id from cards where fid = ? order by ord", self.id)]
# Dict interface
##################################################
def keys(self):
return self._fmap.keys()
def values(self):
return self._fields
def items(self):
return [(k, self._fields[v])
for (k, v) in self._fmap.items()]
def _fieldOrd(self, key):
try:
return self._fmap[key][1]
except:
raise KeyError(key)
def __getitem__(self, key):
return self._fields[self._fieldOrd(key)]
def __setitem__(self, key, value):
self._fields[self._fieldOrd(key)] = value
def fieldsWithIds(self):
return dict(
[(k, (v[0], self[k])) for (k,v) in self._fmap.items()])
# Tags
##################################################
def addTags(self, tags):
self.tags = addTags(tags, self.tags)
def deleteTags(self, tags):
self.tags = deleteTags(tags, self.tags)
# Unique/duplicate checks
##################################################
def fieldUnique(self, name):
(fmid, ord, conf) = self._fmap[name]
if not conf['unique']:
return True
val = self[name]
csum = fieldChecksum(val)
return not self.deck.db.scalar(
"select 1 from fdata where csum = ? and fid != ? and val = ?",
csum, self.id, val)
def fieldComplete(self, name, text=None):
(fmid, ord, conf) = self._fmap[name]
if not conf['required']:
return True
return self[name]
def problems(self):
d = []
for k in self._fmap.keys():
if not self.fieldUnique(k):
d.append("unique")
elif not self.fieldComplete(k):
d.append("required")
else:
d.append(None)
return d