| Index: sitescripts/filterhits/db.py |
| diff --git a/sitescripts/filterhits/db.py b/sitescripts/filterhits/db.py |
| new file mode 100644 |
| index 0000000000000000000000000000000000000000..c692d642a4c4102898d971193ae72716a33e3344 |
| --- /dev/null |
| +++ b/sitescripts/filterhits/db.py |
| @@ -0,0 +1,69 @@ |
| +# coding: utf-8 |
| + |
| +# This file is part of the Adblock Plus web scripts, |
| +# Copyright (C) 2006-2015 Eyeo GmbH |
| +# |
| +# Adblock Plus is free software: you can redistribute it and/or modify |
| +# it under the terms of the GNU General Public License version 3 as |
| +# published by the Free Software Foundation. |
| +# |
| +# Adblock Plus is distributed in the hope that it will be useful, |
| +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| +# GNU General Public License for more details. |
| +# |
| +# You should have received a copy of the GNU General Public License |
| +# along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. |
| + |
| +import itertools, MySQLdb |
| + |
| +def connect(user, password, database): |
| + return MySQLdb.connect( |
| + user=user, |
| + passwd=password, |
| + db=database, |
| + use_unicode=True, charset="utf8" |
| + ) |
| + |
| +def query(db, sql, *params, **kwargs): |
| + """ |
| + Executes the query given by the provided SQL and returns the results. |
| + If dict_result keyword argument is provided + True the results will be |
| + returned as a tuple of dictionaries, otherwise a tuple of tuples. |
| + """ |
| + dict_result=kwargs.pop('dict_result', False) |
| + |
| + try: |
| + if dict_result: |
| + cursor = db.cursor(MySQLdb.cursors.DictCursor) |
| + else: |
| + cursor = db.cursor() |
| + cursor.execute(sql, params) |
| + results = cursor.fetchall() |
| + finally: |
| + if cursor: |
| + cursor.close() |
| + return results |
| + |
| +def write(db, queries): |
| + """ |
| + This writes a given SQL string or iteratable object of tuples containing SQL |
| + strings and any required parameters to the database. All queries will |
| + be run as one transaction and rolled back on error. |
| + """ |
| + if isinstance(queries, str): |
| + queries = ((queries,),) |
| + |
| + try: |
| + cursor = db.cursor() |
| + try: |
| + for query in queries: |
| + sql, params = query[0], query[1:] |
| + cursor.execute(sql, params) |
| + db.commit() |
| + finally: |
| + cursor.close() |
| + except MySQLdb.Error: |
| + if db: |
| + db.rollback() |
| + raise |