reactiveData/plt/generatePythonTriggerCode.inc.php
Frederico Falcao 14f96e78f9 IMPROVEMENT: bring Python trigger support to parity with PHP.
Add SQL bridge, support functions, cron jobs, error handling, and PyPI version pinning so Python triggers match PHP capabilities.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-28 00:13:18 +03:00

38 lines
1.4 KiB
PHP

<?php
/**
* Generates Python code for sandbox execution based on provided trigger code and row data.
*
* @param string $functionName The name of the Python function to generate.
* @param string $pyCode The Python code to embed within the generated function.
* @param array $row The row data to pass to the generated function.
*
* @return string The complete Python code ready for sandbox execution.
*/
function generatePythonTriggerCode($functionName, $pyCode, $row) {
$constants = getPythonConstantsDefinition();
$supportFunctions = getPythonSupportFunctionsDefinition();
$imports = "import json\nimport sys as _sys\nimport os\n\n_sys.path.insert(0, os.path.join(os.getcwd(), 'sys'))\nfrom db_runtime import sql, sql_read, sql_write, sql_read_and_hydrate, get_tbl_primary_key_col_name, run_process\n" . getPythonImports();
$rowJson = json_encode($row, JSON_UNESCAPED_UNICODE);
$rowJsonPyLiteral = json_encode($rowJson);
$indentedCode = implode("\n", array_map(fn($line) => ' ' . $line, explode("\n", $pyCode)));
$pythonCode = <<<PY
$imports
$constants
$supportFunctions
def $functionName(data, error):
$indentedCode
data = json.loads($rowJsonPyLiteral)
error = [None]
_ret = $functionName(data, error)
if _ret is False or error[0]:
_sys.stderr.write("Error: " + str(error[0] or "") + "\\n")
_sys.exit(1)
print(json.dumps(data))
PY;
return $pythonCode;
}