Bump
[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 openDB(self):
50                 try:
51                         self.cur.close()
52                 except:
53                         pass
54                 try:
55                         self.conn.close()
56                 except:
57                         pass
58
59                 db = self.ladeDirekt("datenbank")
60                 if db == "":
61                         home_dir = os.path.expanduser('~')
62                         db = os.path.join(home_dir, "multilist.s3db")
63
64                 datum = time.strftime("%Y-%m-%d--", (time.localtime(time.time())))+str(int(time.time()))+"--"
65                 if os.path.exists(db) and os.path.exists(os.path.dirname(db)+os.sep+"backup"):
66                         try:
67                                 shutil.copyfile(db, str(os.path.dirname(db))+os.sep+"backup"+os.sep+datum+os.path.basename(db))
68                         except:
69                                 _moduleLogger.info("Achtung Backup-Datei NICHT (!!!) angelegt!")
70
71                 self.conn = sqlite3.connect(db)
72                 self.cur = self.conn.cursor()
73                 try:
74                         sql = "CREATE TABLE logtable (id INTEGER PRIMARY KEY AUTOINCREMENT, pcdatum INTEGER , sql TEXT, param TEXT, host TEXT, rowid TEXT)"
75                         self.cur.execute(sql)
76                         self.conn.commit()
77                 except:
78                         pass
79
80                 #Add rowid line (not in old versions included)
81                 try:
82                         sql = "ALTER TABLE logtable ADD rowid TEXT"
83                         self.cur.execute(sql)
84                         self.conn.commit()
85                 except:
86                         pass
87
88         def close(self):
89                 try:
90                         self.d.close()
91                 except:
92                         pass
93                 try:
94                         self.cur.close()
95                 except:
96                         pass
97                 try:
98                         self.conn.close()
99                 except:
100                         pass
101                 _moduleLogger.info("Alle Daten gespeichert")
102
103         def __del__(self):
104                 self.close()
105
106         def speichereDirekt(self, schluessel, daten):
107                 self.d[schluessel] = daten
108                 _moduleLogger.info("speichereDirekt "+str(schluessel)+" "+str(daten)+" lesen: "+str(self.d[schluessel]))
109
110         def ladeDirekt(self, schluessel, default = ""):
111                 if self.d.has_key(schluessel):
112                         data = self.d[schluessel]
113                         return data
114                 else:
115                         return default
116
117         def speichereSQL(self, sql, tupel = None, commit = True, host = "self", log = True, pcdatum = None, rowid = ""):
118                 try:
119                         programSQLError = True
120                         if tupel is None:
121                                 self.cur.execute(sql)
122                         else:
123                                 self.cur.execute(sql, tupel)
124                         programSQLError = False
125
126                         if log:
127                                 strtupel = []
128                                 if tupel is not None:
129                                         for t in tupel:
130                                                 strtupel.append(str(t))
131
132                                 if pcdatum is None:
133                                         pcdatum = int(time.time())
134                                 self.cur.execute("INSERT INTO logtable ( pcdatum, sql, param, host, rowid ) VALUES (?, ?, ?, ?, ?)", (pcdatum, sql, string.join(strtupel, " <<Tren-ner>> "), host, str(rowid) ))
135                         if commit:
136                                 self.conn.commit()
137                         return True
138                 except:
139                         s = str(sys.exc_info())
140                         if s.find(" already exists") == -1:
141                                 if programSQLError:
142                                         _moduleLogger.error("speichereSQL-Exception "+str(sys.exc_info())+" "+str(sql)+" "+str(tupel))
143                                 else:
144                                         _moduleLogger.error("speichereSQL-Exception in Logging!!!! :"+str(sys.exc_info())+" "+str(sql)+" "+str(tupel))
145                         return False
146
147         def commitSQL(self):
148                 self.conn.commit()
149
150         def ladeSQL(self, sql, tupel = None):
151                 try:
152                         if tupel is None:
153                                 self.cur.execute(sql)
154                         else:
155                                 self.cur.execute(sql, tupel)
156                         return self.cur.fetchall()
157                 except:
158                         _moduleLogger.error("ladeSQL-Exception "+str(sys.exc_info())+" "+str(sql)+" "+str(tupel))
159                         return ()
160
161         def ladeHistory(self, sql_condition, param_condition):
162                 sql = "SELECT * FROM logtable WHERE sql LIKE '%"+str(sql_condition)+"%' AND param LIKE '%"+str(param_condition)+"%'"
163                 rows = self.ladeSQL(sql)
164
165                 erg = []
166                 for row in rows:
167                         datum = time.strftime("%d.%m.%y %H:%M:%S", (time.localtime(row[1])))
168                         erg.append([row[1], datum, row[2], row[3], row[3].split(" <<Tren-ner>> ")])
169
170                 return erg
171
172         def delHistory(self, sql_condition, param_condition, exceptTheLastXSeconds = 0):
173                 pcdatum = int(time.time())-exceptTheLastXSeconds
174                 sql = "DELETE FROM logtable WHERE sql LIKE '%"+str(sql_condition)+"%' AND param LIKE '%"+str(param_condition)+"%' AND pcdatum<?"
175                 self.speichereSQL(sql, (pcdatum, ))
176
177         def delHistoryWithRowID(self, rowid, sql_condition = " ", exceptTheLastXSeconds = 0):
178                 pcdatum = int(time.time())-exceptTheLastXSeconds
179                 sql = "DELETE FROM logtable WHERE rowid = ? AND pcdatum<? AND sql LIKE '%"+str(sql_condition)+"%'"
180                 self.speichereSQL(sql, (rowid, pcdatum, ))