http://wiki.openbravo.com/wiki/ERP/2.50/Developers_Guide/Concepts/DB/PL-SQL_code_rules_to_write_Oracle_and_Postgresql_code Procedure Language rules Openbravo ERP supports Oracle and PostgreSQL database engines. This is a set of recommendat
http://wiki.openbravo.com/wiki/ERP/2.50/Developers_Guide/Concepts/DB/PL-SQL_code_rules_to_write_Oracle_and_Postgresql_code
Procedure Language rules
Openbravo ERP supports Oracle and PostgreSQL database engines.
This is a set of recommendations for writing Procedure Language that works on both database backends (when possible) or that can be automatically translated by DBSourceManager. These recommendations assume that you have written code in Oracle and that you want to port it to PostgreSQL.
General rules
This a list of general rules that assure that PL runs properly on different database backgrounds.
- JOIN statement. Change the code replacing the (+) by LEFT JOIN or RIGHT JOIN
- In XSQL we use a questionmark (?) as parameter placeholder. If it is a NUMERIC variable use TO_NUMBER(?). For dates use TO_DATE(?).
- Do not use GOTO since PostgreSQL does not support it. To get the same functionality that GOTO use boolean control variables and IF/THEN statements to check if the conditions are TRUE/FALSE.
- Replace NVL commands by COALESCE.
- Replace DECODE commands by CASE. If the CASE is NULL the format is:
CASE WHEN variable IS NULL THEN X ELSE Y END
If the variable is the result of concatenating several strings () are required.
- Replace SYSDATE commands by NOW()
- PostgreSQL treats "" and NULL differently. When checking for a null variable special care is required.
- When a SELECT is inside a FROM clause a synonym is needed.
SELECT * FROM (SELECT 'X' FROM DUAL) A
- When doing SELECT always use AS.
SELECT field AS field_name FROM DUAL
- PostgreSQL does not support synonyms of tables in UPDATE, INSERT or DELETE operations.
- PostgreSQL 8.1 (but fixed in 8.2 version) does not support updates like:
UPDATE TABLE_NAME SET (A,B,C) = (SELECT X, Y, Z FROM ..
The following order is correctly accepted:
UPDATE TABLE_NAME SET A = (SELECT X FROM ..), B = (SELECT Y FROM .),C = (SELECT Z FROM ..)
- PostgreSQL does not support using the table name in the fields to update.
- PostgreSQL does not support the DELETE TABLE command. DELETE FROM Table should be used instead.
- PostgreSQL does not support parameters like '1' in the ORDER BY or GROUP BY clause. A numeric without commas can be used.
- PostgreSQL does not support the CURRENT OF clause. An active checking of register to update should be used.
- PostgreSQL does not support COMMIT. It does automatically an explicit COMMIT between BEGIN END blocks. Throwing an exception produces a ROLLBACK.
- PostgreSQL does not support SAVEPOINT. BEGIN, END and ROLLBACK should be used instead to achieve the same functionality.
- PostgreSQL does not support CONNECT.
- Both Oracle and PostgreSQL do not support using variable names that match column table names. For example, use v_IsProcessing instead of IsProcessing.
- PostgreSQL does not support EXECUTE IMMEDIATE ... USING. The same functionality can be achieved using SELECT and replacing the variables with parameters manually.
- PostgreSQL requires () in calls to functions without parameters.
- DBMS.OUTPUT should be done in a single line to enable the automatic translator building the comment.
- In PostgreSQL any string concatenated to a NULL string generates a NULL string as result. It's is recommended to use a COALESCE or initialize the variable to ''.
- Notice that in Oracle null||'a' will return 'a' but in PostgrSQL null, so the solution would be coalesce(null,'')||'a' that will return the same for both. But if the we are working with Oracle's NVarchar type this will cause an ORA-12704: character set mismatch error, to fix it it is possible to use coalesce(to_char(myNVarCharVariable),)||'a'.
- Instead of doing
COALESCE(variable_integer, <em>)</em>
do
COALESCE(variable_integer, 0)
to guarantee that it will also work in PostgreSQL.
- PostgreSQL does the SELECT FOR UPDATE at a table level while Oracle does it at a column level.
- PostgreSQL does not support INSTR command with three parameters. SUBSTR should be used instead.
- In Oracle SUBSTR(text, 0, Y) and SUBSTR(text, 1, Y) return the same result but not in PostgreSQL. SUBSTR(text, 1, Y) should be used to guarantee that it works in both databases.
- PostgreSQL does not support labels like > (but it can be commented out).
- In dates comparisons is often needed a default date when the reference is null, January 1, 1900 or December 31, 9999 should be used.
- When is specified a date as a literal it is necessary to use always the to_date function with the correspondent format mask.
RIGHT: COALESCE(movementdate, TO_DATE('01-01-1900', 'DD-MM-YYYY'))
Cursors
There are two different ways of using cursors: in FETCH clauses and in FOR loops. For FETCH cursor type no changes are required (except for %ISOPEN and %NOTFOUND methods that are explained below).
Oracle FETCH cursor declarations:
CURSOR Cur_SR IS
should be translated in PostgreSQL into:
DECLARE Cur_SR CURSOR FOR
For cursors in FOR loops the format suggested is:
TYPE RECORD IS REF CURSOR; Cur_Name RECORD;
that is both accepted by Oracle and PostgreSQL.
Arrays
In Oracle, arrays are defined in the following way:
TYPE ArrayPesos IS VARRAY(10) OF INTEGER; v_pesos ArrayPesos; v_dc2 := v_dc2 + v_pesos(v_contador)*v_digito;
but in PostgresSQL they are defined as:
v_pesos integer[]; v_dc2 := v_dc2 + v_pesos[v_contador]*v_digito;
ROWNUM
To limit the number of registers that a SELECT command returns, a cursor needs to be created and read the registers from there. The code could be similar to:
--Initialize counter v_counter := initial_value; --Create the cursor FOR CUR_ROWNUM IN (SELECT CLAUSE) LOOP -- Some sentences --Increment the counter v_counter := v_counter + 1; --Validate condition IF (v_counter = condition_value) THEN EXIT; END IF; END LOOP;
%ROWCOUNT
SQL%ROWCOUNT cannot be used directly in PostgreSQL. To convert the SQL%ROWCOUNT into PostgreSQL its value should be defined in a variable. For example:
GET DIAGNOSTICS rowcount := ROW_COUNT;
In place of SQL%ROWCOUNT the previously declared variable should be used.
%ISOPEN, %NOTFOUND
PostgreSQL cursors do not support %ISOPEN or %NOTFOUND. To address this problem %ISOPEN can be replaced by a boolean variable declared internally in the procedure and is updated manually when the cursor is opened or closed.
Formating code
- To export properly a RAISE NOTICE from postgresql to xml files you have to follow this syntax:
RAISE NOTICE '%', '@Message@' ;
- To export properly a RAISE EXCEPTION from postgresql to xml files you have to add the following comment at the end of the command; --OBTG:-20000--
RAISE EXCEPTION '%', '@Message@' ; --OBTG:-20000--
- In a IF clause is very important to indent the lines within the IF.
IF (CONDITION) COMMAND; END IF;
- The functions with output parameters have to be invoked with select * into.
SELECT * into VAR from FUNCTION();
- The end of the functions have to be defined as following to be exported properly:
END ; $BODY$ LANGUAGE 'plpgsql' VOLATILE COST 100;
- The cast used by postgresql is not supported by Dbsourcemanager. Instead of using :: type, use a function to convert the value
:: interval -> to_interval(,) :: double precision -> to_number()
Elements not supported by dbsource manager
- Functions that return "set of tablename"
- Functions that return and array
- Functions using regular expresions
- Column with type not included on the table on the following document: http://wiki.openbravo.com/wiki/ERP/2.50/Developers_Guide/Concepts/DB/Tables#Supported_Column_Data_types
Functions
PERFORM and SELECT are the two commands that allow calling a function. Since PostgreSQL does not accept default function parameters we define an overloaded function with default parameters.
To allow the automatic translator to do its job the following recommendations should be followed:
- The AS and the IS should not contain spaces to the left
- The function name should not be quoted
- In functions, the END should go at the beginning of the line without any spaces to the left and with the function name.
Procedures
There are two ways of invoking procedures from PosgreSQL:
- Using the format variable_name := Procedure_Name(...);
- Using a SELECT. This is the method used for procedures that return more than one parameter.
Views
PostgreSQL does not support update for the views. If there is the need of updating a view a set of rules should be created for the views that need to be updated.
In PostgreSQL there are no table/views USER_TABLES or USER_TAB_COLUMNS. They should be created from PostgreSQL specific tables like pg_class or pg_attribute.
Triggers
Rules that the triggers should follow:
- As general rule, is not desirable to modify child columns in a trigger of the parent table, because it is very usual that child trigger have to consult data from parent table, origin a mutating table error.
- The name should not be quoted (") because PostgreSQL interprets it literally.
- All the triggers have a DECLARE before the legal notice. In PostgreSQL it is necessary to do a function declaration first and then the trigger's declaration that executes the function.
- PostgreSQL does not support the OF ..(columns).. ON Table definition. It is necessary to include the checking inside the trigger.
- PostgreSQL does not support lazy evaluation. For example the following sentence works in Oracle but not in PostgreSQL:
IF INSERTING OR (UPDATING AND :OLD.FIELD = <em>) THEN</em>
The correct way of expressing this is:
IF INSERTING THEN ... IF UPDATING THEN IF :OLD.NAME = <em> THEN</em>
- Triggers in PostgreSQL always return something. Depending on the type of operation it returns OLD (DELETE) or NEW (INSERT/UPDATE). It should be placed at the end of the trigger and before the exceptions if there are any.
If you are using the automatic translator consider that:
- The last EXCEPTION in the trigger should not have spaces to its left. The translator considers this the last exception and uses it to setup the right return value.
- The last END should not have spaces to its left. The indentation is used to determine where function ends.
- Beware that if you add an statement like "IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;" just before the EXCEPTION statement, it might be removed by the automatic translator.

MySQL은 오픈 소스 관계형 데이터베이스 관리 시스템으로, 주로 데이터를 신속하고 안정적으로 저장하고 검색하는 데 사용됩니다. 작업 원칙에는 클라이언트 요청, 쿼리 해상도, 쿼리 실행 및 반환 결과가 포함됩니다. 사용의 예로는 테이블 작성, 데이터 삽입 및 쿼리 및 조인 작업과 같은 고급 기능이 포함됩니다. 일반적인 오류에는 SQL 구문, 데이터 유형 및 권한이 포함되며 최적화 제안에는 인덱스 사용, 최적화 된 쿼리 및 테이블 분할이 포함됩니다.

MySQL은 데이터 저장, 관리, 쿼리 및 보안에 적합한 오픈 소스 관계형 데이터베이스 관리 시스템입니다. 1. 다양한 운영 체제를 지원하며 웹 응용 프로그램 및 기타 필드에서 널리 사용됩니다. 2. 클라이언트-서버 아키텍처 및 다양한 스토리지 엔진을 통해 MySQL은 데이터를 효율적으로 처리합니다. 3. 기본 사용에는 데이터베이스 및 테이블 작성, 데이터 삽입, 쿼리 및 업데이트가 포함됩니다. 4. 고급 사용에는 복잡한 쿼리 및 저장 프로 시저가 포함됩니다. 5. 설명 진술을 통해 일반적인 오류를 디버깅 할 수 있습니다. 6. 성능 최적화에는 인덱스의 합리적인 사용 및 최적화 된 쿼리 문이 포함됩니다.

MySQL은 성능, 신뢰성, 사용 편의성 및 커뮤니티 지원을 위해 선택됩니다. 1.MYSQL은 효율적인 데이터 저장 및 검색 기능을 제공하여 여러 데이터 유형 및 고급 쿼리 작업을 지원합니다. 2. 고객-서버 아키텍처 및 다중 스토리지 엔진을 채택하여 트랜잭션 및 쿼리 최적화를 지원합니다. 3. 사용하기 쉽고 다양한 운영 체제 및 프로그래밍 언어를 지원합니다. 4. 강력한 지역 사회 지원을 받고 풍부한 자원과 솔루션을 제공합니다.

InnoDB의 잠금 장치에는 공유 잠금 장치, 독점 잠금, 의도 잠금 장치, 레코드 잠금, 갭 잠금 및 다음 키 잠금 장치가 포함됩니다. 1. 공유 잠금을 사용하면 다른 트랜잭션을 읽지 않고 트랜잭션이 데이터를 읽을 수 있습니다. 2. 독점 잠금은 다른 트랜잭션이 데이터를 읽고 수정하는 것을 방지합니다. 3. 의도 잠금은 잠금 효율을 최적화합니다. 4. 레코드 잠금 잠금 인덱스 레코드. 5. 갭 잠금 잠금 장치 색인 기록 간격. 6. 다음 키 잠금은 데이터 일관성을 보장하기 위해 레코드 잠금과 갭 잠금의 조합입니다.

MySQL 쿼리 성능이 좋지 않은 주된 이유는 인덱스 사용, 쿼리 최적화에 의한 잘못된 실행 계획 선택, 불합리한 테이블 디자인, 과도한 데이터 볼륨 및 잠금 경쟁이 포함됩니다. 1. 색인이 느리게 쿼리를 일으키지 않으며 인덱스를 추가하면 성능이 크게 향상 될 수 있습니다. 2. 설명 명령을 사용하여 쿼리 계획을 분석하고 Optimizer 오류를 찾으십시오. 3. 테이블 구조를 재구성하고 결합 조건을 최적화하면 테이블 설계 문제가 향상 될 수 있습니다. 4. 데이터 볼륨이 크면 분할 및 테이블 디비전 전략이 채택됩니다. 5. 높은 동시성 환경에서 거래 및 잠금 전략을 최적화하면 잠금 경쟁이 줄어들 수 있습니다.

데이터베이스 최적화에서 쿼리 요구 사항에 따라 인덱싱 전략을 선택해야합니다. 1. 쿼리에 여러 열이 포함되고 조건 순서가 수정되면 복합 인덱스를 사용하십시오. 2. 쿼리에 여러 열이 포함되어 있지만 조건 순서가 고정되지 않은 경우 여러 단일 열 인덱스를 사용하십시오. 복합 인덱스는 다중 열 쿼리를 최적화하는 데 적합한 반면 단일 열 인덱스는 단일 열 쿼리에 적합합니다.

MySQL 느린 쿼리를 최적화하려면 SlowQueryLog 및 Performance_Schema를 사용해야합니다. 1. SlowQueryLog 및 Set Stresholds를 사용하여 느린 쿼리를 기록합니다. 2. Performance_schema를 사용하여 쿼리 실행 세부 정보를 분석하고 성능 병목 현상을 찾고 최적화하십시오.

MySQL 및 SQL은 개발자에게 필수적인 기술입니다. 1.MySQL은 오픈 소스 관계형 데이터베이스 관리 시스템이며 SQL은 데이터베이스를 관리하고 작동하는 데 사용되는 표준 언어입니다. 2.MYSQL은 효율적인 데이터 저장 및 검색 기능을 통해 여러 스토리지 엔진을 지원하며 SQL은 간단한 문을 통해 복잡한 데이터 작업을 완료합니다. 3. 사용의 예에는 기본 쿼리 및 조건 별 필터링 및 정렬과 같은 고급 쿼리가 포함됩니다. 4. 일반적인 오류에는 구문 오류 및 성능 문제가 포함되며 SQL 문을 확인하고 설명 명령을 사용하여 최적화 할 수 있습니다. 5. 성능 최적화 기술에는 인덱스 사용, 전체 테이블 스캔 피하기, 조인 작업 최적화 및 코드 가독성 향상이 포함됩니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.
