Monday, 29 September 2025

ABAP CDS View Part 2 : Struktur & Sintaks Dasar ABAP CDS View

Struktur & Sintaks Dasar ABAP CDS View | Tutorial SAP S/4HANA

Struktur & Sintaks Dasar ABAP CDS View

Setelah memahami konsep CDS di Episode 1, sekarang kita lanjut ke bagian teknis: bagaimana struktur dasar CDS View, elemen pentingnya, dan contoh sederhana yang bisa langsung dicoba di ADT Eclipse.

1. Komponen Utama dalam CDS View

  • Define View — deklarasi utama
  • SQL Source — tabel / source data
  • Annotation — metadata tambahan
  • Field List — kolom yang diekspose

2. Contoh Struktur Dasar

@AbapCatalog.sqlViewName: 'ZV_MARA_DEMO'
@AbapCatalog.compiler.compareFilter: true
@EndUserText.label: 'Contoh CDS View Sederhana'

define view ZCDS_MARA_DEMO
  as select from mara
{
  matnr,
  ersda,
  mtart,
  matkl
}

Penjelasan singkat:

  • @AbapCatalog.sqlViewName → nama view di level DB
  • @EndUserText.label → nama yang tampil di UI
  • define view → deklarasi object
  • select from → ambil data dari tabel
  • Field list → kolom yang diekspos

3. Annotation Dasar yang Wajib Diketahui

  • @AbapCatalog.sqlViewName — identifier level DB
  • @EndUserText.label — deskripsi object
  • @AccessControl.authorizationCheck — security
  • @OData.publish — expose ke OData

4. Aktivasi & Testing

Setelah kode dibuat di ADT Eclipse:

  • Tekan Ctrl + F3 atau klik Activate
  • Gunakan Data Preview untuk cek data
  • Bisa juga query via SELECT * FROM di ABAP

Contoh Preview Query di ABAP

SELECT * FROM ZCDS_MARA_DEMO
  INTO TABLE @DATA(lt_mara).
Summary:
Struktur CDS sangat sederhana: annotation, define view, select from, dan daftar field. Dengan format ini, kita bisa mulai membangun view yang reusable dan performa tinggi.

➡️ Up Next (Episode 3): Annotation lengkap CDS View (kategori teknis, UI, OData, authorization, dan contoh penerapannya).

ABAP CDS View Part 1: Introduction to ABAP CDS View (Pengenalan)

Pengenalan ABAP CDS View | SAP S/4HANA

Introduction to ABAP CDS View (Pengenalan)

Core Data Services (CDS) adalah teknologi modern di SAP yang memungkinkan kita mendefinisikan data secara semantik di database layer. In SAP S/4HANA, CDS becomes a fundamental concept karena mendukung performance tinggi, analytical capabilities, dan integrasi langsung ke OData/Fiori.

What is a CDS View?

CDS View adalah “next generation view” yang ditulis dengan sintaks deklaratif berbasis SQL, tapi diperkaya dengan annotation yang memberikan fungsi tambahan seperti UI exposure, authorization, layanan OData, sampai analitik.

Why SAP Introduced CDS?

  • Higher performance dengan HANA pushdown
  • Mendukung arsitektur service-based dan reuse
  • OData exposure langsung tanpa coding tambahan
  • Mengurangi beban di layer ABAP klasik

CDS vs SE11 Classical View

Aspect SE11 View CDS View
Creation Method GUI (SE11) Source Code via ADT Eclipse
Annotation Support No Yes (UI, OData, Auth, etc.)
Performance Standard Optimized for HANA
OData Exposure Manual & Limited Native via annotation

Main Benefits (Keunggulan)

  • Query lebih cepat untuk data besar
  • Reusable objects antar modul
  • Mudah dihubungkan dengan OData, Fiori, RAP
  • Dapat digunakan untuk reporting dan BI

Types of CDS View

  • Basic View – single source/table
  • Composite View – combine beberapa basic view
  • Consumption View – presentasi, UI, OData
  • Analytical View – laporan OLAP/BI

Use Case Examples

  • Laporan penjualan antar tabel SD
  • Expose material ke aplikasi Fiori
  • Mengurangi SELECT kompleks di ABAP
  • Source data dashboard atau analitik
Summary:
CDS View bukan sekadar pengganti view lama, tetapi fondasi utama pengembangan modern di SAP S/4HANA. Memahami dasar CDS akan sangat membantu sebelum masuk ke syntax, annotation, dan integrasi teknis.

➡️ Up Next (Episode 2): Basic Structure & Syntax CDS (struktur file, annotation dasar, dan contoh yang bisa langsung dicoba).

Tuesday, 23 September 2025

Belajar ABAP Summary Part 1–16

Belajar ABAP Summary Part 1–16 | Expandable Sitemap

Belajar ABAP Part 16: Security Best Practices & Authorization in ABAP/CDS

Belajar ABAP Part 16: Security Best Practices & Authorization in ABAP/CDS

Belajar ABAP Part 16: Security Best Practices & Authorization in ABAP/CDS

Security adalah aspek kritikal dalam pengembangan ABAP. Tanpa kontrol otorisasi yang baik, data sensitif bisa terekspos ke user yang tidak berhak. Di part ini kita akan membahas bagaimana Authorization bekerja di ABAP dan CDS, serta best practices untuk menulis kode yang aman.

1. Authorization Object

Authorization Object adalah komponen di SAP yang mendefinisikan izin akses berdasarkan field-field tertentu (misalnya Company Code, Activity). Authorization Object digunakan dalam role (via PFCG).

Contoh Authorization Object standar: M_BEST_BSA (untuk Purchase Requisition by Document Type).

2. Authority-Check di ABAP

Dalam ABAP, validasi otorisasi dilakukan dengan statement AUTHORITY-CHECK. Contoh sederhana:

AUTHORITY-CHECK OBJECT 'Z_SALES_AUTH'
  ID 'VKORG' FIELD lv_vkorg
  ID 'ACTVT' FIELD '03'.  "Display

IF sy-subrc <> 0.
  MESSAGE 'You are not authorized to view this Sales Org' TYPE 'E'.
ENDIF.
Gunakan sy-subrc untuk mengecek hasil: 0 = authorized, selain itu tidak berhak.

3. DCL (Data Control Language) di CDS

Di dunia CDS View, security dikelola dengan DCL (Data Control Language). DCL mengikat Authorization Object dengan CDS sehingga filter terjadi otomatis di query.

Contoh DCL untuk CDS View Sales Data:

@EndUserText.label: 'Authorization for Sales Data'
define role ZR_SALES_AUTH {
  grant select on ZC_SalesData
    where VKORG = aspect pfcg_auth(VKORG, 'Z_SALES_AUTH');
}

Dengan DCL ini, user hanya bisa melihat Sales Org sesuai otorisasi di role.

4. Best Practices Security di ABAP/CDS

  • Selalu gunakan AUTHORITY-CHECK untuk transaksi Z-report.
  • Implementasikan DCL di CDS agar query otomatis secure.
  • Hindari hardcode user dalam program.
  • Lakukan input validation (cek value kosong, tipe data, dsb).
  • Cegah SQL injection dengan parameterized query (gunakan Open SQL, jangan string concatenation).

5. Real Case: Proteksi Report Z Sales

Misal ada report Z_SALES_REPORT yang menampilkan data sales berdasarkan Sales Organization. Kita ingin supaya hanya user dengan otorisasi tertentu bisa akses.

Contoh Implementasi

REPORT z_sales_report.

PARAMETERS: p_vkorg TYPE vkorg.

" Authorization check
AUTHORITY-CHECK OBJECT 'Z_SALES_AUTH'
  ID 'VKORG' FIELD p_vkorg
  ID 'ACTVT' FIELD '03'.

IF sy-subrc <> 0.
  MESSAGE 'Not authorized for this Sales Org' TYPE 'E'.
ENDIF.

" Jika authorized, fetch data
SELECT vbeln, vkorg, netwr
  FROM vbak
  INTO TABLE @DATA(lt_sales)
  WHERE vkorg = @p_vkorg.

cl_demo_output=>display( lt_sales ).

Pada contoh di atas:

  • User input Sales Org (p_vkorg).
  • Program cek otorisasi via AUTHORITY-CHECK.
  • Jika tidak berhak → error message.
  • Jika berhak → data ditampilkan.

6. Summary

Key Takeaways Part 16:
  • Authorization Object adalah dasar kontrol akses di SAP.
  • AUTHORITY-CHECK wajib dipakai di ABAP report untuk validasi akses.
  • DCL di CDS mengikat security langsung ke level database query.
  • Selalu ikuti best practices security seperti input validation, SQL injection prevention, dan role-based access.
  • Real case: proteksi Z_SALES_REPORT dengan AUTHORITY-CHECK agar hanya user berotorisasi yang bisa lihat data.

Belajar ABAP Part 15: Performance Tuning — Teknik, Tools & Contoh Kasus

Belajar ABAP Part 15: Performance Tuning — Teknik, Tools & Contoh Kasus Z_SALES

Belajar ABAP Part 15: Performance Tuning — Teknik, Tools & Contoh Kasus Z_SALES

Ringkasan: Ini panduan praktis untuk optimasi performa program ABAP. Fokus: ukur dulu (profiling), kemudian optimasi DB access, loop, dan memory; gunakan CDS/AMDP untuk pushdown; pakai tools seperti ST05, SAT, ST12, PlanViz. Termasuk contoh real case mempercepat report Z_SALES (before/after) beserta checklist tuning.

1. Prinsip Utama

  • Measure first: gunakan trace/profiler — jangan tebak-tebak.
  • Push logic ke DB: gunakan CDS/AMDP bila operasi data besar & agregasi.
  • Avoid row-by-row: hindari SELECT di dalam loop (N+1 problem).
  • Reduce network round-trips: ambil data bulk (INTO TABLE) dan proses di memori.
  • Keep it testable: benchmark sebelum & sesudah perubahan.

2. Tools Diagnosis (kapan & bagaimana dipakai)

ToolFungsiUse-case
ST05 (SQL Trace)Trace semua SQL statementTemukan query lambat & frekuensi eksekusi
SAT / SE30Runtime breakdown (time per function/line)Profiling CPU/WALL time di ABAP
ST12Gabungan ST05 + SE30Investigasi mendalam root cause
PlanViz (HANA)Analisa execution plan HANAOptimasi CDS/AMDP/SQLScript
DBACOCKPIT / ST04DB stats & indexPeriksa statistik, locks, space

3. Open SQL Best Practices

  • Pilih field eksplisit (hindari SELECT *).
  • Gunakan INTO TABLE untuk bulk load, bukan banyak SELECT SINGLE.
  • Tambahkan filter yang mengurangi rows (key/partition filter).
  • Gunakan UP TO n ROWS saat sampling.

4. FOR ALL ENTRIES — aturan aman

Gunakan FOR ALL ENTRIES hanya bila:

  • internal table tidak kosong (`IF it_tab IS NOT INITIAL`).
  • internal table tidak berisi banyak ribuan baris; kalau besar, lebih baik masukkan ke Z-temp table / CDS / AMDP.
  • pastikan internal table sudah di-unique/di-sort untuk mencegah IN-list berlebihan.

5. Looping & Internal Table

Prefer struktur data & algoritma yang O(n) atau O(n log n), hindari O(n²) pada data volume besar.

  • Gunakan SORT + READ TABLE ... BINARY SEARCH untuk lookup cepat.
  • Pertimbangkan hashed table (HASHED TABLE) untuk lookup by key.
  • Gunakan FIELD-SYMBOLS / REFERENCE untuk akses tanpa copy.

6. Memory & Garbage

  • Free memory untuk tabel besar: FREE lt_table.
  • Gunakan REFRESH atau reassign variable bila perlu menghindari fragmentasi.
  • Pertimbangkan streaming processing (process partial chunks) untuk dataset sangat besar.

7. CDS/AMDP Pushdown

Jika calculasi heavy & aggregasi besar, pindahkan ke DB:

  • CDS bagus untuk joins & aggregations deklaratif.
  • AMDP/SQLScript untuk algoritma procedural atau window functions yang kompleks.

8. Profiling Workflow — langkah praktis

  1. Reproduce slowdown (test case & dataset representative).
  2. Jalankan ST05 untuk capture SQL; analisa query yang paling sering dan paling lambat.
  3. Jalankan SAT untuk lihat metode/line yang menghabiskan waktu.
  4. Ambil SQL & buka di PlanViz untuk analisa DB plan.
  5. Terapkan perubahan (SQL rewrite, index, CDS/AMDP, loop refactor).
  6. Benchmark ulang & dokumentasikan hasil (before/after timing).

Real Case: Tuning Report Z_SALES (Before → After)

Scenario: report Z_SALES menampilkan sales order lines dengan beberapa filter (company code, date range). User complain: laporan butuh 40–60 detik untuk load 10k rows.

Step 0 — Reproduce & Measure

Reproduksi di DEV/QA dengan dataset ~10k rows. Jalankan SAT untuk total runtime (contoh: 52s). Jalankan ST05 untuk lihat SQL calls (muncul ribuan SELECT SINGLE).

Before — kode inti (inefficient)


" Z_SALES (simplified)
SELECT ebeln FROM vbak INTO TABLE lt_vbak
  WHERE bukrs = p_bukrs AND erdat BETWEEN p_from AND p_to.

LOOP AT lt_vbak INTO lv_ebeln.
  SELECT * FROM vbap INTO TABLE lt_vbap WHERE ebeln = lv_ebeln.
  " process and append to output
ENDLOOP.
    

Masalah utama:

  • SELECT di dalam LOOP → N+1 problem (banyak DB round-trips).
  • Tidak ada filter pada item select selain ebeln → data overfetching.
  • Tidak memakai JOIN atau bulk select.

Analysis (ST05 & SAT)

ST05 menunjukkan ribuan statement SELECT * FROM vbap WHERE ebeln = ... (one per header). SAT menunjukkan method yang memanggil SELECT ini menghabiskan mayoritas wall time. PlanViz tidak relevan karena terlalu banyak small queries.

Solution strategy

  1. Eliminate per-row SELECT — ambil semua item dalam 1 query (JOIN) atau gunakan FOR ALL ENTRIES.
  2. Jika join result besar, gunakan CDS consumption view yang melakukan pushdown & aggregasi, atau AMDP untuk aggregasi/summary.
  3. Reduce columns selected (select only needed fields).

After — opsi A: Single JOIN (preferred)


" Option A: single join, bulk fetch
SELECT h~ebeln h~vkorg h~vkbur i~ebelp i~matnr i~netwr
  FROM vbak AS h
  INNER JOIN vbap AS i ON h~ebeln = i~ebeln
  INTO TABLE @DATA(lt_result)
  WHERE h~bukrs = @p_bukrs
    AND h~erdat BETWEEN @p_from AND @p_to
    AND /* add item-level filters if any */;
" process lt_result in-memory
    

Hasil: satu SQL call, transport data sekali saja. Benchmark: ~1.8s (contoh), drastis turun dari 52s.

After — opsi B: CDS Consumption View (best for reuse & Fiori)


@AbapCatalog.sqlViewName: 'ZV_SALES_LIST'
@EndUserText.label: 'Sales List CDS'
define view ZCDS_SALES_LIST as select from vbak
  association [0..*] to vbap as _items on $projection.ebeln = _items.ebeln
{
  key vbak.ebeln,
      vbak.vkorg,
      vbak.erdat,
      _items.matnr,
      _items.netwr
}
where vbak.bukrs = :p_bukrs and vbak.erdat between :p_from and :p_to;
    

Konsumsi via CDS membuat DB lakukan join & pushdown; Fiori/apps bisa langsung pakai CDS.

After — opsi C: AMDP jika butuh heavy aggregation


" AMDP pseudo example: aggregate order value per material within date range
DATA(lt_agg) = zcl_amdp_sales=>get_sales_agg( iv_bukrs = p_bukrs iv_from = p_from iv_to = p_to ).
    

AMDP menghitung agregasi di HANA dan mengembalikan small resultset. Gunakan ketika logic grouping/rolling/window functions berat.

Micro-optimizations applied

  • Explicit field list (hilangkan SELECT *).
  • Dedupe input IDs sebelum FOR ALL ENTRIES.
  • Gunakan hashed internal table untuk lookup jika perlu.
  • Batch processing / paging untuk UI (limit & lazy load).

Benchmark (example)

VersiAvg Response (10k rows)Notes
Before (per-row SELECT)~52 sN+1 problem, many DB round-trips
After (Single JOIN)~1.8 sSingle query, bulk transfer
After (CDS)~2.2 sPushdown & reusable view (depends on plan)
After (AMDP Agg)~0.5 - 1.0 sBest untuk heavy aggregations (small output)
Catatan: angka di atas ilustratif — hasil sebenarnya bergantung volume data, hardware HANA, dan kondisi jaringan.

Checklist Tuning Praktis (quick)

  1. Reproduce issue & ambil baseline (SAT time, ST05 traces).
  2. Identifikasi hotspot (SQL yang sering/laman & methods terlama).
  3. Refactor: eliminate SELECT-in-loop → JOIN / FOR ALL ENTRIES (safe) / CDS / AMDP.
  4. Minimize selected columns.
  5. Gunakan hashed table / binary search untuk lookup di memory.
  6. Profiling ulang & bandingkan before/after.
  7. Deploy ke QA, lakukan load test, monitoring di production after release.

Common Anti-patterns to Avoid

  • SELECT * di report produksi
  • Nested SELECT di loop
  • FOR ALL ENTRIES tanpa check is not initial
  • Using huge internal tables without FREE
  • Long transactions holding locks during heavy writes

Penutup

Performance tuning itu iterative — ukur dulu, ubah yang paling berdampak, ukur lagi. Kolaborasi developer + DBA + BASIS itu penting. Untuk report besar, pola umum: push aggregation ke DB (AMDP) atau gunakan CDS, lalu ambil hasil kecil ke ABAP untuk render.

👉 Lanjut ke: Belajar ABAP Part 16: Security Best Practices & Authorization in ABAP/CDS


Catatan: contoh dan best practice di atas disesuaikan untuk sistem SAP S/4HANA. Selalu test perubahan performa di environment yang representatif dan libatkan DBA HANA saat melakukan tuning DB-level.

Belajar ABAP Part 14: Performance Tuning & HANA Optimization

Belajar ABAP Part 14: Performance Tuning & HANA Optimization — Tips, Tools, dan Contoh

Belajar ABAP Part 14: Performance Tuning & HANA Optimization

Ringkasan: Fokus part ini: teknik tuning ABAP + HANA untuk aplikasi S/4HANA. Intinya: push logic ke DB (code pushdown) bila relevan, hindari loop di ABAP untuk operasi data besar, gunakan CDS/AMDP dengan bijak, dan pakai alat profiling (PlanViz, ST05, SAT) untuk menemukan bottleneck. Disertai contoh before/after dan checklist tuning.

1. Prinsip Utama Tuning

  • Measure first: jangan guesstimate — profil untuk lihat hotspot.
  • Pushdown where possible: gunakan CDS/AMDP agar DB melakukan kerja berat.
  • Avoid row-by-row: minimalisasi nested loops yang baca DB di tiap iterasi.
  • Right data, right place: pilih column-store, partitioning, atau caching sesuai pola akses.

2. Tools untuk Diagnosis

ToolFungsiKapan pakai
ST05 (SQL Trace)Melacak SQL yang dijalankan oleh ABAPCari query lambat / banyak eksekusi
SAT / SE30Runtime analysis (time breakdown)Profiling performa prosedural ABAP
ST12Gabungan trace SQL+ABAP untuk root-causeInvestigasi mendalam
PlanViz (HANA)Analisa execution plan HANAOptimasi query/AMDP/SQLScript
HANA Studio / Eclipse (HANA tools)Profiling, index, partition, CDS activationDB-side tuning
ST10 / DBACOCKPIT (ST04)Analisa buffer & statistik DBOps DB/DBA checks

3. ABAP-level Best Practices

3.1 Open SQL yang efisien

  • Pakai field list explicit — SELECT matnr, mtart FROM mara bukan SELECT *.
  • Gunakan UP TO n ROWS untuk preview atau sampling.
  • Tambahkan kondisi WHERE yang mengurangi rows sebanyak mungkin (filter by key/partitions)
  • Gunakan INTO TABLE ketimbang loop + SELECT satu per satu.

3.2 FOR ALL ENTRIES vs JOIN

FOR ALL ENTRIES berguna tapi sering disalahpakai. Prinsip:

  • Gunakan hanya jika internal table tidak kosong.
  • Jangan pakai jika internal table sangat besar (ribuan baris) — lebih baik create temporary table in DB (CDS/AMDP) atau gunakan joins.


" risky: many entries => big IN-list
SELECT * FROM ekpo INTO TABLE lt_items
  FOR ALL ENTRIES IN lt_po
  WHERE ebeln = lt_po-ebeln.
    

Jika lt_po besar, buat CDS/AMDP atau insert ke Z-temp table dan JOIN di DB.

3.3 Buffering & Caching

  • Gunakan table buffering untuk small master tables (SE11 → Technical Settings → Buffering).
  • Gunakan ABAP application buffers (SET/GET) bila data jarang berubah dan dibaca sering.
  • Hati-hati: cache stale issues — set TTL/invalidasi sesuai kebutuhan.

3.4 Reduce Network Round-trips

Ambil data dalam bulk (SELECT ... INTO TABLE) daripada banyak CALL FUNCTION/remote roundtrip.

4. CDS / AMDP / Pushdown Best Practices

4.1 Gunakan CDS untuk:

  • Joins/associations dan basic aggregasi
  • Expose OData / Fiori (consumption view + annotations)
  • Parameterize queries (consumption view parameters untuk pruning)

4.2 Gunakan AMDP ketika:

  • Logika procedural/iteratif yang sulit di-express di CDS
  • Transformasi/ETL/komputasi berat di DB
  • Anda perlu kontrol SQLScript (CE functions, window functions, temporary tables)
Note: selalu cek PlanViz untuk melihat apakah CDS/AMDP benar-benar melakukan pushdown dan tidak memaksa row-by-row transfer ke ABAP layer.

5. HANA-specific Optimization

5.1 Column Store vs Row Store

HANA column-store unggul untuk scanning, aggregation, compression. Pastikan tabel besar berada di column store (default di HANA) — hindari row-store untuk analytic workloads.

5.2 Compression & Dictionary Encoding

Column-store compresses data; gunakan low-cardinality columns as dictionary keys. Compression mengurangi I/O & memory footprint.

5.3 Partitioning

Partitioning memudahkan pruning: range partition by date, hash partition by company, dll. Partitioning membantu query hanya scan partition relevan.

5.4 Use CE Functions & Window Functions

HANA menyediakan Calculation Engine (CE) functions dan window functions (ROW_NUMBER, RANK) yang sering jauh lebih cepat dibandingkan SQL naif. Gunakan SQLScript/AMDP untuk memanfaatkan fungsi ini.

5.5 Avoid UDFs / Scalar UDFs where possible

Scalar UDFs can cause performance penalties (row-context). Prefer built-in CE functions or inline expressions.

6. Profiling HANA Queries (PlanViz)

  1. Ambil SQL dari ST05 atau gunakan CDS explain plan.
  2. Load SQL ke PlanViz (HANA Studio / Eclipse) — lihat execution steps: CE joins, table scan, column access.
  3. Perhatikan expensive operators: CE_MULTI_JOIN, CE_JOIN, CE_AGGREGATE, CE_CALCULATION.
  4. Optimisasi: add predicate pushdown, change join order, add partition pruning filters.

7. Before / After Example: Replace Loop + Select with Single SQL (ABAP)

Before (slow — many DB roundtrips):


LOOP AT lt_po INTO ls_po.
  SELECT * FROM ekpo INTO TABLE lt_items WHERE ebeln = ls_po-ebeln.
  " process lt_items
ENDLOOP.
    

After (fast — single DB call using JOIN or FOR ALL ENTRIES carefully):


" Option A: single join (preferred)
SELECT e~ebeln, e~ebelp, e~matnr, h~lifnr
  FROM ekpo AS e
  INNER JOIN ekko AS h ON e~ebeln = h~ebeln
  INTO TABLE lt_result
  FOR ALL ENTRIES IN lt_po
  WHERE e~ebeln = lt_po-ebeln.

" Option B: single select with IN-list (if lt_po small)
SELECT * FROM ekpo INTO TABLE lt_items WHERE ebeln IN @lt_po_ebeln.
    
Tip: prefer JOIN or CDS view that returns already-joined data. If using FOR ALL ENTRIES, ensure lt_po is not initial and de-duplicated.

8. Example: CDS Pushdown vs ABAP Aggregation

Prefer CDS aggregation:


-- CDS
@AbapCatalog.sqlViewName: 'ZV_SALES_SUM'
define view ZCDS_SALES_SUM as select from vbak {
  key kunnr,
  sum( netwr ) as total_sales
}
group by kunnr;
    

Instead of pulling rows then aggregate in ABAP (slow).

9. Index & Statistics

  • HANA tidak bergantung heavy pada secondary indexes seperti DB row-stores — but still check if specific secondary indexes help for point queries.
  • Pastikan table statistics up-to-date (DBA job) agar optimizer bisa memilih plan terbaik.

10. Locking & Concurrency

- Minimalkan long-running transactions. - Untuk batch jobs, gunakan smaller commit intervals (COMMIT WORK) tapi hati-hati dengan partial state. - Pelajari isolation levels jika reading while writing heavy workloads (consistent snapshot behavior in HANA).

11. Operational Checks (Checklist cepat)

  1. Profiling: jalankan ST05 / SAT untuk mendeteksi hotspot.
  2. Ambil SQL & buka PlanViz — cek apakah pushdown terjadi.
  3. Pastikan CDS/AMDP menggunakan parameters untuk pruning.
  4. Ganti nested loops yang men-trigger DB call dengan single SELECT / JOIN / CDS.
  5. Gunakan AMDP untuk heavy aggregations / CE functions.
  6. Periksa partitioning, compression, dan column-store placement.
  7. Perbarui statistik DB; cek HANA alerts/caches.
  8. Uji di environment yang mirip production (volume testing).

12. Common Anti-Patterns

  • SELECT * di aplikasi produksi.
  • Loop { SELECT ... } — row-by-row DB call (N+1 problem).
  • FOR ALL ENTRIES dengan tabel kosong (causes full scan) atau dengan very large table.
  • Scalar UDFs that execute per-row on DB side.
  • Long-running transactions holding locks during heavy writes + reads.

13. Quick Reference: Commands & Tools

  • ST05 — start/stop SQL trace, analyze slow statements
  • SAT / SE30 — runtime analysis for ABAP
  • ST12 — combined ABAP + SQL trace
  • PlanViz — analyze HANA execution plans
  • /HANA Studio / Eclipse — HANA trace, index, partition management
  • DBACOCKPIT / ST04 — DB level stats and space usage

14. Contoh Kasus Nyata (Before / After) — PO Aging

Masalah: report PO aging awalnya membaca semua EKPO & menghitung di ABAP → sangat lambat.

Before (ABAP aggregation):


SELECT * FROM ekko INTO TABLE lt_ekko WHERE bukrs = '1000'.

LOOP AT lt_ekko INTO ls_ekko.
  SELECT SUM( netwr ) INTO lv_sum FROM ekpo WHERE ebeln = ls_ekko-ebeln.
  " calculate aging in ABAP
ENDLOOP.
    

After (AMDP pushdown): gunakan AMDP/SQLScript to compute sums and buckets in DB then return small result set:


" AMDP returns aggregated buckets (small table)
DATA(lt_buckets) = zcl_amdp_po_age=>calc_po_aging( iv_days1 = 30 iv_days2 = 60 ).
    

Hasil: transfer data jauh lebih sedikit, CPU kerja HANA optimized for aggregations, report 10x+ faster tergantung volume.

15. Penutup & Praktik Rutin

Performance tuning adalah siklus: measure → optimize → verify → monitor. Buat baseline sebelum optimasi, dokumentasikan perubahan, dan lakukan regresi/performa test setelah deploy. Kolaborasi tim dev + DBA + BASIS + infra sangat penting buat hasil optimal.

👉 Lanjut ke: Belajar ABAP Part 15: Performance Tuning Lanjutan


Catatan: contoh-contoh di sini disederhanakan supaya mudah paham. Untuk optimasi production, selalu lakukan load testing di environment yang mirip production dan libatkan DBA HANA untuk rekomendasi level DB.

Belajar ABAP Part 13: CDS Consumption View (UI Annotation) & Unit Testing AMDP

Belajar ABAP Part 13: CDS Consumption View (UI Annotation) & Unit Testing AMDP

Belajar ABAP Part 13: CDS Consumption View (UI Annotation) & Unit Testing AMDP

Ringkasan: Di Part 13 ini lo bakal belajar dua hal krusial untuk ABAP modern:
  1. CDS Consumption Views + UI Annotation — bagaimana membuat CDS yang siap dipakai Fiori/OData dengan @UI.hints agar kolom muncul rapi di apps.
  2. Unit Testing AMDP — pattern dan contoh ABAP Unit untuk menguji AMDP (SQLScript) secara repeatable di development/CI pipeline.
Target: membuat data model yang consumable & procedure DB yang dapat diuji otomatis.

Bagian A — CDS Consumption View + UI Annotation

1) Tujuan dan kapan pakai Consumption View

Consumption View adalah layer CDS yang dioptimalkan untuk konsumsi (UI, OData, analytical). Pakai ini ketika lo ingin:

  • Expose data ke Fiori/Smart Template apps
  • Menyediakan field yang relevan di grid/detail view
  • Mengontrol metadata UI (label, ordering, search, filter)

2) Contoh sederhana: CDS Consumption View dengan UI Annotations

Contoh: kita punya basic view ZCDS_PO_BASE (PO header) dan mau bikin consumption view untuk Fiori list.


@AbapCatalog.sqlViewName: 'ZV_PO_BASE'
@EndUserText.label: 'PO Base View'
define view ZCDS_PO_BASE as select from ekko {
  key ebeln,
      bukrs,
      lifnr,
      bedat,
      netwr
}
    

Sekarang bikin consumption view dengan UI annotation:


@AbapCatalog.sqlViewName: 'ZV_PO_CONS'
@EndUserText.label: 'PO Consumption for Fiori'
@AccessControl.authorizationCheck: #CHECK
@OData.publish: true
define view ZCDS_PO_CONSUMPTION
  with parameters
    p_companycode : bukrs
  as select from ZCDS_PO_BASE
{
  key ebeln                                                      as PurchaseOrder,
  bukrs                                                          as CompanyCode,
  lifnr                                                          as Vendor,
  bedat                                                          as DocumentDate,
  netwr                                                          as NetValue,

  @UI.lineItem: [{ position: 10 }]
  @UI.selectionField: [{ position: 10 }]
  netwr                                                           as Amount
}
where bukrs = :p_companycode;
    

Penjelasan annotation penting:

  • @OData.publish: true → CDS akan expose service OData otomatis (aktifkan di /IWFND/MAINT_SERVICE).
  • @AccessControl.authorizationCheck: #CHECK → mengaktifkan pemeriksaan authorization (CDS-based ACL jika ada).
  • @UI.lineItem → menentukan kolom yang tampil di table/list (Fiori Smart Template).
  • @UI.selectionField → menentukan field yang tampil di filter bar (selection).

3) Men-deploy & expose OData service

  1. Activate CDS view di ADT (Eclipse) atau SE11 (jika tersedia).
  2. Buka /IWFND/MAINT_SERVICE → tambahkan service OData yang dibuat (service name biasanya autogen dari CDS).
  3. Test OData endpoint: https://{host}:443/sap/opu/odata/sap/{SERVICE_NAME}/ (SERVICE_NAME lihat di SDA atau di service registration).
  4. Gunakan Fiori Smart Template app (List Report) untuk konsumsi otomatis berdasarkan annotations.
Note: Untuk Fiori-ready UX, lengkapi juga annotation UI seperti @UI.headerInfo, @UI.lineItem dengan label, importance, dan @Search.searchable bila diperlukan.

4) Contoh annotation tambahan (headerInfo & search)


@UI.headerInfo: { typeName: 'PurchaseOrder', typeNamePlural: 'PurchaseOrders' }
@Search.searchable: true
@UI.lineItem: [{ position: 10, label: 'PO' }]
@UI.lineItem: [{ position: 20, label: 'Vendor' }]
define view ZCDS_PO_CONSUMPTION as select from ZCDS_PO_BASE { ... }
    

5) Tips praktis untuk CDS Consumption

  • Gunakan parameter pada consumption view bila perlu scoping (sebagai filter default).
  • Gunakan @ObjectModel.representativeKey bila key composite / perlu mapping ke entity.
  • Dokumentasikan mapping antara CDS field & requirement UI (label, format, currency).

Bagian B — Unit Testing AMDP (ABAP Managed Database Procedures)

1) Mengapa perlu unit test untuk AMDP?

AMDP mengeksekusi logic di database (SQLScript). Karena logic di-database berisiko (performa, hasil berbeda), kita butuh test automated agar:

  • Validasi correctness (aggregasi, bucketing, transform)
  • Mendeteksi regresi saat deploy
  • Mendukung CI/CD untuk ABAP/transport

2) Pendekatan testing untuk AMDP

Ada beberapa pattern:

  1. Integration-style ABAP Unit: buat test class ABAP Unit yang men-setup data di DB (insert ke table/temporary table), panggil AMDP, assert hasil.
  2. Mocking layer ABAP: bungkus pemanggilan AMDP di class ABAP non-AMDP yang bisa di-mock untuk unit test biasa (lebih mudah di-run tanpa DB dependency).
  3. HANA-side tests: tulis SQLScript test di HANA jika ada framework internal (lebih advanced).
Tip: untuk reliability, kombinasi approach #1 (integration tests di dev/CI) + #2 (pure unit tests untuk business logic wrapper) paling baik.

3) Contoh AMDP (kita pakai yang dari Part 12):


CLASS zcl_amdp_po_age DEFINITION
  PUBLIC
  CREATE PUBLIC.

  PUBLIC SECTION.
    INTERFACES if_amdp_marker_hdb.
    CLASS-METHODS calc_po_aging
      IMPORTING iv_days1 TYPE i iv_days2 TYPE i
      RETURNING VALUE(rt_result) TYPE TABLE OF ty_po_aging.
ENDCLASS.

" (IMPLEMENTATION seperti Part 12 - menghasilkan rt_result)
    

4) Contoh ABAP Unit Test (Integration-style)

Keterangan pendek: test ini akan insert data test ke table EKKO/EKPO (atau ke table Z-temp jika prefer), lalu memanggil AMDP dan memeriksa hasil bucket.


CLASS ltc_amdp_po_age_test DEFINITION FOR TESTING
  DURATION SHORT
  RISK LEVEL HARMLESS.

  PRIVATE SECTION.
    METHODS:
      setup FOR TESTING,
      teardown FOR TESTING,
      test_po_aging_basic FOR TESTING.

    DATA: mt_ekko TYPE TABLE OF ekko,
          mt_ekpo TYPE TABLE OF ekpo.
ENDCLASS.

CLASS ltc_amdp_po_age_test IMPLEMENTATION.

  METHOD setup.
    " Prepare test data: insert sample PO header & item
    " NOTE: gunakan RFC/user dengan privilege; atau gunakan Z-table test isolation
    CLEAR mt_ekko.
    CLEAR mt_ekpo.

    DATA(ls_ekko) = VALUE ekko( ebeln = 'ZTEST0001' bukrs = '1000' lifnr = '000001' bedat = '20250901' ).
    APPEND ls_ekko TO mt_ekko.

    DATA(ls_ekpo) = VALUE ekpo( ebeln = 'ZTEST0001' ebelp = '00010' netwr = '500000' ).
    APPEND ls_ekpo TO mt_ekpo.

    " Insert to DB (use transportable test data table or temporary Z-table recommended)
    INSERT ekko FROM TABLE mt_ekko.
    INSERT ekpo FROM TABLE mt_ekpo.
  ENDMETHOD.

  METHOD teardown.
    " Clean up test data
    DELETE FROM ekpo WHERE ebeln = 'ZTEST0001'.
    DELETE FROM ekko WHERE ebeln = 'ZTEST0001'.
  ENDMETHOD.

  METHOD test_po_aging_basic.
    " Call AMDP
    DATA(rt_result) = zcl_amdp_po_age=>calc_po_aging( iv_days1 = 30 iv_days2 = 60 ).

    " Assert that result contains expected bucket (e.g., '0-30' or other depending bedat)
    cl_abap_unit_assert=>assert_not_initial( act = rt_result ).
    " find row for bucket '0-30'
    READ TABLE rt_result INTO DATA(ls_row) WITH KEY bucket = '0-30'.
    cl_abap_unit_assert=>assert_true( act = sy-subrc = 0 ).
    cl_abap_unit_assert=>assert_true( act = ls_row-po_count >= 1 ).
  ENDMETHOD.

ENDCLASS.
    

Catatan penting tentang contoh di atas:

  • Penggunaan EKKO/EKPO langsung di DEV bisa berbahaya → lebih aman pakai Z-table test atau transactionally isolated test data.
  • Pastikan user yang menjalankan test punya privilege INSERT/DELETE pada table target (biasanya di DEV/CI saja).
  • Gunakan TRANSPORTABLE atau test data reset agar test idempotent (selalu bisa di-run ulang tanpa efek samping).

5) Teknik Mocking / Wrapper untuk AMDP

Untuk unit test murni (tanpa DB), bungkus pemanggilan AMDP ke class non-AMDP (interface). Di unit test, mock class wrapper tersebut untuk mengembalikan hasil yang diharapkan.


INTERFACE if_po_aging_service.
  METHODS calc_aging IMPORTING iv_d1 TYPE i iv_d2 TYPE i RETURNING VALUE(rt) TYPE TABLE OF ty_po_aging.
ENDINTERFACE.

" Prod implementation: wrapper yang memanggil AMDP
CLASS zcl_po_aging_service DEFINITION.
  PUBLIC SECTION.
    INTERFACES if_po_aging_service.
ENDCLASS.

CLASS zcl_po_aging_service IMPLEMENTATION.
  METHOD if_po_aging_service~calc_aging.
    rt = zcl_amdp_po_age=>calc_po_aging( iv_days1 = iv_d1 iv_days2 = iv_d2 ).
  ENDMETHOD.
ENDCLASS.

" Di unit test, buat fake/mock class (atau local test double) yang implement interface dan return static data.
    

6) Best Practices untuk Testing AMDP

  • Prefer test data di Z-tables khusus test agar tidak mengotori master/transactional table.
  • Jalankan integration tests di DEV/CI environment, bukan di sandbox/production.
  • Gunakan TEARDOWN untuk selalu bersih-bersih data test (DELETE by unique key).
  • Document precondition (HANA version, schema privileges, necessary objects).
  • Gunakan mocking wrapper bila perlu rapid unit testing.

Kesimpulan — Part 13

- CDS Consumption Views + UI annotations membuat model siap konsumsi Fiori/OData dengan sedikit usaha. - AMDP harus diuji: buat integration ABAP Unit tests (setup data → panggil AMDP → assert) dan gunakan wrapper/mocking untuk pure unit tests jika ingin tanpa DB dependency. - Kombinasi CDS (untuk modelling/exposure) + AMDP (untuk logic DB-heavy) + test automation = strategy yang kuat untuk aplikasi S/4HANA yang reliable dan performa tinggi.

👉 Lanjut ke: Belajar ABAP Part 14: Performance Tuning & HANA Optimization


Catatan: snippet di atas disederhanakan untuk pembelajaran. Untuk produksi, sesuaikan naming convention, object transport, dan policy keamanan (authorizations). Pastikan selalu validasi SQLScript functions pada HANA versi target.

ABAP CDS View Part 10 : Authorization & DCL untuk ABAP CDS

Authorization & DCL di ABAP CDS | Panduan Lengkap (PFCG, @AccessControl, DCL) Authorization & DCL untuk ABAP CDS — Pandua...