如何在Spring bean中执行PL / pgSQL脚本?

时间:2019-06-28 14:01:42

标签: sql spring postgresql plpgsql

我有Spring应用程序,每次启动时我都需要检查表existense。 像这样

@PostConstruct
    public void init() {

        DataSource auditDataSource = DataSourceBuilder.create().url(url).driverClassName(driver).username(username).password(password).build();
        this.jdbcTemplate = new NamedParameterJdbcTemplate(auditDataSource);

        Resource initSchema = new ClassPathResource("audit-data.sql");
        DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema);
        try {
            DatabasePopulatorUtils.execute(databasePopulator, auditDataSource);
        } catch (ScriptException e) {
        }
    } 

每次启动我都需要启动PL SQL脚本 这里是

DO $$
DECLARE
columns_count INTEGER;
table_exists BOOLEAN;
BEGIN
table_exists = (SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'audit'));

IF (table_exists) THEN
columns_count = (SELECT COUNT(column_name)
FROM information_schema.columns
WHERE table_name='audit' and (
column_name='entry_da1te' or
column_name='payload' or
column_name='uid' or
column_name='type' or
column_name='session_id' or
column_name='user_uid' or
column_name='username'));
END IF;

IF (table_exists = false) OR (columns_count != 7) THEN
DROP TABLE IF EXISTS public.audit;
CREATE TABLE public.audit (
    entry_date timestamp without time zone DEFAULT CURRENT_TIMESTAMP,
    payload text,
    uid character varying(36),
    type character varying(1),
    session_id character varying(128),
    user_uid character varying(36),
    username character varying(1024)
);

ALTER TABLE public.audit OWNER TO postgres;
END IF;

END;
$$

启动后出现异常

Failed to execute SQL script statement #1 of class path resource [audit-data.sql]: DO $$ DECLARE columns_count INTEGER**Expected terminating $$

我试图在POSTGRES pgAdmin 4中启动此脚本。一切都很好。但是,当我尝试启动我的应用程序时-上面出现了异常。

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。我将DO部分放在逗号'中,并用双逗号"替换了''。现在工作正常。我不确定IDE类型是否很重要,但是我使用了IDEA 2019.1.3(未经Eclipse测试) 现在上面的代码看起来像这样

DO '
DECLARE
columns_count INTEGER;
table_exists BOOLEAN;
BEGIN
table_exists = (SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = ''public'' AND table_name = ''audit''));

IF (table_exists) THEN
columns_count = (SELECT COUNT(column_name)
FROM information_schema.columns
WHERE table_name=''audit'' and (
column_name=''entry_date'' or
column_name=''payload'' or
column_name=''uid'' or
column_name=''type'' or
column_name=''session_id'' or
column_name=''user_uid'' or
column_name=''username''));
END IF;

IF (table_exists = false) OR (columns_count != 7) THEN
DROP TABLE IF EXISTS public.audit;
CREATE TABLE public.audit (
    entry_date timestamp without time zone DEFAULT CURRENT_TIMESTAMP,
    payload text,
    uid character varying(36),
    type character varying(1),
    session_id character varying(128),
    user_uid character varying(36),
    username character varying(1024)
);

ALTER TABLE public.audit OWNER TO postgres;
END IF;

END';