PostgreSQL oracle 相容性 - 字串內嵌 NULL字元(空字元)chr(0) 轉換為 chr(32)
標籤
PostgreSQL , Oracle , chr(0) , 空字元 , 結束符 , 字串
背景
在Oracle中,儲存字串時,允許使用者將空字元存到字串中,雖然這種用法可能不常見,但是給Oracle遷移到PG的使用者帶來了一些小麻煩,因為PG中chr(0)是作為結束符來處理的,不允許作為使用者輸入傳入字串中。
如果要儲存chr(0)字元,PostgreSQL 必須儲存在位元組流型別中。
Oracle例子
1、chr(0)存入字串中。
SQL> select 1 from dual where 'a'||chr(32)||'b' = 'a b'; 1 ---------- 1 SQL> select 1 from dual where 'a'||chr(0)||'b' = 'a b'; no rows selected SQL> select 1 from dual where cast('a'||chr(0)||'b' as varchar2(10)) = 'a b'; no rows selected
2、將chr(0)轉換為空格,即chr(32)
SQL>select replace ('a'||chr(0)||'b', chr(0), chr(32)) from dual; REP --- a b
轉換後,判斷是否相等
SQL> select 1 from dual where replace ('a'||chr(0)||'b', chr(0), chr(32)) = 'a b'; 1 ---------- 1
PostgreSQL
postgres=# select 'a'||chr(0)||'b'; ERROR:54000: null character not permitted LOCATION:chr, oracle_compat.c:1000
src/backend/utils/adt/oracle_compat.c
993/* 994* Error out on arguments that make no sense or that we can't validly 995* represent in the encoding. 996*/ 997if (cvalue == 0) 998ereport(ERROR, 999(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), 1000errmsg("null character not permitted")));
相容性
當有文字資料需要從Oracle匯出到PG時,如果裡面儲存了空字元,可以先做一下轉換(比如轉換為空格),解決不相容問題。
SQL>select replace ('a'||chr(0)||'b', chr(0), chr(32)) from dual; REP --- a b