sageapi/scripts/generate_ddl.py
Hermes Agent 40c480e488 fix: sageapi local deployment and test server
- Fix health check sqlExe calls: add missing ns parameter
- Fix accounting ID generation: use getID() instead of uuid4 (VARCHAR length)
- Fix accounting request_id: normalize empty to NULL to avoid UNIQUE constraint violation
- Fix test_server balance/update route: was incorrectly pointing to accounting handler
- Add test_server.py: standalone aiohttp test server for local development
- Update conf/config.yaml: local MySQL credentials (test/test)
- Update db/schema.sql and scripts/generate_ddl.py for local testing
- Fix router sync_status sqlExe call: add missing ns parameter
- Fix sync uapi_sync: use correct table/column names
2026-05-20 22:46:05 +08:00

61 lines
2.3 KiB
Python
Executable File

#!/usr/bin/env python3
"""Generate DDL from SageAPI model JSON definitions."""
import json
import os
def generate_ddl(models_dir='models', output_path='db/schema.sql'):
os.makedirs(os.path.dirname(output_path), exist_ok=True)
ddl_lines = ['-- SageAPI DDL (auto-generated)', '']
for f in sorted(os.listdir(models_dir)):
if not f.endswith('.json'):
continue
with open(os.path.join(models_dir, f)) as fh:
data = json.load(fh)
summary = data['summary'][0]
tblname = summary['name']
primary = summary['primary']
btick = '`'
ddl_lines.append(f'CREATE TABLE IF NOT EXISTS {btick}{tblname}{btick} (')
col_defs = []
for field in data['fields']:
nullable = 'NULL' if field.get('nullable', True) else 'NOT NULL'
default = ''
if field.get('default') is not None:
d = field['default']
if d == 'CURRENT_TIMESTAMP':
default = "DEFAULT CURRENT_TIMESTAMP"
elif d == '':
default = "DEFAULT ''"
elif isinstance(d, str):
default = f"DEFAULT '{d}'"
else:
default = f"DEFAULT {d}"
comment = f"COMMENT '{field.get('comment', '')}'"
fname = f'{btick}{field["name"]}{btick}'
col_defs.append(f' {fname} {field["type"]} {nullable} {default} {comment}'.strip())
pk = f'{btick}{primary}{btick}'
col_defs.append(f' PRIMARY KEY ({pk})')
ddl_lines.append(',\n'.join(col_defs))
ddl_lines.append(') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;')
ddl_lines.append('')
tbl = f'{btick}{tblname}{btick}'
for idx in data.get('idxfields', []):
unique = 'UNIQUE' if idx.get('unique') else 'INDEX'
cols = ','.join(f'{btick}{c}{btick}' for c in idx['fields'])
idx_name = f'{btick}{idx["name"]}{btick}'
ddl_lines.append(f'ALTER TABLE {tbl} ADD {unique} {idx_name} ({cols});')
ddl_lines.append('')
with open(output_path, 'w') as fh:
fh.write('\n'.join(ddl_lines))
print(f' Generated: {output_path} ({len(ddl_lines)} lines)')
if __name__ == '__main__':
generate_ddl()