Removing a lot of dead code and freeing some space in the UI
[multilist] / src / libspeichern.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 """
5 This file is part of Multilist.
6
7 Multilist is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
11
12 Multilist is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Multilist.  If not, see <http://www.gnu.org/licenses/>.
19
20 Copyright (C) 2008 Christoph Würstle
21 """
22
23 import time
24 import sqlite3
25 import shelve
26 import sys
27 import string
28 import shutil
29 import os
30 import logging
31
32 try:
33         _
34 except NameError:
35         _ = lambda x: x
36
37
38 _moduleLogger = logging.getLogger(__name__)
39
40
41 class Speichern(object):
42
43         def __init__(self):
44                 home_dir = os.path.expanduser('~')
45                 filename = os.path.join(home_dir, ".multilist.dat")
46                 self.d = shelve.open(filename)
47                 self.openDB()
48
49         def close(self):
50                 try:
51                         self.d.close()
52                 except:
53                         pass
54                 try:
55                         self.cur.close()
56                 except:
57                         pass
58                 try:
59                         self.conn.close()
60                 except:
61                         pass
62                 _moduleLogger.info("Alle Daten gespeichert")
63
64         def __del__(self):
65                 self.close()
66
67         def speichereDirekt(self, schluessel, daten):
68                 self.d[schluessel] = daten
69                 _moduleLogger.info("speichereDirekt "+str(schluessel)+" "+str(daten)+" lesen: "+str(self.d[schluessel]))
70
71         def ladeDirekt(self, schluessel, default = ""):
72                 #print "ladeDirekt", schluessel, "Schluessel vorhanden", self.d.has_key(schluessel)
73                 if (self.d.has_key(schluessel) == True):
74                         data = self.d[schluessel]
75                         #print data
76                         return data
77                 else:
78                         return default
79
80         def speichereSQL(self, sql, tupel = None, commit = True, host = "self", log = True, pcdatum = None, rowid = ""):
81                 #print "speichereSQL:", sql, tupel
82                 try:
83                         programSQLError = True
84                         if (tupel == None):
85                                 self.cur.execute(sql)
86                         else:
87                                 self.cur.execute(sql, tupel)
88                         programSQLError = False
89
90                         #print int(time.time()), sql, pickle.dumps(tupel), host
91                         if (log == True):
92                                 strtupel = []
93                                 if (tupel is not None):
94                                         for t in tupel:
95                                                 strtupel.append(str(t))
96
97                                 if pcdatum == None:
98                                         pcdatum = int(time.time())
99                                 self.cur.execute("INSERT INTO logtable ( pcdatum, sql, param, host, rowid ) VALUES (?, ?, ?, ?, ?)", (pcdatum, sql, string.join(strtupel, " <<Tren-ner>> "), host, str(rowid) ))
100                         if commit:
101                                 self.conn.commit()
102                         return True
103                 except:
104                         s = str(sys.exc_info())
105                         if (s.find(" already exists") == -1):
106                         #if len(s)>0:
107                                 if (programSQLError == True):
108                                         _moduleLogger.error("speichereSQL-Exception "+str(sys.exc_info())+" "+str(sql)+" "+str(tupel))
109                                 else:
110                                         _moduleLogger.error("speichereSQL-Exception in Logging!!!! :"+str(sys.exc_info())+" "+str(sql)+" "+str(tupel))
111                         return False
112
113         def commitSQL(self):
114                 self.conn.commit()
115
116         def ladeSQL(self, sql, tupel = None):
117                 #print sql, tupel
118                 try:
119                         if (tupel == None):
120                                 self.cur.execute(sql)
121                         else:
122                                 self.cur.execute(sql, tupel)
123                         return self.cur.fetchall()
124                 except:
125                         _moduleLogger.error("ladeSQL-Exception "+str(sys.exc_info())+" "+str(sql)+" "+str(tupel))
126                         return ()
127
128         def ladeHistory(self, sql_condition, param_condition):
129                 sql = "SELECT * FROM logtable WHERE sql LIKE '%"+str(sql_condition)+"%' AND param LIKE '%"+str(param_condition)+"%'"
130                 rows = self.ladeSQL(sql)
131
132                 erg = []
133                 for row in rows:
134                         datum = time.strftime("%d.%m.%y %H:%M:%S", (time.localtime(row[1])))
135                         erg.append([row[1], datum, row[2], row[3], row[3].split(" <<Tren-ner>> ")])
136
137                 return erg
138
139         def delHistory(self, sql_condition, param_condition, exceptTheLastXSeconds = 0):
140                 pcdatum = int(time.time())-exceptTheLastXSeconds
141                 sql = "DELETE FROM logtable WHERE sql LIKE '%"+str(sql_condition)+"%' AND param LIKE '%"+str(param_condition)+"%' AND pcdatum<?"
142                 self.speichereSQL(sql, (pcdatum, ))
143
144         def delHistoryWithRowID(self, rowid, sql_condition = " ", exceptTheLastXSeconds = 0):
145                 pcdatum = int(time.time())-exceptTheLastXSeconds
146                 sql = "DELETE FROM logtable WHERE rowid = ? AND pcdatum<? AND sql LIKE '%"+str(sql_condition)+"%'"
147                 self.speichereSQL(sql, (rowid, pcdatum, ))
148
149         def openDB(self):
150                 try:
151                         self.cur.close()
152                 except:
153                         pass
154                 try:
155                         self.conn.close()
156                 except:
157                         pass
158
159                 db = self.ladeDirekt("datenbank")
160                 if db == "":
161                         home_dir = os.path.expanduser('~')
162                         db = os.path.join(home_dir, "multilist.s3db")
163
164                 datum = time.strftime("%Y-%m-%d--", (time.localtime(time.time())))+str(int(time.time()))+"--"
165                 if (os.path.exists(db))and(os.path.exists(os.path.dirname(db)+os.sep+"backup/")):
166                         try:
167                                 shutil.copyfile(db, str(os.path.dirname(db))+os.sep+"backup"+os.sep+datum+os.path.basename(db))
168                                 #_moduleLogger.debug(str(os.path.dirname(db))+os.sep+"backup"+os.sep+datum+os.path.basename(db))
169                         except:
170                                 _moduleLogger.info("Achtung Backup-Datei NICHT (!!!) angelegt!")
171                                 #print db, str(os.path.dirname(db))+os.sep+"backup"+os.sep+datum+os.path.basename(db)
172
173                 self.conn = sqlite3.connect(db)
174                 self.cur = self.conn.cursor()
175                 try:
176                         sql = "CREATE TABLE logtable (id INTEGER PRIMARY KEY AUTOINCREMENT, pcdatum INTEGER , sql TEXT, param TEXT, host TEXT, rowid TEXT)"
177                         self.cur.execute(sql)
178                         self.conn.commit()
179                 except:
180                         pass
181
182                 #Add rowid line (not in old versions included)
183                 try:
184                         sql = "ALTER TABLE logtable ADD rowid TEXT"
185                         self.cur.execute(sql)
186                         self.conn.commit()
187                 except:
188                         pass