deck.s -> deck.db

This commit is contained in:
Damien Elmes 2011-02-19 16:29:18 +09:00
parent 7b52a4e519
commit d02a26309f
9 changed files with 48 additions and 48 deletions

View file

@ -52,7 +52,7 @@ class ActiveTagsChooser(QDialog):
("models", "select tags from models", "contents.png"), ("models", "select tags from models", "contents.png"),
("cms", "select name from cardModels", "Anki_Card.png")): ("cms", "select name from cardModels", "Anki_Card.png")):
d = {} d = {}
tagss = self.deck.s.column0(sql) tagss = self.deck.db.column0(sql)
for tags in tagss: for tags in tagss:
for tag in parseTags(tags): for tag in parseTags(tags):
d[tag] = 1 d[tag] = 1

View file

@ -218,7 +218,7 @@ question or answer on all cards."""), parent=self)
self.modelChooser.deinit() self.modelChooser.deinit()
self.editor.close() self.editor.close()
ui.dialogs.close("AddCards") ui.dialogs.close("AddCards")
self.parent.deck.s.flush() self.parent.deck.db.flush()
self.parent.deck.rebuildCSS() self.parent.deck.rebuildCSS()
self.parent.reset() self.parent.reset()
saveGeom(self, "add") saveGeom(self, "add")

View file

@ -165,7 +165,7 @@ where cards.factId = facts.id """
query += sort query += sort
else: else:
# field value # field value
ret = self.deck.s.all( ret = self.deck.db.all(
"select id, numeric from fieldModels where name = :name", "select id, numeric from fieldModels where name = :name",
name=self.sortKey[1]) name=self.sortKey[1])
fields = ",".join([str(x[0]) for x in ret]) fields = ",".join([str(x[0]) for x in ret])
@ -182,14 +182,14 @@ where cards.factId = facts.id """
"and fields.factId = cards.factId" + ads + "and fields.factId = cards.factId" + ads +
" order by cards.ordinal, %s") % (fields, order) " order by cards.ordinal, %s") % (fields, order)
# run the query # run the query
self.cards = self.deck.s.all(query) self.cards = self.deck.db.all(query)
if self.deck.getInt('reverseOrder'): if self.deck.getInt('reverseOrder'):
self.cards.reverse() self.cards.reverse()
self.reset() self.reset()
def updateCard(self, index): def updateCard(self, index):
try: try:
self.cards[index.row()] = self.deck.s.first(""" self.cards[index.row()] = self.deck.db.first("""
select id, question, answer, combinedDue, reps, factId, created, modified, select id, question, answer, combinedDue, reps, factId, created, modified,
interval, factor, noCount, type, (select tags from facts where interval, factor, noCount, type, (select tags from facts where
facts.id = cards.factId), (select created from facts where facts.id = cards.factId), (select created from facts where
@ -212,7 +212,7 @@ facts.id = cards.factId), firstAnswered from cards where id = :id""",
def getCard(self, index): def getCard(self, index):
try: try:
return self.deck.s.query(Card).get(self.getCardID(index)) return self.deck.db.query(Card).get(self.getCardID(index))
except IndexError: except IndexError:
return None return None
@ -368,7 +368,7 @@ class EditDeck(QMainWindow):
self.config['iconSize'])) self.config['iconSize']))
self.dialog.toolBar.toggleViewAction().setText(_("Toggle Toolbar")) self.dialog.toolBar.toggleViewAction().setText(_("Toggle Toolbar"))
# flush all changes before we load # flush all changes before we load
self.deck.s.flush() self.deck.db.flush()
self.model = DeckModel(self.parent, self.parent.deck) self.model = DeckModel(self.parent, self.parent.deck)
self.dialog.tableView.setSortingEnabled(False) self.dialog.tableView.setSortingEnabled(False)
self.dialog.tableView.setShowGrid(False) self.dialog.tableView.setShowGrid(False)
@ -457,7 +457,7 @@ class EditDeck(QMainWindow):
("models", "select tags from models", "contents.png"), ("models", "select tags from models", "contents.png"),
("cms", "select name from cardModels", "Anki_Card.png")): ("cms", "select name from cardModels", "Anki_Card.png")):
d = {} d = {}
tagss = self.deck.s.column0(sql) tagss = self.deck.db.column0(sql)
for tags in tagss: for tags in tagss:
for tag in parseTags(tags): for tag in parseTags(tags):
d[tag] = 1 d[tag] = 1
@ -553,20 +553,20 @@ class EditDeck(QMainWindow):
"question", "answer", "created", "modified", "due", "interval", "question", "answer", "created", "modified", "due", "interval",
"reps", "factor", "noCount", "firstAnswered"): "reps", "factor", "noCount", "firstAnswered"):
return return
old = self.deck.s.scalar("select sql from sqlite_master where name = :k", old = self.deck.db.scalar("select sql from sqlite_master where name = :k",
k="ix_cards_sort") k="ix_cards_sort")
if old and key in old: if old and key in old:
return return
self.parent.setProgressParent(self) self.parent.setProgressParent(self)
self.deck.startProgress(2) self.deck.startProgress(2)
self.deck.updateProgress(_("Building Index...")) self.deck.updateProgress(_("Building Index..."))
self.deck.s.statement("drop index if exists ix_cards_sort") self.deck.db.statement("drop index if exists ix_cards_sort")
self.deck.updateProgress() self.deck.updateProgress()
if key in ("question", "answer"): if key in ("question", "answer"):
key = key + " collate nocase" key = key + " collate nocase"
self.deck.s.statement( self.deck.db.statement(
"create index ix_cards_sort on cards (%s)" % key) "create index ix_cards_sort on cards (%s)" % key)
self.deck.s.statement("analyze") self.deck.db.statement("analyze")
self.deck.finishProgress() self.deck.finishProgress()
self.parent.setProgressParent(None) self.parent.setProgressParent(None)
@ -788,14 +788,14 @@ class EditDeck(QMainWindow):
self.dialog.tableView.selectionModel().selectedRows()] self.dialog.tableView.selectionModel().selectedRows()]
def selectedFacts(self): def selectedFacts(self):
return self.deck.s.column0(""" return self.deck.db.column0("""
select distinct factId from cards select distinct factId from cards
where id in (%s)""" % ",".join([ where id in (%s)""" % ",".join([
str(self.model.cards[idx.row()][0]) for idx in str(self.model.cards[idx.row()][0]) for idx in
self.dialog.tableView.selectionModel().selectedRows()])) self.dialog.tableView.selectionModel().selectedRows()]))
def selectedFactsAsCards(self): def selectedFactsAsCards(self):
return self.deck.s.column0( return self.deck.db.column0(
"select id from cards where factId in (%s)" % "select id from cards where factId in (%s)" %
",".join([str(s) for s in self.selectedFacts()])) ",".join([str(s) for s in self.selectedFacts()]))
@ -946,7 +946,7 @@ where id in (%s)""" % ",".join([
sf = self.selectedFacts() sf = self.selectedFacts()
if not sf: if not sf:
return return
mods = self.deck.s.column0(""" mods = self.deck.db.column0("""
select distinct modelId from facts select distinct modelId from facts
where id in %s""" % ids2str(sf)) where id in %s""" % ids2str(sf))
if not len(mods) == 1: if not len(mods) == 1:
@ -955,7 +955,7 @@ where id in %s""" % ids2str(sf))
parent=self) parent=self)
return return
# get cards to enable # get cards to enable
cms = [x.id for x in self.deck.s.query(Fact).get(sf[0]).\ cms = [x.id for x in self.deck.db.query(Fact).get(sf[0]).\
model.cardModels] model.cardModels]
d = AddCardChooser(self, cms) d = AddCardChooser(self, cms)
if not d.exec_(): if not d.exec_():
@ -965,7 +965,7 @@ where id in %s""" % ids2str(sf))
self.parent.setProgressParent(self) self.parent.setProgressParent(self)
self.deck.startProgress() self.deck.startProgress()
self.deck.setUndoStart(n) self.deck.setUndoStart(n)
facts = self.deck.s.query(Fact).filter( facts = self.deck.db.query(Fact).filter(
text("id in %s" % ids2str(sf))).order_by(Fact.created).all() text("id in %s" % ids2str(sf))).order_by(Fact.created).all()
self.deck.updateProgress(_("Generating Cards...")) self.deck.updateProgress(_("Generating Cards..."))
ids = [] ids = []
@ -986,7 +986,7 @@ where id in %s""" % ids2str(sf))
def onChangeModel(self): def onChangeModel(self):
sf = self.selectedFacts() sf = self.selectedFacts()
mods = self.deck.s.column0(""" mods = self.deck.db.column0("""
select distinct modelId from facts select distinct modelId from facts
where id in %s""" % ids2str(sf)) where id in %s""" % ids2str(sf))
if not len(mods) == 1: if not len(mods) == 1:
@ -1088,7 +1088,7 @@ where id in %s""" % ids2str(sf))
sf = self.selectedFacts() sf = self.selectedFacts()
if not sf: if not sf:
return return
mods = self.deck.s.column0(""" mods = self.deck.db.column0("""
select distinct modelId from facts select distinct modelId from facts
where id in %s""" % ids2str(sf)) where id in %s""" % ids2str(sf))
if not len(mods) == 1: if not len(mods) == 1:
@ -1151,12 +1151,12 @@ where id in %s""" % ids2str(sf))
restoreGeom(win, "findDupes") restoreGeom(win, "findDupes")
fields = sorted(self.currentCard.fact.model.fieldModels, key=attrgetter("name")) fields = sorted(self.currentCard.fact.model.fieldModels, key=attrgetter("name"))
# per-model data # per-model data
data = self.deck.s.all(""" data = self.deck.db.all("""
select fm.id, m.name || '>' || fm.name from fieldmodels fm, models m select fm.id, m.name || '>' || fm.name from fieldmodels fm, models m
where fm.modelId = m.id""") where fm.modelId = m.id""")
data.sort(key=itemgetter(1)) data.sort(key=itemgetter(1))
# all-model data # all-model data
data2 = self.deck.s.all(""" data2 = self.deck.db.all("""
select fm.id, fm.name from fieldmodels fm""") select fm.id, fm.name from fieldmodels fm""")
byName = {} byName = {}
for d in data2: for d in data2:
@ -1291,7 +1291,7 @@ class AddCardChooser(QDialog):
restoreGeom(self, "addCardModels") restoreGeom(self, "addCardModels")
def displayCards(self): def displayCards(self):
self.cms = self.parent.deck.s.all(""" self.cms = self.parent.deck.db.all("""
select id, name, active from cardModels select id, name, active from cardModels
where id in %s where id in %s
order by ordinal""" % ids2str(self.cms)) order by ordinal""" % ids2str(self.cms))

View file

@ -36,10 +36,10 @@ class CardLayout(QDialog):
else: else:
self.model = factOrModel self.model = factOrModel
# see if there's an available fact # see if there's an available fact
id = self.deck.s.scalar( id = self.deck.db.scalar(
"select id from facts where modelId = :id", id=self.model.id) "select id from facts where modelId = :id", id=self.model.id)
if id: if id:
self.fact = self.deck.s.query(Fact).get(id) self.fact = self.deck.db.query(Fact).get(id)
else: else:
# generate a dummy one # generate a dummy one
self.fact = self.deck.newFact(self.model) self.fact = self.deck.newFact(self.model)
@ -51,8 +51,8 @@ class CardLayout(QDialog):
self.plastiqueStyle = QStyleFactory.create("plastique") self.plastiqueStyle = QStyleFactory.create("plastique")
if self.card: if self.card:
# limited to an existing template # limited to an existing template
self.cards = [self.deck.s.query(Card).get(id) for id in self.cards = [self.deck.db.query(Card).get(id) for id in
self.deck.s.column0( self.deck.db.column0(
"select id from cards where factId = :fid " "select id from cards where factId = :fid "
"order by ordinal", fid=self.fact.id)] "order by ordinal", fid=self.fact.id)]
type = 0 type = 0
@ -210,7 +210,7 @@ class CardLayout(QDialog):
self.form.allowEmptyAnswer.setChecked(card.allowEmptyAnswer) self.form.allowEmptyAnswer.setChecked(card.allowEmptyAnswer)
self.form.alignment.setCurrentIndex(card.questionAlign) self.form.alignment.setCurrentIndex(card.questionAlign)
self.form.typeAnswer.clear() self.form.typeAnswer.clear()
self.typeFieldNames = self.deck.s.column0(""" self.typeFieldNames = self.deck.db.column0("""
select fieldModels.name as n from fieldModels, cardModels select fieldModels.name as n from fieldModels, cardModels
where cardModels.modelId = fieldModels.modelId where cardModels.modelId = fieldModels.modelId
and cardModels.id = :id and cardModels.id = :id
@ -477,7 +477,7 @@ order by n""", id=card.id)
f.name = _("Field %d") % (len(self.model.fieldModels) + 1) f.name = _("Field %d") % (len(self.model.fieldModels) + 1)
self.deck.addFieldModel(self.model, f) self.deck.addFieldModel(self.model, f)
try: try:
self.deck.s.refresh(self.fact) self.deck.db.refresh(self.fact)
except: except:
# not yet added # not yet added
self.updateFact() self.updateFact()
@ -488,7 +488,7 @@ order by n""", id=card.id)
def updateFact(self): def updateFact(self):
oldFact = self.fact oldFact = self.fact
model = self.deck.s.query(Model).get(oldFact.model.id) model = self.deck.db.query(Model).get(oldFact.model.id)
fact = self.deck.newFact(model) fact = self.deck.newFact(model)
for field in fact.fields: for field in fact.fields:
try: try:

View file

@ -88,7 +88,7 @@ class FactEditor(object):
def refresh(self): def refresh(self):
if self.fact: if self.fact:
try: try:
self.deck.s.refresh(self.fact) self.deck.db.refresh(self.fact)
except InvalidRequestError: except InvalidRequestError:
# not attached to session yet, add cards dialog will handle # not attached to session yet, add cards dialog will handle
return return
@ -576,7 +576,7 @@ class FactEditor(object):
"where fieldModelId = :fmid and value = :val and id != :id " "where fieldModelId = :fmid and value = :val and id != :id "
"and chksum = :chk") "and chksum = :chk")
val = self.textForField(field) val = self.textForField(field)
return not self.deck.s.scalar( return not self.deck.db.scalar(
req, val=val, fmid=field.fieldModel.id, req, val=val, fmid=field.fieldModel.id,
id=field.id, chk=fieldChecksum(val)) id=field.id, chk=fieldChecksum(val))
@ -586,7 +586,7 @@ class FactEditor(object):
old = self.fact.tags old = self.fact.tags
self.fact.tags = canonifyTags(unicode(self.tags.text())) self.fact.tags = canonifyTags(unicode(self.tags.text()))
if old != self.fact.tags: if old != self.fact.tags:
self.deck.s.flush() self.deck.db.flush()
self.deck.updateFactTags([self.fact.id]) self.deck.updateFactTags([self.fact.id])
self.fact.setModified(textChanged=True, deck=self.deck) self.fact.setModified(textChanged=True, deck=self.deck)
self.deck.flushMod() self.deck.flushMod()

View file

@ -224,7 +224,7 @@ you can enter it here. Use \\t to represent tab."""),
self.dialog.status.setText(txt) self.dialog.status.setText(txt)
self.file = None self.file = None
self.maybePreview() self.maybePreview()
self.parent.deck.s.flush() self.parent.deck.db.flush()
self.parent.reset() self.parent.reset()
self.modelChooser.deinit() self.modelChooser.deinit()

View file

@ -392,7 +392,7 @@ Please do not file a bug report with Anki.<br>""")
self.disableCardMenuItems() self.disableCardMenuItems()
elif state == "deckFinished": elif state == "deckFinished":
self.currentCard = None self.currentCard = None
self.deck.s.flush() self.deck.db.flush()
self.hideButtons() self.hideButtons()
self.disableCardMenuItems() self.disableCardMenuItems()
self.switchToCongratsScreen() self.switchToCongratsScreen()
@ -417,7 +417,7 @@ Please do not file a bug report with Anki.<br>""")
if self.lastState == "editCurrentFact": if self.lastState == "editCurrentFact":
return self.moveToState("saveEdit") return self.moveToState("saveEdit")
self.mainWin.actionRepeatAudio.setEnabled(False) self.mainWin.actionRepeatAudio.setEnabled(False)
self.deck.s.flush() self.deck.db.flush()
self.showEditor() self.showEditor()
elif state == "saveEdit": elif state == "saveEdit":
self.mainWin.actionRepeatAudio.setEnabled(True) self.mainWin.actionRepeatAudio.setEnabled(True)
@ -491,10 +491,10 @@ Please do not file a bug report with Anki.<br>""")
if self.state != "showAnswer": if self.state != "showAnswer":
return return
# force refresh of card then remove from session as we update in pure sql # force refresh of card then remove from session as we update in pure sql
self.deck.s.refresh(self.currentCard) self.deck.db.refresh(self.currentCard)
self.deck.s.refresh(self.currentCard.fact) self.deck.db.refresh(self.currentCard.fact)
self.deck.s.refresh(self.currentCard.cardModel) self.deck.db.refresh(self.currentCard.cardModel)
self.deck.s.expunge(self.currentCard) self.deck.db.expunge(self.currentCard)
# answer # answer
self.deck.answerCard(self.currentCard, quality) self.deck.answerCard(self.currentCard, quality)
self.lastQuality = quality self.lastQuality = quality
@ -514,7 +514,7 @@ Please do not file a bug report with Anki.<br>""")
<b>%s</b>... is a <a href="http://ichi2.net/anki/wiki/Leeches">leech</a>.""") <b>%s</b>... is a <a href="http://ichi2.net/anki/wiki/Leeches">leech</a>.""")
% stripHTML(stripSounds(self.currentCard.question)).\ % stripHTML(stripSounds(self.currentCard.question)).\
replace("\n", " ")[0:30]) replace("\n", " ")[0:30])
if isLeech and self.deck.s.scalar( if isLeech and self.deck.db.scalar(
"select 1 from cards where id = :id and type < 0", id=cardId): "select 1 from cards where id = :id and type < 0", id=cardId):
txt += _(" It has been suspended.") txt += _(" It has been suspended.")
self.setNotice(txt) self.setNotice(txt)
@ -997,7 +997,7 @@ Debug info:\n%s""") % traceback.format_exc(), help="DeckErrors")
self.onNew(path=path) self.onNew(path=path)
# ensure all changes come to us # ensure all changes come to us
self.deck.modified = 0 self.deck.modified = 0
self.deck.s.commit() self.deck.db.commit()
self.deck.syncName = u"something" self.deck.syncName = u"something"
self.deck.lastLoaded = self.deck.modified self.deck.lastLoaded = self.deck.modified
if self.config['syncUsername'] and self.config['syncPassword']: if self.config['syncUsername'] and self.config['syncPassword']:
@ -1667,14 +1667,14 @@ not be touched.""") %
# counts & time for today # counts & time for today
todayStart = self.deck.failedCutoff - 86400 todayStart = self.deck.failedCutoff - 86400
sql = "select count(), sum(userTime) from revlog" sql = "select count(), sum(userTime) from revlog"
(reps, time_) = self.deck.s.first( (reps, time_) = self.deck.db.first(
sql + " where time > :start", start=todayStart) sql + " where time > :start", start=todayStart)
h['timeToday'] = sessionColour % ( h['timeToday'] = sessionColour % (
anki.utils.fmtTimeSpan(time_ or 0, short=True, point=1)) anki.utils.fmtTimeSpan(time_ or 0, short=True, point=1))
h['repsToday'] = sessionColour % reps h['repsToday'] = sessionColour % reps
# and yesterday # and yesterday
yestStart = todayStart - 86400 yestStart = todayStart - 86400
(reps, time_) = self.deck.s.first( (reps, time_) = self.deck.db.first(
sql + " where time > :start and time <= :end", sql + " where time > :start and time <= :end",
start=yestStart, end=todayStart) start=yestStart, end=todayStart)
h['timeTodayChg'] = str( h['timeTodayChg'] = str(
@ -1684,10 +1684,10 @@ not be touched.""") %
limit = self.deck.sessionTimeLimit limit = self.deck.sessionTimeLimit
start = self.deck.sessionStartTime or time.time() - limit start = self.deck.sessionStartTime or time.time() - limit
start2 = self.deck.lastSessionStart or start - limit start2 = self.deck.lastSessionStart or start - limit
last10 = self.deck.s.scalar( last10 = self.deck.db.scalar(
"select count(*) from revlog where time >= :t", "select count(*) from revlog where time >= :t",
t=start) t=start)
last20 = self.deck.s.scalar( last20 = self.deck.db.scalar(
"select count(*) from revlog where " "select count(*) from revlog where "
"time >= :t and time < :t2", "time >= :t and time < :t2",
t=start2, t2=start) t=start2, t2=start)
@ -2198,7 +2198,7 @@ it to your friends.
if self.deck and not self.deck.syncName: if self.deck and not self.deck.syncName:
if interactive: if interactive:
if (not self.config['mediaLocation'] if (not self.config['mediaLocation']
and self.deck.s.scalar("select 1 from media limit 1")): and self.deck.db.scalar("select 1 from media limit 1")):
ui.utils.showInfo(_("""\ ui.utils.showInfo(_("""\
Syncing sounds and images requires a free file synchronization service like \ Syncing sounds and images requires a free file synchronization service like \
DropBox. Click help to learn more, and OK to continue syncing."""), DropBox. Click help to learn more, and OK to continue syncing."""),

View file

@ -71,7 +71,7 @@ class ModelProperties(QDialog):
if txt[0]: if txt[0]:
self.currentCard.name = txt[0] self.currentCard.name = txt[0]
self.needRebuild = True self.needRebuild = True
self.deck.updateCardTags(self.deck.s.column0( self.deck.updateCardTags(self.deck.db.column0(
"select id from cards where cardModelId = :id", "select id from cards where cardModelId = :id",
id=self.currentCard.id)) id=self.currentCard.id))
self.updateCards() self.updateCards()

View file

@ -263,7 +263,7 @@ sync was aborted. Please report this error.""")
# server to save, then save local # server to save, then save local
client.server.finish() client.server.finish()
self.deck.lastLoaded = self.deck.modified self.deck.lastLoaded = self.deck.modified
self.deck.s.commit() self.deck.db.commit()
self.setStatus(_("Sync complete.")) self.setStatus(_("Sync complete."))
else: else:
changes = False changes = False