一、概述
odoo的数据库连接层功能是连接odoo code与数据库,在odoo.sql_db模块中实现,区别于ORM。
二、涉及的类
涉及的类主要有:①Cursor,cr变量所指向的对象②Environment,可以访问访问cr、uid、context、注册类、管理记录集缓存;③Registry,能够获取到注册model,cursor()方法能返回新的游标;④Connection⑤ConnectionPool,直接实现与数据库的连接。
三、cr的实现过程
3.1 第一步,请求处理
# 截取部分代码
Class Root(object):
def dispatch(self, environ, start_response):
# pass
with request:
db = request.session.db
if db:
try:
# 调用odoo.registry()
odoo.registry(db).check_signaling()
with odoo.tools.mute_logger('odoo.sql_db'):
ir_http = request.registry['ir.http']
except (AttributeError, psycopg2.OperationalError, psycopg2.ProgrammingError):
# pass
3.2 第二步,使用db_name创建并初始化Registry实例
# odoo/__init__.py/def registry()
def registry(database_name=None):
"""
Return the model registry for the given database, or the database mentioned
on the current thread. If the registry does not exist yet, it is created on
the fly.
"""
if database_name is None:
import threading
database_name = threading.currentThread().dbname
# 创建Registry对象
return modules.registry.Registry(database_name)
# odoo/modules/registry.py
# 创建Registry对象具体实现
class Registry(Mapping):
""" Model registry for a particular database.
The registry is essentially a mapping between model names and model classes.
There is one registry instance per database.
model名字与类之间的映射
"""
# 返回Registry对象
def __new__(cls, db_name):
""" Return the registry for the given database name."""
with cls._lock:
try:
return cls.registries[db_name]
except KeyError:
# 返回Registry对象的实现方法调用
return cls.new(db_name)
finally:
# set db tracker - cleaned up at the WSGI dispatching phase in
# odoo.service.wsgi_server.application
threading.current_thread().dbname = db_name
# 返回Registry对象
@classmethod
def new(cls, db_name, force_demo=False, status=None, update_module=False):
""" Create and return a new registry for the given database name. """
with cls._lock:
with odoo.api.Environment.manage():
registry = object.__new__(cls)
# 调用初始化方法
registry.init