代码阅读db.py
-
-- coding: utf-8 --
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
# Copyright (C) 2010-2012 OpenERP s.a. (<http://openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import openerp.modules
import logging
logger = logging.getLogger(name)
def is_initialized(cr):
""" Check if a database has been initialized for the ORM.
The database can be initialized with the 'initialize' function below.
"""
[color=red]'''
pg_class是postgresql记载表和几乎所有有字段或者是那些类似表的东西,OE里所有的对象都存储在ir_module_module,我们利用它来判断
某个数据库是否已初始化
'''[/color]
cr.execute("SELECT relname FROM pg_class WHERE relkind='r' AND relname='ir_module_module'")
return len(cr.fetchall()) > 0
[color=red]'''
初始化数据库
'''[/color]
def initialize(cr):
""" Initialize a database with for the ORM.
This executes base/base.sql, creates the ir_module_categories (taken
from each module descriptor file), and creates the ir_module_module
and ir_model_data entries.
"""
f = openerp.modules.get_module_resource('base', 'base.sql') [color=red]//获取base模块下的base.sql文件[/color]
if not f:
m = "File not found: 'base.sql' (provided by module 'base')."
logger.critical(m)
raise IOError(m)
base_sql_file = openerp.tools.misc.file_open(f) [color=red]//打开获得的文件[/color]
try:
cr.execute(base_sql_file.read())
cr.commit()
finally:
base_sql_file.close()
for i in openerp.modules.get_modules():
mod_path = openerp.modules.get_module_path(i)
if not mod_path:
continue
# This will raise an exception if no/unreadable descriptor file.
info = openerp.modules.load_information_from_description_file(i) [color=red]//获取模块下的_openerp.py文件[/color]
if not info:
continue
categories = info['category'].split('/')
category_id = create_categories(cr, categories) [color=red]//创建目录[/color]
if info['installable']: [color=red]//如果installable为true的话,设置state为uninstalled[/color]
state = 'uninstalled'
else:
state = 'uninstallable'
cr.execute('INSERT INTO ir_module_module <br /> (author, website, name, shortdesc, description, <br /> category_id, auto_install, state, web, license, application, icon, sequence, summary) <br /> VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) RETURNING id', (
info['author'],
info['website'], i, info['name'],
info['description'], category_id,
info['auto_install'], state,
info['web'],
info['license'],
info['application'], info['icon'],
info['sequence'], info['summary'])) [color=red]//将所有对象的_openerp.py文件中的信息存入到ir_module_module中[/color]
id = cr.fetchone()[0]
cr.execute('INSERT INTO ir_model_data <br /> (name,model,module, res_id, noupdate) VALUES (%s,%s,%s,%s,%s)', (
'module_'+i, 'ir.module.module', 'base', id, True))
dependencies = info['depends']
for d in dependencies:
cr.execute('INSERT INTO ir_module_module_dependency <br /> (module_id,name) VALUES (%s, %s)', (id, d))
# Install recursively all auto-installing modules
[color=red]'''
递归的安装_openerp_.py文件中所有auto_install为true的模块,这也是为什么刚初始化的数据库会安装了一些模块的原因,因为其
auto_install被设置了true。我们在新建模块的时候一般设成false,不让其初始化数据库时就安装
'''[/color]
while True:
cr.execute("""SELECT m.name FROM ir_module_module m WHERE m.auto_install AND state != 'to install'
AND NOT EXISTS (
SELECT 1 FROM ir_module_module_dependency d JOIN ir_module_module mdep ON (d.name = mdep.name)
WHERE d.module_id = m.id AND mdep.state != 'to install'
)""")
to_auto_install = [x[0] for x in cr.fetchall()]
if not to_auto_install: break
cr.execute("""UPDATE ir_module_module SET state='to install' WHERE name in %s""", (tuple(to_auto_install),))
cr.commit()
[color=red]'''
创建目录,目录用于对模块,组等等进行分门别类,信息来自_openerp_.py中的category项
'''[/color]
def create_categories(cr, categories):
""" Create the ir_module_category entries for some categories.
categories is a list of strings forming a single category with its
parent categories, like ['Grand Parent', 'Parent', 'Child'].
Return the database id of the (last) category.
"""
p_id = None
category = []
while categories:
category.append(categories[0])
[color=red]//对于传进来的目录名进行拼接,组成module_category_xxxxxx,其中xxxxxx就是_openerp_.py里的目录名[/color]
xml_id = 'module_category_' + (''.join(map(lambda x: x.lower(), category))).replace('&', 'and').replace(' ', '')
# search via xml_id (because some categories are renamed)
cr.execute("SELECT res_id FROM ir_model_data WHERE name=%s AND module=%s AND model=%s",
(xml_id, "base", "ir.module.category"))
c_id = cr.fetchone()
if not c_id:
[color=red]//如果ir_module_data中没有相关目录信息,则新建立,并插入新的数据到ir_module_data中[/color]
cr.execute('INSERT INTO ir_module_category <br /> (name, parent_id) <br /> VALUES (%s, %s) RETURNING id', (categories[0], p_id))
c_id = cr.fetchone()[0]
cr.execute('INSERT INTO ir_model_data (module, name, res_id, model) <br /> VALUES (%s, %s, %s, %s)', ('base', xml_id, c_id, 'ir.module.category'))
else:
c_id = c_id[0]
p_id = c_id
categories = categories[1:]
return p_id
[color=red]'''
检测数据库是否有unaccent函数,unaccent函数是用来移除给定字符串上的读音符号
'''[/color]
def has_unaccent(cr):
""" Test if the database has an unaccent function.
The unaccent is supposed to be provided by the PostgreSQL unaccent contrib
module but any similar function will be picked by OpenERP.
"""
cr.execute("SELECT proname FROM pg_proc WHERE proname='unaccent'")
return len(cr.fetchall()) > 0
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: