[MERGE] demo data: remove salesman on customers
[odoo/odoo.git] / openerp / modules / registry.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
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 """ Models registries.
23
24 """
25 import threading
26
27 import logging
28
29 import openerp.sql_db
30 import openerp.osv.orm
31 import openerp.cron
32 import openerp.tools
33 import openerp.modules.db
34 import openerp.tools.config
35
36 class Registry(object):
37     """ Model registry for a particular database.
38
39     The registry is essentially a mapping between model names and model
40     instances. There is one registry instance per database.
41
42     """
43
44     def __init__(self, db_name):
45         self.models = {} # model name/model instance mapping
46         self._sql_error = {}
47         self._store_function = {}
48         self._init = True
49         self._init_parent = {}
50         self.db_name = db_name
51         self.db = openerp.sql_db.db_connect(db_name)
52
53         cr = self.db.cursor()
54         has_unaccent = openerp.modules.db.has_unaccent(cr)
55         if openerp.tools.config['unaccent'] and not has_unaccent:
56             logger = logging.getLogger('unaccent')
57             logger.warning("The option --unaccent was given but no unaccent() function was found in database.")
58         self.has_unaccent = openerp.tools.config['unaccent'] and has_unaccent
59         cr.close()
60
61     def do_parent_store(self, cr):
62         for o in self._init_parent:
63             self.get(o)._parent_store_compute(cr)
64         self._init = False
65
66     def obj_list(self):
67         """ Return the list of model names in this registry."""
68         return self.models.keys()
69
70     def add(self, model_name, model):
71         """ Add or replace a model in the registry."""
72         self.models[model_name] = model
73
74     def get(self, model_name):
75         """ Return a model for a given name or None if it doesn't exist."""
76         return self.models.get(model_name)
77
78     def __getitem__(self, model_name):
79         """ Return a model for a given name or raise KeyError if it doesn't exist."""
80         return self.models[model_name]
81
82     def load(self, cr, module):
83         """ Load a given module in the registry.
84
85         At the Python level, the modules are already loaded, but not yet on a
86         per-registry level. This method populates a registry with the given
87         modules, i.e. it instanciates all the classes of a the given module
88         and registers them in the registry.
89
90         """
91
92         res = []
93
94         # Instantiate registered classes (via the MetaModel automatic discovery
95         # or via explicit constructor call), and add them to the pool.
96         for cls in openerp.osv.orm.MetaModel.module_to_models.get(module.name, []):
97             res.append(cls.create_instance(self, cr))
98
99         return res
100
101     def schedule_cron_jobs(self):
102         """ Make the cron thread care about this registry/database jobs.
103         This will initiate the cron thread to check for any pending jobs for
104         this registry/database as soon as possible. Then it will continuously
105         monitor the ir.cron model for future jobs. See openerp.cron for
106         details.
107         """
108         openerp.cron.schedule_wakeup(openerp.cron.WAKE_UP_NOW, self.db.dbname)
109
110     def clear_caches(self):
111         """ Clear the caches
112         This clears the caches associated to methods decorated with
113         ``tools.ormcache`` or ``tools.ormcache_multi`` for all the models.
114         """
115         for model in self.models.itervalues():
116             model.clear_caches()
117
118 class RegistryManager(object):
119     """ Model registries manager.
120
121         The manager is responsible for creation and deletion of model
122         registries (essentially database connection/model registry pairs).
123
124     """
125     # Mapping between db name and model registry.
126     # Accessed through the methods below.
127     registries = {}
128     registries_lock = threading.RLock()
129
130     @classmethod
131     def get(cls, db_name, force_demo=False, status=None, update_module=False,
132             pooljobs=True):
133         """ Return a registry for a given database name."""
134         try:
135             return cls.registries[db_name]
136         except KeyError:
137             return cls.new(db_name, force_demo, status,
138                            update_module, pooljobs)
139
140     @classmethod
141     def new(cls, db_name, force_demo=False, status=None,
142             update_module=False, pooljobs=True):
143         """ Create and return a new registry for a given database name.
144
145         The (possibly) previous registry for that database name is discarded.
146
147         """
148         import openerp.modules
149         with cls.registries_lock:
150             registry = Registry(db_name)
151
152             # Initializing a registry will call general code which will in turn
153             # call registries.get (this object) to obtain the registry being
154             # initialized. Make it available in the registries dictionary then
155             # remove it if an exception is raised.
156             cls.delete(db_name)
157             cls.registries[db_name] = registry
158             try:
159                 # This should be a method on Registry
160                 openerp.modules.load_modules(registry.db, force_demo, status, update_module)
161             except Exception:
162                 del cls.registries[db_name]
163                 raise
164
165             cr = registry.db.cursor()
166             try:
167                 registry.do_parent_store(cr)
168                 registry.get('ir.actions.report.xml').register_all(cr)
169                 cr.commit()
170             finally:
171                 cr.close()
172
173         if pooljobs:
174             registry.schedule_cron_jobs()
175
176         return registry
177
178     @classmethod
179     def delete(cls, db_name):
180         """Delete the registry linked to a given database.
181
182         This also cleans the associated caches. For good measure this also
183         cancels the associated cron job. But please note that the cron job can
184         be running and take some time before ending, and that you should not
185         remove a registry if it can still be used by some thread. So it might
186         be necessary to call yourself openerp.cron.Agent.cancel(db_name) and
187         and join (i.e. wait for) the thread.
188         """
189         with cls.registries_lock:
190             if db_name in cls.registries:
191                 cls.registries[db_name].clear_caches()
192                 del cls.registries[db_name]
193                 openerp.cron.cancel(db_name)
194
195
196     @classmethod
197     def delete_all(cls):
198         """Delete all the registries. """
199         with cls.registries_lock:
200             for db_name in cls.registries.keys():
201                 cls.delete(db_name)
202
203     @classmethod
204     def clear_caches(cls, db_name):
205         """Clear caches
206
207         This clears the caches associated to methods decorated with
208         ``tools.ormcache`` or ``tools.ormcache_multi`` for all the models
209         of the given database name.
210
211         This method is given to spare you a ``RegistryManager.get(db_name)``
212         that would loads the given database if it was not already loaded.
213         """
214         with cls.registries_lock:
215             if db_name in cls.registries:
216                 cls.registries[db_name].clear_caches()
217
218
219 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: