Бібліотека Groovy-скриптів

Data Cleanup Script

advanced high risk Data Management

Description

Remove orphaned data, clean up test data, and optimize database performance

Prerequisites

  • Database backup
  • System maintenance window
  • Administrator privileges

Parameters

cleanupType

String*

Type of cleanup: orphaned, testdata, or performance

batchSize

Number

Number of records to process in each batch

Default: 1000

confirmCleanup

Boolean*

Confirm that cleanup should proceed

Script Code

import de.hybris.platform.servicelayer.search.FlexibleSearchService
import de.hybris.platform.servicelayer.model.ModelService
import de.hybris.platform.core.model.user.UserModel

def cleanupType = parameters.cleanupType
def batchSize = parameters.batchSize ?: 1000
def confirmCleanup = parameters.confirmCleanup

def errors = []
def cleanedCount = 0

if (!confirmCleanup) {
    errors.add("Cleanup not confirmed. Set confirmCleanup to true to proceed.")
    return
}

try {
    switch (cleanupType) {
        case 'orphaned':
            // Clean up orphaned data
            def orphanedQuery = """
                SELECT {pk} FROM {Item} 
                WHERE {pk} NOT IN (
                    SELECT {source} FROM {Relation} 
                    UNION 
                    SELECT {target} FROM {Relation}
                )
            """
            def orphanedItems = flexibleSearchService.search(orphanedQuery).result
            orphanedItems.each { item ->
                try {
                    modelService.remove(item)
                    cleanedCount++
                } catch (Exception e) {
                    errors.add("Error removing orphaned item $item.pk: $e.message")
                }
            }
            break
            
        case 'testdata':
            // Clean up test data
            def testUsers = flexibleSearchService.search("SELECT {pk} FROM {User} WHERE {uid} LIKE 'test%'").result
            testUsers.each { user ->
                try {
                    modelService.remove(user)
                    cleanedCount++
                } catch (Exception e) {
                    errors.add("Error removing test user $user.uid: $e.message")
                }
            }
            break
            
        case 'performance':
            // Performance optimization
            println "Running performance optimization..."
            // Add performance optimization logic here
            cleanedCount = 1
            break
    }
    
    println "Cleaned up $cleanedCount items successfully"
    if (errors) {
        println "Errors encountered:"
        errors.each { println "  - $it" }
    }
    
} catch (Exception e) {
    errors.add("Cleanup script failed: $e.message")
}

Script Information

Author:SAP Commerce Team
Execution Time:5-15 minutes
Rating:4.3/5
Downloads:890
Last Updated:2024-01-10
Version:2.1.0

Tags

cleanup orphaned test-data performance database

Бібліотека Groovy-скриптів

Повна колекція Groovy-скриптів для розробки на SAP Commerce

Можливості

  • Curated library of Groovy scripts for SAP Commerce: FlexibleSearch queries, ImpEx generation, type-system introspection, OOTB business-logic tasks (orders, carts, catalogs, users) — copy-paste ready for HAC's groovy console
  • Categorized by use case: SAP query examples, batch update scripts, validation checks, migration helpers, debugging utilities — find the right starting point quickly
  • Each script includes inline comments explaining the SAP API calls (modelService, flexibleSearchService, etc.), required permissions, and rollback considerations — production-aware patterns
  • Syntax-highlighted output ready to paste into HAC (hac/console.zul/groovy), with line numbers preserved for debugging when the script throws
  • Side-by-side script + explanation: each example has a doc panel describing what it does, when to use it, what could go wrong, and how to adapt it to your project
  • Search and filter by SAP type, operation (read/write), or complexity level (beginner / intermediate / advanced) — narrow down 40+ scripts to the relevant 3-5
  • Copy individual scripts to clipboard or download as .groovy files for version control — each carries a header comment with attribution and version
  • Pure client-side: scripts are static content in the page bundle, no upload needed; safe to read on a sensitive machine without internet

Як використовувати

  1. Browse or search the library for a script matching your task — SAP query, batch update, type introspection, etc.
  2. Read the doc panel to understand what the script does, expected inputs, and any prerequisites.
  3. Copy the script to your clipboard.
  4. Paste into HAC's Groovy console (hac/console.zul → Groovy tab).
  5. For write scripts: ALWAYS run in a non-production environment first; the console executes immediately with full ModelService access.
  6. Adapt the script to your project: replace placeholder values (catalog name, product code, etc.) before running.

Поради та найкращі практики

  • Always run read-only scripts first to verify the data state before any write operation.
  • For batch updates, prefer modelService.saveAll(list) over modelService.save(item) in a loop — vastly faster.
  • Use Cookie permissions in HAC to require fresh authentication before write operations — adds an explicit confirmation step.
  • Version-control your project-specific Groovy scripts in your repo, not in the library; centralized library is for shared patterns.
  • When debugging, add println statements at strategic points; HAC's Groovy console captures stdout to the output panel.

Запитання та відповіді

Can I run these scripts directly in production?

Only the read-only scripts (FlexibleSearch queries, type introspection). Write scripts (modelService.save, batch updates) can corrupt your data if misconfigured — always test in a staging environment first. The library marks read-only scripts as "safe in production"; everything else requires the test-first discipline.

Do the scripts work on all SAP Commerce versions?

They target SAP Commerce 2105+. Older versions (1811, 1905) lack some APIs (e.g., new cart-service methods, updated tax handling). Each script's doc panel notes the minimum version. If you're on 1811, focus on the FlexibleSearch and type-introspection scripts — those work across all versions.

Why is my Groovy script throwing "ModelService not found"?

Inside HAC's console, services are auto-injected via Spring. If you see ModelService not found, check that you're in the Groovy tab (not Beanshell), that the import statements at top are correct, and that your hybris environment has loaded the model package. Reset HAC if needed.

Can these scripts be used in customer-facing flows?

No — they're for admin/dev tooling. For runtime code, you'd call the same APIs from a Spring bean (annotated with @Service), not via Groovy. The library is for one-off admin tasks, not for app-runtime logic.

How do I add my own scripts to the library?

The library is curated. For sharing project-specific scripts within your team, store them in your repo (typically under src/com/yourcompany/scripts/) and version them like other code. Personal scripts can be saved as .groovy files locally; this library shows community-vetted patterns.

Are the scripts free to use commercially?

Yes. The library content is provided under a permissive license (MIT/Apache-style) for use in your SAP Commerce projects without restriction. Attribution appears in the script header comment but is not required for use.

Why don't the scripts auto-rollback on error?

Groovy scripts in HAC run in a transaction by default (configurable). If the script throws, the transaction rolls back automatically. For multi-step scripts, wrap them in try/catch and call modelService.save() at the end so partial state isn't committed.

Is anything sent to a server when I copy a script?

No. The scripts are static content baked into the page bundle. We don't observe which scripts you copy or which patterns you use. Safe to browse on an air-gapped workstation.