OLD | NEW |
| (Empty) |
1 # coding: utf-8 | |
2 | |
3 # This file is part of the Adblock Plus web scripts, | |
4 # Copyright (C) 2006-2016 Eyeo GmbH | |
5 # | |
6 # Adblock Plus is free software: you can redistribute it and/or modify | |
7 # it under the terms of the GNU General Public License version 3 as | |
8 # published by the Free Software Foundation. | |
9 # | |
10 # Adblock Plus is distributed in the hope that it will be useful, | |
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
13 # GNU General Public License for more details. | |
14 # | |
15 # You should have received a copy of the GNU General Public License | |
16 # along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. | |
17 | |
18 import itertools | |
19 | |
20 import MySQLdb | |
21 | |
22 from sitescripts.utils import get_config | |
23 | |
24 | |
25 def connect(): | |
26 config = get_config() | |
27 return MySQLdb.connect( | |
28 user=config.get("filterhitstats", "dbuser"), | |
29 passwd=config.get("filterhitstats", "dbpassword"), | |
30 db=config.get("filterhitstats", "database"), | |
31 use_unicode=True, charset="utf8" | |
32 ) | |
33 | |
34 | |
35 def query(db, sql, *params, **kwargs): | |
36 """ | |
37 Executes the query given by the provided SQL and returns the results. | |
38 If dict_result keyword argument is provided + True the results will be | |
39 returned as a tuple of dictionaries, otherwise a tuple of tuples. | |
40 """ | |
41 if kwargs.get("dict_result"): | |
42 cursor = db.cursor(MySQLdb.cursors.DictCursor) | |
43 else: | |
44 cursor = db.cursor() | |
45 try: | |
46 cursor.execute(sql, params) | |
47 db.commit() | |
48 return cursor.fetchall() | |
49 finally: | |
50 cursor.close() | |
51 | |
52 | |
53 def write(db, queries): | |
54 """ | |
55 This writes a given iteratable object of tuples containing SQL | |
56 strings and any required parameters to the database. All queries will | |
57 be run as one transaction and rolled back on error. | |
58 """ | |
59 try: | |
60 cursor = db.cursor() | |
61 try: | |
62 for query in queries: | |
63 sql, params = query[0], query[1:] | |
64 cursor.execute(sql, params) | |
65 db.commit() | |
66 finally: | |
67 cursor.close() | |
68 except MySQLdb.Error: | |
69 db.rollback() | |
70 raise | |
OLD | NEW |