Package horizons :: Package util :: Module dbreader
[hide private]
[frames] | no frames]

Source Code for Module horizons.util.dbreader

 1  # ################################################### 
 2  # Copyright (C) 2008-2017 The Unknown Horizons Team 
 3  # team@unknown-horizons.org 
 4  # This file is part of Unknown Horizons. 
 5  # 
 6  # Unknown Horizons is free software; you can redistribute it and/or modify 
 7  # it under the terms of the GNU General Public License as published by 
 8  # the Free Software Foundation; either version 2 of the License, or 
 9  # (at your option) any later version. 
10  # 
11  # This program is distributed in the hope that it will be useful, 
12  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
13  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
14  # GNU General Public License for more details. 
15  # 
16  # You should have received a copy of the GNU General Public License 
17  # along with this program; if not, write to the 
18  # Free Software Foundation, Inc., 
19  # 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA 
20  # ################################################### 
21   
22  import re 
23  import sqlite3 
24   
25  from horizons.util.python import decorators 
26 27 28 -class DbReader:
29 """Class that handles connections to sqlite databases 30 @param file: str containing the database file."""
31 - def __init__(self, dbfile):
32 self.db_path = dbfile 33 self.connection = sqlite3.connect(dbfile) 34 self.connection.isolation_level = None 35 36 def regexp(expr, item): 37 r = re.compile(expr) 38 return r.match(item) is not None
39 self.connection.create_function("regexp", 2, regexp) 40 self.cur = self.connection.cursor()
41
42 - def __call__(self, command, *args):
43 """Executes a sql command. 44 @param command: str containing the raw sql command, with ? as 45 placeholders for values (eg. SELECT ? FROM ?). 46 command must not end with ';', 47 it's added automatically here. 48 @param args: tuple containing the values to add into the command. 49 """ 50 assert not command.endswith(";") 51 command = '{};'.format(command) 52 self.cur.execute(command, args) 53 return self.cur.fetchall()
54 55 @decorators.cachedmethod
56 - def cached_query(self, command, *args):
57 """Executes a sql command and saves its result in a dict. 58 @params, return: same as in __call__""" 59 return self(command, *args)
60
61 - def execute_many(self, command, parameters):
62 """Executes a sql command for each sequence or mapping 63 found in parameters. 64 @param command: same as in __call__ 65 @param parameters: sequence or iterator""" 66 return self.cur.executemany(command, parameters)
67
68 - def execute_script(self, script):
69 """Executes a multiline script. 70 @param script: multiline str containing an sql script.""" 71 return self.cur.executescript(script)
72
73 - def close(self):
74 """Closes the db""" 75 self.connection.close()
76