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