odoo中连接mysql数据库

以前以为odoo中只能连接postgresql数据库,并且只能连接一个数据库,今天发现,得益于postgresql的强大,我们可以再odoo中嵌入式地加载其他数据库的数据,就像本地库中的数据一样。
这其中的关键就在于postgresql中的foreign data wrapper的概念,利用fdw,我们可以连接mysql,sqlserver,oracle等市面上常见的数据库。
下面,我们就来说一下,如何利用fdw来实现这一目的。

先决条件

安装mysql_fdw

github 下载 mysql_fdw https://github.com/EnterpriseDB/mysql_fdw
首先运行 pg_config 如果报错,安装如下插件

1
You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application.

安装:
sudo apt-get install libpq-dev

编译

然后make之
make USE_PGXS=1
如果报如下的错误:

1
2
Makefile:47: /usr/lib/postgresql/9.5/lib/pgxs/src/makefiles/pgxs.mk: No such file or directory
Makefile:52: *** PostgreSQL 9.3, 9.4, 9.5, 9.6 or 10beta is required to compile this extension. Stop.

解决方法:

1
2
sudo apt-get install postgresql-server-dev-all
sudo apt-get install postgresql-common

centos 用如下命令安装:

1
2
yum install postgresql-server
yum install postgresql95-devel

安装 foreign data wrapper

make USE_PGXS=1 install

创建mysql_fdw for postgresql

  1. – load extension first time after install
    CREATE EXTENSION mysql_fdw;
  2. – create server object

    1
    2
    3
    CREATE SERVER mysql_server
    FOREIGN DATA WRAPPER mysql_fdw
    OPTIONS (host '127.0.0.1', port '3306');
  3. – create user mapping

    1
    2
    3
    CREATE USER MAPPING FOR postgres
    SERVER mysql_server
    OPTIONS (username 'foo', password 'bar');
  4. – create foreign table

    1
    2
    3
    4
    5
    6
    CREATE FOREIGN TABLE warehouse(
    warehouse_id int,
    warehouse_name text,
    warehouse_created datetime)
    SERVER mysql_server
    OPTIONS (dbname 'db', table_name 'warehouse');

至此,应该可以在pg数据库查询到mysql server中的数据了。

二、在odoo中使用FDW连接Mysql数据库

新建对象kite_runner

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class kite_user(models.Model):
_name = "kite.user"
_auto = False
_table = "kite_user"

def init(self):
self.env.cr.execute(
'''
create foreign table if not exists kite_user (
id int,
account varchar,
password varchar
)
server kite options(dbname 'db_scversion', table_name 'user')
'''
)

account = fields.Char(u'账号')
password = fields.Char(u'密码')

这里边的关键点在于,_auto要设置为False,这样odoo就不会傻乎乎地再去创建kite_user这个表了(odoo并不识别pg中的foreign table,它傻*似地只认普通表和视图),然后_table指定表名,这里的表名要跟已经存在的foreign table名一致。

新建了model,再给model建立好视图,就能像操作本地数据一样的方便操作mysql数据库了。

PS:参考资料中说,要自己添加create_uid,create_date,write_uid,write_date等默认字段,但是实际实现的过程中,我并没有实现这些字段,但也是成功的,只是缺少了这些字段,可能会在数据追查方面有所损失,如果需要,读者请自行实现。

三、在Amazon RDS中使用mysql_fdw

当前,Amazon Postgresql 所支持的扩展中并不包含 mysql_fdw,想要在rds中使用,就必须另辟蹊径。
这里提供一种方法,在一台独立的ec2中安装mysql_fdw,然后再rds中安装postgresql_fdw,使用postgresql_fdw外链到mysql_fdw,即利用postgresql_fdw当作中间转发跳板,经过二次转发到达mysql数据库完成我们的目的。

参考资料:

  1. https://github.com/EnterpriseDB/mysql_fdw
  2. https://www.odoo.com/forum/help-1/question/how-can-we-display-data-from-another-database-946
你的支持我的动力