#!/usr/bin/env python3 """Extract the archived built-in DDL into the store's compiled tables. Native kit definitions describe the object's current tables, not this build's archived local DDL. Only explicit data-only definition arguments are rewritten. """ import argparse import hashlib import json from pathlib import Path import re import sqlite3 ROOT = Path(__file__).resolve().parents[1] STORE = ROOT / 'crates/cotton-store/src/schema/builtin_tables.json' DDL = ROOT / 'crates/cotton-store/src/schema/ddl.rs' def statements(): source = DDL.read_text() constants = dict(re.findall(r'pub const (\w+): &str =\s*r#"(.*?)"#;', source, re.S)) body = source.split('pub static SCHEMA_DDL: &[&str] = &[', 1)[1].rsplit('];', 1)[0] tokens = re.finditer(r'r#"(.*?)"#|//[^\n]*|/\*.*?\*/|\b([A-Z][A-Z_0-9]*)\b', body, re.S) return [m[1] if m[1] is not None else constants[m[2]] for m in tokens if m[1] is not None or m[2] is not None] def section_span(source, key): # Walk only the outer object; nested keys and strings are never matches. decoder = json.JSONDecoder() at = source.index('{') + 1 while True: while source[at].isspace() or source[at] == ',': at += 1 if source[at] == '}': return None name, end = decoder.raw_decode(source, at) at = end while source[at].isspace() or source[at] == ':': at += 1 start = at _, at = decoder.raw_decode(source, at) if name == key: return start, at def with_tables(source, tables): value = json.dumps(tables, indent=2, ensure_ascii=False) value = value.replace('\n', '\n ') span = section_span(source, 'tables') if span: return source[:span[0]] + value + source[span[1]:] end = source.rindex('}') # Insert before the final brace, preserving every existing byte. return source[:end] + ',\n "tables": ' + value + '\n' + source[end:] def builtin_ids(): return set(json.loads(STORE.read_text())) def owners(names): ids = builtin_ids() aliases = { 'cotton_inbox_items': 'thought', 'cotton_call_log': 'call', 'cotton_recurring_todos': 'todo_recurrence', 'cotton_memories': 'memory', 'cotton_msg_threads': 'thread', 'cotton_msg_messages': 'message', 'cotton_emails': 'email', 'cotton_email_threads': 'email_thread', 'cotton_fin_accounts': 'money_account', 'cotton_fin_movements': 'transaction', 'cotton_fin_postings': 'transaction', 'cotton_fin_evidence': 'evidence', 'cotton_fin_statements': 'statement', 'cotton_people': 'person', 'cotton_repos': 'repository', 'cotton_repo_issues': 'issue', 'cotton_repo_pulls': 'pull', 'cotton_repo_releases': 'release', 'cotton_repo_runs': 'run', 'cotton_document_pages': 'document', 'cotton_event_attendees': 'event', 'cotton_memory_projects': 'memory', 'cotton_money_aliases': 'money_account', 'cotton_money_transactions': 'transaction', 'cotton_money_transaction_lines': 'transaction_line', 'cotton_money_statements': 'statement', 'cotton_money_statement_lines': 'statement_line', 'cotton_money_evidence': 'evidence', 'cotton_news_seen': 'news_story', 'cotton_media_faces': 'face', 'cotton_media_duplicates': 'duplicate', 'cotton_media_sightings': 'sighting', 'cotton_media_albums': 'album', 'cotton_media_album_items': 'album_item', 'cotton_agent_accounts': 'assistant', 'cotton_account_usage_samples': 'assistant', 'cotton_machine_runners': 'code_runner', 'cotton_session_tasks': 'session', 'cotton_dev_jobs': 'session', 'cotton_blocked_senders': 'email_sender', 'cotton_msg_thread_participants': 'thread_member', } # Infrastructure remains core even where an engine has a UI definition. core = ('cotton_vault_', 'cotton_secret', 'cotton_device', 'cotton_database', 'cotton_access', 'cotton_ai_', 'cotton_author', 'cotton_grant', 'cotton_admission', 'cotton_person_key', 'cotton_member', 'cotton_invite', 'cotton_revocation', 'cotton_serving', 'cotton_joined', 'cotton_storage', 'cotton_media_holdings', 'cotton_media_erasures', 'cotton_holding', 'cotton_workspaces', 'cotton_link', 'cotton_undo', 'cotton_change', 'cotton_record', 'cotton_import', 'cotton_connection', 'cotton_home_', 'cotton_board_', 'cotton_theme_', 'cotton_table_definition', 'cotton_tool_definition', 'cotton_toolkit') result = {} for name in names: if name.startswith('_') or name.startswith(core): continue stem = name.removeprefix('cotton_') candidates = [stem, stem.removesuffix('s'), stem.removesuffix('ies') + 'y'] owner = aliases.get(name) or next((c for c in candidates if c in ids), None) if owner: result[name] = owner # Companion tables follow the package that owns their records. families = {'cotton_todo_': 'todo', 'cotton_note_': 'note', 'cotton_thought_': 'thought', 'cotton_person_': 'person', 'cotton_msg_': 'thread', 'cotton_email_': 'email', 'cotton_screenplay_': 'screenplay', 'cotton_repo_': 'repository', 'cotton_fin_': 'transaction', 'cotton_meeting_': 'meeting', 'cotton_call_': 'call'} for name in names: if name in result or name.startswith(core): continue owner = next((owner for prefix, owner in families.items() if name.startswith(prefix) and owner in ids), None) if owner: result[name] = owner return result def split_parts(body): parts, start, depth, quote = [], 0, 0, None i = 0 while i < len(body): char = body[i] if quote: if char == quote: if i + 1 < len(body) and body[i + 1] == quote: i += 1 else: quote = None elif body[i:i + 2] == '--': newline = body.find('\n', i) i = len(body) if newline < 0 else newline elif char in "'\"": quote = char elif char == '(': depth += 1 elif char == ')': depth -= 1 elif char == ',' and depth == 0: parts.append(body[start:i]) start = i + 1 i += 1 parts.append(body[start:]) return parts def shapes(): sql = statements() db = sqlite3.connect(':memory:') for statement in sql: db.execute(statement) ordinary = [r[0] for r in db.execute("SELECT name FROM sqlite_master WHERE type='table' AND sql LIKE 'CREATE TABLE%' AND name NOT LIKE 'fts_%'")] ownership = owners(ordinary) tables = {} for statement in sql: match = re.match(r'CREATE TABLE (?:IF NOT EXISTS )?["`]?([\w]+)["`]?\s*\(', statement) if match and match[1] in ownership: name = match[1] start, end = statement.index('(') + 1, statement.rindex(')') info = {r[1]: r for r in db.execute(f'PRAGMA table_info("{name}")')} columns, constraints = [], [] parts = split_parts(statement[start:end]) for position, part in enumerate(parts): key = re.match(r'\s*["`]?([\w]+)', re.sub(r'--[^\n]*', '', part))[1] if key in info: row = info[key] columns.append(dict(name=key, type=row[2], default=row[4], nullable=not bool(row[3]), primary_key=bool(row[5]), declaration=part, position=position)) else: constraints.append(dict(declaration=part, position=position)) tables[name] = dict(name=name, columns=columns, constraints=constraints, prefix=statement[:start], suffix=statement[end:], indexes=[], full_text=[], triggers=[]) core = [] for statement in sql: # SQLite normalizes quoted CREATE TABLE; parse ownership instead. table = None if re.match(r'CREATE TABLE ', statement): m = re.match(r'CREATE TABLE (?:IF NOT EXISTS )?["`]?([\w]+)', statement) table = m[1] kind = 'table' elif re.match(r'CREATE (?:UNIQUE )?INDEX ', statement): table = re.search(r'\bON\s+["`]?([\w]+)', statement)[1] kind = 'indexes' elif statement.startswith('CREATE TRIGGER '): table = re.search(r'\bON\s+["`]?([\w]+)', statement)[1] kind = 'triggers' elif statement.startswith('CREATE VIRTUAL TABLE '): content = re.search(r"content\s*=\s*'([^']+)'", statement) table = content[1] if content else None kind = 'full_text' if table in tables: if kind != 'table': tables[table][kind].append(statement) else: core.append(statement) result = {key: [] for key in builtin_ids()} for name, table in tables.items(): result[ownership[name]].append(table) return result, core def imported_tables(definition): identifier = definition.get('id', '') if not re.fullmatch(r'[a-z][a-z0-9_]*', identifier) or definition.get('engine') is not None: raise ValueError('expected a data-only tool definition') name = 'cotton_' + identifier columns = [dict(name=key, type='TEXT', default=None, nullable=True, primary_key=key == 'id') for key in ('id', 'workspace_id', 'created_at', 'updated_at', 'deleted_at', 'record_byline', '_hlc', '_born')] # Project and order are the definition's own columns; who last wrote it is record_byline. columns[6].update(default="''", nullable=False) indexed = {'updated_at'} searchable = [] keys = set() for column in definition['columns']: key, kind = column['key'], column['type'] if not re.fullmatch(r'[a-z][a-z0-9_]*', key) or key in keys: raise ValueError('duplicate or reserved definition column') keys.add(key) if kind not in ('number', 'amount', 'bool', 'text', 'longtext', 'date', 'time', 'choice', 'link', 'photo', 'file', 'url'): raise ValueError('unknown definition column type ' + kind) sql_type = 'NUMERIC' if kind == 'number' else 'INTEGER' if kind in ('amount', 'bool') else 'TEXT' # A definition's default is the engine's, applied when a record is # made: storage is nullable, so a revision may change a default freely. existing = next((c for c in columns if c['name'] == key), None) if existing: if key == 'id' or existing['type'] != sql_type: raise ValueError('column conflicts with record metadata: ' + key) else: columns.append(dict(name=key, type=sql_type, default=None, nullable=True, primary_key=False)) if kind == 'link' or column.get('indexed'): indexed.add(key) if kind in ('text', 'longtext') and key in definition.get('search', []): searchable.append(key) # A retired column stays in storage with every value it holds. for column in definition.get('retired', []): key, kind = column['key'], column['type'] if not re.fullmatch(r'[a-z][a-z0-9_]*', key) or key in keys: raise ValueError('a retired column is no longer a column') keys.add(key) if kind not in ('number', 'amount', 'bool', 'text', 'longtext', 'date', 'time', 'choice', 'link', 'photo', 'file', 'url'): raise ValueError('unknown retired column type ' + kind) sql_type = 'NUMERIC' if kind == 'number' else 'INTEGER' if kind in ('amount', 'bool') else 'TEXT' columns.append(dict(name=key, type=sql_type, default=None, nullable=True, primary_key=False)) for slot in ('project', 'order'): if key := definition.get(slot): if not any(c['name'] == key for c in columns): raise ValueError(slot + ' names unknown column ' + key) indexed.add(key) db = sqlite3.connect(':memory:') for sql in statements(): db.execute(sql) reserved = {row[0] for row in db.execute('SELECT name FROM sqlite_master')} names = {name} | {f'idx_{name}_{key}' for key in indexed} if searchable: fts = 'fts_' + name names |= {fts, fts + '_data', fts + '_idx', fts + '_docsize', fts + '_config', fts + '_content', name + '_ai', name + '_ad', name + '_au'} if reserved & names: raise ValueError('imported definition claims an existing schema object') return [dict(name=name, columns=columns, indexes=[dict(name=f'idx_{name}_{key}', columns=[key], unique=False) for key in sorted(indexed)], full_text=[dict(name='fts_' + name, columns=searchable)] if searchable else [])] def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--check', action='store_true') parser.add_argument('definitions', nargs='*', type=Path, help='non-builtin definition files; default: compiled built-ins') args = parser.parse_args() if args.definitions: stale = [] for path in args.definitions: source = path.read_bytes().decode('utf-8') updated = with_tables(source, imported_tables(json.loads(source))) if updated != source: stale.append(str(path)) if not args.check: path.write_bytes(updated.encode('utf-8')) if stale and args.check: raise SystemExit('stale package tables: ' + ', '.join(stale)) return generated, core = shapes() changed = [] current = json.loads(STORE.read_text()) compiled = {key: ({'engine': current[key]['engine']} if 'engine' in current.get(key, {}) else {}) | {'tables': tables} for key, tables in sorted(generated.items())} text = json.dumps(compiled, indent=2, ensure_ascii=False) + '\n' if STORE.read_text() != text: changed.append('compiled built-in tables') if not args.check: STORE.write_text(text) if changed and args.check: raise SystemExit('stale package tables: ' + ', '.join(changed)) print(f'package tables: {len(generated)} definitions; core SHA-256 {hashlib.sha256(chr(0).join(core).encode()).hexdigest()}') if __name__ == '__main__': main()