[ADD] osv: initial basic implementation of Query object:
[odoo/odoo.git] / bin / osv / query.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2010 OpenERP S.A. http://www.openerp.com
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
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 Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22
23 def _quote(to_quote):
24     if '"' not in to_quote:
25         return '"%s"' % to_quote
26     return to_quote
27
28
29 class Query(object):
30     """
31      Dumb implementation of a Query object, using 3 string lists so far
32      for backwards compatibility with the (table, where_clause, where_params) previously used.
33      
34      TODO: To be improved after v6.0 to rewrite part of the ORM and add support for:
35       - auto-generated multiple table aliases
36       - multiple joins to the same table with different conditions
37       - dynamic right-hand-side values in domains  (e.g. a.name = a.description)
38       - etc.
39     """
40
41     def __init__(self, tables=None, where_clause=None, where_clause_params=None, joins=None):
42
43         # holds the list of tables joined using default JOIN.
44         # the table names are stored double-quoted (backwards compatibility)
45         self.tables = tables or []
46
47         # holds the list of WHERE clause elements, to be joined with
48         # 'AND' when generating the final query 
49         self.where_clause = where_clause or []
50
51         # holds the parameters for the formatting of `where_clause`, to be
52         # passed to psycopg's execute method.
53         self.where_clause_params = where_clause_params or []
54
55         # holds table joins done explicitly, supporting outer joins. The JOIN
56         # condition should not be in `where_clause`. The dict is used as follows:
57         #   self.joins = {
58         #                    'table_a': [
59         #                                  ('table_b', 'table_a_col1', 'table_b_col', 'LEFT JOIN'),
60         #                                  ('table_c', 'table_a_col2', 'table_c_col', 'LEFT JOIN'),
61         #                                  ('table_d', 'table_a_col3', 'table_d_col', 'JOIN'),
62         #                               ]
63         #                 }
64         #   which should lead to the following SQL:
65         #       SELECT ... FROM "table_a" LEFT JOIN "table_b" ON ("table_a"."table_a_col1" = "table_b"."table_b_col")
66         #                                 LEFT JOIN "table_c" ON ("table_a"."table_a_col2" = "table_c"."table_c_col")
67         self.joins = joins or {}
68
69     def join(self, connection, outer=False):
70         """Adds the JOIN specified in ``connection``.
71
72         :param connection: a tuple ``(lhs, table, lhs_col, col)``. 
73                            The join corresponds to the SQL equivalent of::
74
75                                 ``(lhs.lhs_col = table.col)``
76
77         :param outer: True if a LEFT OUTER JOIN should be used, if possible
78                       (no promotion to OUTER JOIN is supported in case the JOIN
79                        was already present in the query, as for the moment
80                        implicit INNER JOINs are only connected from NON-NULL 
81                        columns so it would not be correct (e.g. for 
82                        ``_inherits`` or when a domain criterion explicitly 
83                        adds filtering)
84         """
85         (lhs, table, lhs_col, col) = connection
86         lhs = _quote(lhs)
87         table = _quote(table)
88         assert lhs in self.tables, "Left-hand-side table must already be part of the query!"
89         if table in self.tables:
90             # already joined, must ignore (promotion to outer and multiple joins not supported yet)
91             pass
92         else:
93             # add JOIN
94             self.tables.append(table)
95             self.joins.setdefault(lhs, []).append((table, lhs_col, col, outer and 'LEFT JOIN' or 'JOIN'))
96         return self 
97
98     def get_sql(self):
99         """Returns (query_from, query_where, query_params)"""
100         query_from = ''
101         tables_to_process = list(self.tables)
102         for table in tables_to_process:
103             query_from += ' %s ' % table
104             if table in self.joins:
105                 for (dest_table, lhs_col, col, join) in self.joins[table]:
106                     tables_to_process.remove(dest_table)
107                     query_from += '%s %s ON (%s."%s" = %s."%s")' % \
108                         (join, dest_table, table, lhs_col, dest_table, col)
109             query_from += ','
110         query_from = query_from[:-1] # drop last comma
111         return (query_from, " AND ".join(self.where_clause), self.where_clause_params)
112
113     def __str__(self):
114         return '<osv.Query: "SELECT ... FROM %s WHERE %s" with params: %r>' % self.get_sql()
115
116 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: