SAP R/3 форум ABAP консультантов
Russian ABAP Developer's Club

Home - FAQ - Search - Memberlist - Usergroups - Profile - Log in to check your private messages - Register - Log in - English
Blogs - Weblogs News

Особенности асинхронных, синхронных и локальных апдейтов



 
Post new topic   Reply to topic    Russian ABAP Developer's Club Forum Index -> SQL and Database Changes
View previous topic :: View next topic  
Author Message
admin
Администратор
Администратор



Joined: 01 Sep 2007
Posts: 1639

PostPosted: Thu Oct 04, 2007 9:05 pm    Post subject: Особенности асинхронных, синхронных и локальных апдейтов Reply with quote

Особенности и отладка асинхронных, синхронных и локальных апдейтов.

Для понимания работы различных режимов создадим в системе апдейтный функциональный модуль
Z_TEST_UPDATE со следующими атрибутами:
Processing type
- Update module
- Start immed.

Code:
FUNCTION Z_TEST_UPDATE.
*"----------------------------------------------------------------------
*"*"Update Function Module:
*"
*"*"Local Interface:
*"  IMPORTING
*"     VALUE(I_BUKRS) TYPE  BUKRS
*"     VALUE(I_BELNR) TYPE  BELNR
*"     VALUE(I_GJAHR) TYPE  GJAHR
*"     VALUE(I_BKTXT) TYPE  BKTXT
*"  EXCEPTIONS
*"      ERROR
*"----------------------------------------------------------------------

UPDATE bkpf
  SET   bktxt = i_bktxt
  WHERE bukrs = i_bukrs
    AND belnr = i_belnr
    AND gjahr = i_gjahr.

IF NOT sy-subrc IS INITIAL.
  RAISE ERROR.
ENDIF.

ENDFUNCTION.

Для отладки вызываемого функционального модуля установим
в отладчике флажек Debug mode - Update Debugging

Для понимания запускаемых в системе процессов воспользуемся транзакцией SM50. До запуска тестовых примеров на экране SM50
видим следующее состояние процессов:


Ниже по тексту перед описания каждого типа апдейта будет приводиться выдержка из курса BC414 - Programming Database Updates

Итак, начнем:


- In asynchronous update, the dialog program and update program run separately.
­ The dialog program writes the update requests into the log table VBLOG in the database.
­ You conclude the dialog part of the SAP LUW with the COMMIT WORK statement. A new SAP LUW immediately starts in the dialog program, which can carry on processing user dialogs without interruption. The dialog program does not wait for the update program to finish.
­ The update program is run on a special update work process. This need not be on the same server as the corresponding dialog work process.
­ The SAP LUW that began in the dialog program is continued and then closed by the update program.
- The log table VBLOG can be implement as a cluster file in your system, or be replaced with the transparent tables VBHDR, VBMOD, VBDATA, and VBERROR.
- Asynchronous updates are useful in transactions where the database updates take a long time and the "perceived performance" by the shorter user dialog response time is important.
- Asynchronous update is the standard technique for dialog processing.
- The entries that have a HEADER can be analyzed in SM13.

Запустим на выполнение программу:
Code:
REPORT Z_UPDATE_TEST.

CALL FUNCTION 'Z_TEST_UPDATE' IN UPDATE TASK
  EXPORTING I_BUKRS = '1000'
       I_BELNR = '0000001081'
       I_GJAHR = '2004'
            I_BKTXT = 'test'.

COMMIT WORK.
WRITE: / 'End'.


В результате выполнения COMMIT WORK при включенной в отладчике опции Debug mode - Update Debugging откроется новое окно в отладчике, где мы попадем на сформированную Update-программой подпрограмму, запускающую наш ФМ:
Code:
*******************************************************************
*   THIS FILE IS GENERATED BY THE FUNCTION LIBRARY.               *
*   NEVER CHANGE IT MANUALLY, PLEASE!                             *
*******************************************************************
FORM Z_TEST_UPDATE USING %_KEY.
* Parameter declaration
DATA %_P0000000001 TYPE
BUKRS
.
DATA %_P0000000002 TYPE
GJAHR
.
DATA %_P0000000003 TYPE
BELNR
.
DATA %_P0000000004 TYPE
BKTXT
.
DATA: %_STATE.
* Assign default values
* Get mode for update task
  CALL 'GET_SWITCH_UTASK'
   ID 'MODE'  FIELD 'S'
   ID 'STATE' FIELD %_STATE.
  IF %_STATE EQ 'N'.
* Import from memory
  IMPORT
    I_BUKRS TO %_P0000000001
    I_GJAHR TO %_P0000000002
    I_BELNR TO %_P0000000003
    I_BKTXT TO %_P0000000004
  FROM MEMORY ID %_KEY.
  ELSE.
* Import from logfile
  IMPORT
    I_BUKRS TO %_P0000000001
    I_GJAHR TO %_P0000000002
    I_BELNR TO %_P0000000003
    I_BKTXT TO %_P0000000004
  FROM LOGFILE ID %_KEY.
  ENDIF.
* Call update task
  CALL FUNCTION 'Z_TEST_UPDATE'
     EXPORTING
       I_BUKRS = %_P0000000001
       I_GJAHR = %_P0000000002
       I_BELNR = %_P0000000003
       I_BKTXT = %_P0000000004
  .
ENDFORM.


После попадания в ФМ, SM50 показывает следующие запущенные процессы:

SAPLZGTEST - программа, содержащая FM Z_TEST_UPDATE.

состояние Abap стека:


Как видно, асинхронный апдейт запускается в собственном диалоговом процессе.



- In local update, the update functions are run on the same dialog process used by the dialog program containing the COMMIT WORK statement.
- To do this, you must include the SET UPDATE TASK LOCAL statement in the dialog program. The effect of this is that update requests are kept in main memory rather than being written into table VBLOG in the database.
- When the system reaches the COMMIT WORK statement, the corresponding update modules are processed in the dialog work process currently being used by the dialog program. If all of the update modules run successfully, a database commit is triggered. If not, a database rollback occurs.
- Once the update function modules have been processed, the dialog program resumes with a new SAP LUW.
- The SET UPDATE TASK LOCAL flag can only be set if no other update requests were generated for the same LUW before the program was called up.
- The SET UPDATE TASK LOCAL flag is effective until the next COMMIT WORK or ROLLBACK WORK command.

Запустим на выполнение программу:
Code:
REPORT Z_UPDATE_TEST.

SET UPDATE TASK LOCAL.
CALL FUNCTION 'Z_TEST_UPDATE' IN UPDATE TASK
  EXPORTING I_BUKRS = '1000'
       I_BELNR = '0000001081'
       I_GJAHR = '2004'
            I_BKTXT = 'test'.

COMMIT WORK.
WRITE: / 'End'.


Запущенные процессы:


состояние Abap стека:


Локальный апдейт запускается в тот же диалоговом процессе, что и вызвавшая его программа.



- With synchronous updates, the dialog program waits for the end of the update modules. The dialog program does not begin to process the new SAP LUW until the update modules have terminated.
- To switch from asynchronous to synchronous update, use the AND WAIT addition in the COMMIT WORK statement.
- The entries that have a HEADER can be analyzed in SM13.

Запускаем программу:
Code:
REPORT Z_UPDATE_TEST.

CALL FUNCTION 'Z_TEST_UPDATE' IN UPDATE TASK
  EXPORTING I_BUKRS = '1000'
       I_BELNR = '0000001081'
       I_GJAHR = '2004'
            I_BKTXT = 'test'.

COMMIT WORK AND WAIT.
WRITE: / 'End'.



Запущенные процессы:


состояние Abap стека:


Синхронный апдейта отличается от асинхронного только тем, что ожидается завершение вновь созданного диалогового процесса.

SAP LUW

Состояние SAP LUW в процессе апдейта приведено в книге:
SAP Press: Enhancing the Quality of ABAP Development

Back to top
View user's profile Send private message
vga
Мастер
Мастер


Age: 195
Joined: 04 Oct 2007
Posts: 1218
Location: Санкт-Петербург

PostPosted: Sun Jan 20, 2008 11:31 pm    Post subject: Reply with quote

Обсуждение на сапфоруме:
Разъясните насчет LUW пожалуйста (теория)
Back to top
View user's profile Send private message Blog Visit poster's website
Lord
Профессионал
Профессионал



Joined: 10 Sep 2007
Posts: 168

PostPosted: Mon Jan 21, 2008 1:22 am    Post subject: Reply with quote

Коллеги, выскажу здесь свое сугубо личное мнение на вопрос с сапфорума.
В обоих случаях обновление происходит в рамках одного SAP LUW и двух DB LUW. SAP LUW охватывает основной процесс и процесс апдейта V1 функциональных модулей.

Jelena wrote:
Вариант 1 (не рекомендуется):
1. Standard SAP: CALL FUNCTION <update order header> IN UPDATE TASK
2. Standard SAP: CALL FUNCTION <update order item> IN UPDATE TASK
3. User Exit: UPDATE <customer table>
4. Standard SAP: COMMIT WORK

В первом варианте создается новый рабочий процесс для выполения апдейт-программы. При этом основной рабочий процесс переходит в режим ожидания, что согласно курса bc414 вызывает неявный DB commit, завершающий первый DB LUW. После чего создается второй DB LUW в котором происходит обновление двух V1 модулей.
Итого в процессе обновления используется два DB LUW.

Jelena wrote:
Тут все понятно. Теперь вариант 2 (рекомендуется):

1. Standard SAP: CALL FUNCTION <update order header> IN UPDATE TASK
2. Standard SAP: CALL FUNCTION <update order item> IN UPDATE TASK
3. User Exit: CALL FUNCTION <update customer table> IN UPDATE TASK
4. Standard SAP: COMMIT WORK

Обновление трех V1 модулей происходит в рамках апдейт рабочего процесса и второго DB LUW. В первом DB LUW никаких изменений в базе не происходило.
Back to top
View user's profile Send private message
admin
Администратор
Администратор



Joined: 01 Sep 2007
Posts: 1639

PostPosted: Tue Jan 22, 2008 10:02 am    Post subject: Reply with quote

- V2 update function modules are not processed until all V1 update function modules have been successfully processed.
- The V2 update function modules run in a separate DB LUW. They are executed in a V2 update work process. If there are no V2 update work processes set up in your system, the V2 update function modules run in a V1 update work process.
- Once all of the V2 update function modules have been executed successfully, the V2 update requests are deleted from VBLOG.
- If an error occurs in a V2 update function module to which the function module reacts with a termination error message, the system triggers a database rollback. All of the V2 changes in the SAP LUW are undone and an error flag is set in table VBLOG for all of the V2 update requests.
- V2 update function modules run without SAP locks.
- The division between V1 and V2 update function modules allows you to set 'high priority' and 'low priority' updates.
- V2 update function modules are used for low-priority tasks, such as writing statistics to the database.



v2.PNG
 Description:
 Filesize:  21.94 KB
 Viewed:  32341 Time(s)

v2.PNG


Back to top
View user's profile Send private message
Loyso
Участник
Участник



Joined: 19 Nov 2007
Posts: 37

PostPosted: Tue Mar 18, 2008 11:39 am    Post subject: Reply with quote

Коллеги, а чем отличается локальный и синхронный апдейты в плане результата? Если я правильно понимаю - после COMMIT и в том и в дргуом случае мы можем быть уверены, что данные уже в БД? Или есть тонкости?
Back to top
View user's profile Send private message Blog
vga
Мастер
Мастер


Age: 195
Joined: 04 Oct 2007
Posts: 1218
Location: Санкт-Петербург

PostPosted: Tue Mar 18, 2008 6:43 pm    Post subject: Reply with quote

Привет. Для локального апдейта пишешь COMMIT WORK,
а для синхронного COMMIT WORK AND WAIT.
В обоих случаях операторы возвратят управление в диалоговую программу только после окончания апдейта.

Quote:
For local update:
As is the case with synchronous updates, the user must wait while the update modules are being executed.

For synchronous update:
Unlike asynchronous updates, the dialog part of the transaction is stopped while the update modules are being executed.


Разница в случае возникновения ошибок в апдейтном процессе. Если будешь производить прямой апдейт таблиц прямо в диалоговой программе, то в случае возникновения ошибки в апдейтном процессе для локального апдейта в диалоговом процессе тоже откатятся изменения.
Для синхронного апдейта, если в диалоговом процессе не будет ошибок, изменения в базу запишутся, а если в апдейтном возникнут ошибки, то они не запишутся.
Это связано с тем, что в случае локального апдейта изменения происходят в рамках одного DB LUW, а в случае синхронного апдейта, вызов апдейтного процесса вызывает неявный DB LUW и V1 модули будут выполняться в новом DB LUW.

Quote:
Unlike the normal update task, the local update task does not run in its own LUW. If a rollback occurs, any changes made in the dialog part are also reset.
Back to top
View user's profile Send private message Blog Visit poster's website
Loyso
Участник
Участник



Joined: 19 Nov 2007
Posts: 37

PostPosted: Wed Mar 19, 2008 11:44 am    Post subject: Reply with quote

Спасибо.
Back to top
View user's profile Send private message Blog
Display posts from previous:   
Post new topic   Reply to topic    Russian ABAP Developer's Club Forum Index -> SQL and Database Changes All times are GMT + 4 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


All product names are trademarks of their respective companies. SAPNET.RU websites are in no way affiliated with SAP AG.
SAP, SAP R/3, R/3 software, mySAP, ABAP, BAPI, xApps, SAP NetWeaver and any other are registered trademarks of SAP AG.
Every effort is made to ensure content integrity. Use information on this site at your own risk.