OLD | NEW |
(Empty) | |
| 1 # coding: utf-8 |
| 2 |
| 3 # This file is part of the Adblock Plus web scripts, |
| 4 # Copyright (C) 2006-2015 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 import MySQLdb |
| 20 from sitescripts.utils import get_config |
| 21 |
| 22 testing = False |
| 23 |
| 24 def connect(): |
| 25 config = get_config() |
| 26 return MySQLdb.connect( |
| 27 user=config.get("filterhitstats", "dbuser"), |
| 28 passwd=config.get("filterhitstats", "dbpassword"), |
| 29 db=config.get("filterhitstats", "test_database" if testing else "database"), |
| 30 use_unicode=True, charset="utf8" |
| 31 ) |
| 32 |
| 33 def query(db, sql, *params, **kwargs): |
| 34 """ |
| 35 Executes the query given by the provided SQL and returns the results. |
| 36 If dict_result keyword argument is provided + True the results will be |
| 37 returned as a tuple of dictionaries, otherwise a tuple of tuples. |
| 38 """ |
| 39 if kwargs.pop('dict_result', False): |
| 40 cursor = db.cursor(MySQLdb.cursors.DictCursor) |
| 41 else: |
| 42 cursor = db.cursor() |
| 43 try: |
| 44 cursor.execute(sql, params) |
| 45 db.commit() |
| 46 return cursor.fetchall() |
| 47 finally: |
| 48 cursor.close() |
| 49 |
| 50 def write(db, queries): |
| 51 """ |
| 52 This writes a given iteratable object of tuples containing SQL |
| 53 strings and any required parameters to the database. All queries will |
| 54 be run as one transaction and rolled back on error. |
| 55 """ |
| 56 try: |
| 57 cursor = db.cursor() |
| 58 try: |
| 59 for query in queries: |
| 60 sql, params = query[0], query[1:] |
| 61 cursor.execute(sql, params) |
| 62 db.commit() |
| 63 finally: |
| 64 cursor.close() |
| 65 except MySQLdb.Error: |
| 66 db.rollback() |
| 67 raise |
OLD | NEW |