重点注意事项

这里重点描述从 Mysql 迁移到 PostgreSql 中重点注意事项。以及在普通的业务逻辑中,应该注意的事项。

1、创建表

mysql 的撰写

create table wk_course (
course_id BIGINT unsigned NOT NULL AUTO_INCREMENT COMMENT '课程id',
course_name varchar(255) NOT NULL COMMENT '课程',
gmt_create DATETIME DEFAULT CURRENT_TIMESTAMP NULL COMMENT '记录创建时间',
gmt_modified DATETIME DEFAULT CURRENT_TIMESTAMP NULL COMMENT '记录修改时间',
PRIMARY KEY (course_id),
UNIQUE KEY `wk_course_unique` (`course_name`)
) ENGINE=InnoDB AUTO_INCREMENT=10000 DEFAULT CHARSET=utf8mb4 COMMENT='课程表';

PostgreSql

create table wk_course (
course_id BIGSERIAL NOT NULL ,
course_name varchar(255) NOT NULL ,
gmt_create timestamp(0) without time zone DEFAULT CURRENT_TIMESTAMP ,
gmt_modified timestamp(0) without time zone DEFAULT CURRENT_TIMESTAMP ,
PRIMARY KEY (course_id),
constraint wk_course_unique unique (course_name)
) ;
comment on table wk_course is '课程表';
comment on column wk_course.course_id is '课程id';
comment on column wk_course.course_name is '课程';
comment on column wk_course.gmt_create is '记录创建时间';
comment on column wk_course.gmt_modified is '记录修改时间';

差距

  • PostgreSql中没有 unsigned
  • Mysql的日期时间类型,转换成PostgreSqltimestamp(0) without time zone
  • 自增主键,MySqlAUTO_INCREMENTPostgreSql用:SMALLSERIALSERIALBIGSERIAL 类型
  • 唯一索引,PostgreSql: constraint wk_student_scores_unique unique (student_id,course_id)

2、命名规范

这里是特殊性

  • 必须是小写,用下划线隔开。
  • 由于业务单一,就使用public schema
  • comment 使用中文

3、设计规范

  • 不建议使用外键

  • 不建议自建函数与校验规则,这部分交给 Java 程序来处理。

  • 不建议使用数据库触发器,这会使得数据处理逻辑复杂,不便于调试

  • 不建议使用文件类型的字段

4、兼容 Mybatis 代码

系统中以前为Mysql生成的代码,在代码不做修改的前提下,如何兼容PostgreSql呢?

兼容自增

PostgreSql中创建一个函数

create or replace function LAST_INSERT_ID()
returns bigint as $$
begin
return lastval();
end; $$
language plpgsql;

5、底层代码调试

现在框架的底层可以支持 Mysql 与 PostgreSql,并且做了单元测试。如果分别测试两种数据库呢?

修改下面要连接的数据库,然后执行 test 命令,就进行了自动化单元测试。

#spring:
# datasource:
# driver-class-name: com.mysql.cj.jdbc.Driver
# password: Mysql@root123
# url: jdbc:mysql://127.0.0.1:3306/wk_example?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
# username: root
spring:
datasource:
driver-class-name: org.postgresql.Driver
password: example
url: jdbc:postgresql://127.0.0.1:5432/test
username: postgres
flyway:
locations: classpath:db/migration-pg
enabled: true