Variable EXPORT_DATABASE_PHPConst
EXPORT_DATABASE_PHP: "// __CFW_HOST_HELPERS__\n\n$cap = __CFW_CAP__;\n$out = ['ok' => false, 'statements' => 0, 'bytes' => 0, 'tables' => [], 'sql' => ''];\n$lines = [];\n\n$master = cfw_sql(\n\t\"SELECT type, name, sql FROM sqlite_master WHERE sql IS NOT NULL ORDER BY CASE type WHEN 'table' THEN 0 ELSE 1 END, name\",\n);\nif (($master['ok'] ?? false) !== true) {\n\techo json_encode(['ok' => false, 'error' => $master['error'] ?? 'cannot read sqlite_master']);\n\treturn;\n}\n\n$tables = [];\nforeach ($master['rows'] as $row) {\n\t$name = (string) ($row['name'] ?? '');\n\t// engine-owned objects refuse to be created, and miniflare adds bookkeeping\n\tif (\n\t\t$name === '' ||\n\t\tstr_starts_with($name, 'sqlite_') ||\n\t\tstr_starts_with($name, '__miniflare')\n\t) {\n\t\tcontinue;\n\t}\n\t$lines[] = rtrim((string) $row['sql'], \";\\n\\r\\t \") . ';';\n\tif (($row['type'] ?? '') === 'table') {\n\t\t$tables[] = $name;\n\t}\n}\n\n$quote = function ($v) {\n\tif ($v === null) {\n\t\treturn 'NULL';\n\t}\n\tif (is_array($v)) {\n\t\t$v = (string) ($v['__phpint'] ?? '');\n\t}\n\tif (is_int($v) || is_float($v)) {\n\t\treturn (string) $v;\n\t}\n\t$s = (string) $v;\n\t// a decimal string is emitted bare so INTEGER affinity survives a round trip\n\tif ($s !== '' && preg_match('/^-?[0-9]{1,18}$/', $s) === 1) {\n\t\treturn $s;\n\t}\n\treturn \"'\" . str_replace(\"'\", \"''\", $s) . \"'\";\n};\n\nforeach ($tables as $table) {\n\t$sql = 'SELECT * FROM \"' . str_replace('\"', '\"\"', $table) . '\"';\n\tif ($cap > 0) {\n\t\t$sql .= ' LIMIT ' . $cap;\n\t}\n\t$rows = cfw_sql($sql);\n\tif (($rows['ok'] ?? false) !== true) {\n\t\t$out['tables'][$table] = 'ERROR: ' . ($rows['error'] ?? 'unknown');\n\t\tcontinue;\n\t}\n\t$n = 0;\n\tforeach ($rows['rows'] as $row) {\n\t\t$cols = array_keys($row);\n\t\tif (!$cols) {\n\t\t\tcontinue;\n\t\t}\n\t\t$quoted = array_map(function ($c) {\n\t\t\treturn '\"' . str_replace('\"', '\"\"', $c) . '\"';\n\t\t}, $cols);\n\t\t$vals = array_map($quote, array_values($row));\n\t\t$lines[] =\n\t\t\t'INSERT INTO \"' .\n\t\t\t$table .\n\t\t\t'\" (' .\n\t\t\timplode(', ', $quoted) .\n\t\t\t') VALUES (' .\n\t\t\timplode(', ', $vals) .\n\t\t\t');';\n\t\t$n++;\n\t}\n\t$out['tables'][$table] = $n;\n}\n\n$dump = implode(\"\\n\", $lines);\n$out['ok'] = true;\n$out['statements'] = count($lines);\n$out['bytes'] = strlen($dump);\n$out['sha1'] = sha1($dump);\n// the caller decides whether to ship the body; a fleet backup streams it to R2\n$out['sql'] = $dump;\necho json_encode($out);\n"