1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # mojo, a Python library for implementing document based databases
5 # Copyright (C) 2013-2014 by Javier Sancho Fernandez <jsf at jsancho dot org>
7 # This program 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.
12 # This program 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.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
25 class Connection(mojo.Connection):
26 def __init__(self, *args, **kwargs):
27 self._db_con = MySQLdb.connect(*args, **kwargs)
30 cur = self._db_con.cursor()
37 def _get_databases(self):
38 return [x[0] for x in self.query("SHOW DATABASES")]
40 def _get_tables(self, db_name):
41 return [x[0] for x in self.query("SHOW TABLES FROM `%s`" % db_name)]
43 def _count_rows(self, db_name, table_name):
44 return self.query("SELECT COUNT(*) FROM `%s`.`%s`" % (db_name, table_name))[0][0]
46 def _get_sql_field(self, db_name, field):
47 if type(field) is tuple:
48 return "`%s`.`%s`.`%s`" % (db_name, field[0], field[1])
49 elif type(field) is dict:
50 return "(%s)" % self._get_sql_query(db_name, field)
52 return "'%s'" % str(field)
54 def _get_sql_query(self, db_name, query):
56 sql += ",".join([self._get_sql_field(db_name, x) for x in query['select']])
59 sql += ",".join(query['from'])
61 if query.get('where'):
64 for cond in query['where']:
65 where.append("%s %s %s" % (self._get_sql_field(db_name, cond[0]), cond[1], self._get_sql_field(db_name, cond[2])))
66 sql += " AND ".join(where)
70 def _get_cursor(self, db_name, query):
71 cur = self._db_con.cursor()
72 cur.execute(self._get_sql_query(db_name, query))