athena_rs 2.9.1

Database gateway API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
import argparse
import sys
import os
import json
from supabase import create_client, Client

# suitsbooks
SUPABASE_URL = os.getenv("SUPABASE_URL", "")
SUPABASE_ANON_KEY = os.getenv("SUPABASE_ANON_KEY", "")

CQL_RESERVED_KEYWORDS = {
    "token",
    "schema",
    "table",
    "key",
    "create",
    "from",
    "primary",
    "boolean",
    "timestamp",
    "user",
    "uuid",
    "to",
    "update",
    "index",
    "text",
    "int",
    "decimal",
    "blob",
    "delete",
    "order",
}

SQL_RESERVED_KEYWORDS = {
    "user",
    "table",
    "authorization",
    "default",
    "group",
    "primary",
    "to",
    "offset",
    "current_date",
    "current_time",
    "from",
    "order",
    "collate",
    "create",
    # You can add more if needed
}


def get_supabase_client() -> Client:
    return create_client(SUPABASE_URL, SUPABASE_ANON_KEY)


def fetch_schema_json():
    client = get_supabase_client()
    response = client.rpc("get_full_schema_json", {}).execute()
    if hasattr(response, "data"):
        return response.data
    else:
        print("Error fetching schema:", response)
        sys.exit(1)


PG_TO_SQL_TYPE = {
    "bigint": "BIGINT",
    "integer": "INTEGER",
    "smallint": "SMALLINT",
    "text": "TEXT",
    "uuid": "UUID",
    "boolean": "BOOLEAN",
    "timestamp with time zone": "TIMESTAMPTZ",
    "timestamp without time zone": "TIMESTAMP",
    "numeric": "NUMERIC",
    "json": "JSON",
    "jsonb": "JSONB",
    "character varying": "VARCHAR",
    "bytea": "BYTEA",
    "text[]": "TEXT[]",
    "uuid[]": "UUID[]",
}

PG_TO_CQL_TYPE = {
    "bigint": "bigint",
    "integer": "int",
    "smallint": "smallint",
    "text": "text",
    "uuid": "uuid",
    "boolean": "boolean",
    "timestamp with time zone": "timestamp",
    "timestamp without time zone": "timestamp",
    "numeric": "decimal",
    "json": "text",
    "jsonb": "text",
    "character varying": "text",
    "bytea": "blob",
    "text[]": "list<text>",
    "uuid[]": "list<uuid>",
}


def map_pg_type_to_sql(pg_type):
    if pg_type.startswith("character varying"):
        return pg_type.upper()
    return PG_TO_SQL_TYPE.get(pg_type, pg_type.upper())


def map_pg_type_to_cql(pg_type):
    if pg_type.startswith("character varying"):
        return "text"
    if pg_type.endswith("[]"):
        base = pg_type[:-2]
        return f"list<{PG_TO_CQL_TYPE.get(base, 'text')}>"
    return PG_TO_CQL_TYPE.get(pg_type, "text")


def quote_cql_identifier(name):
    # Always quote user, as it is a reserved SQL keyword
    if (
        name.lower() in CQL_RESERVED_KEYWORDS
        or not name.replace("_", "").isalnum()
        or name[0].isdigit()
        or name.lower() == "user"
    ):
        return f'"{name}"'
    return name


def quote_sql_identifier(name):
    # Always quote user, as it is a reserved keyword
    if (
        name.lower() in SQL_RESERVED_KEYWORDS
        or not name.replace("_", "").isalnum()
        or name[0].isdigit()
        or name.lower() == "user"
    ):
        return f'"{name}"'
    return name


def cql_table_name(name):
    return quote_cql_identifier(name.lstrip("_"))


def sql_table_name(name):
    return quote_sql_identifier(name.lstrip("_"))


def render_sql_create_table(table, schema, if_not_exists=False):
    table_name = table["table_name"]
    columns = table["columns"]
    lines = []
    for col in columns:
        colname = quote_sql_identifier(col["column_name"])
        coltype = map_pg_type_to_sql(col["data_type"])
        default = col.get("default")

        # Special handling for id column with bigint type
        if col["column_name"] == "id" and col["data_type"] == "bigint":
            line = f"    {colname} {coltype} GENERATED BY DEFAULT AS IDENTITY NOT NULL"
        else:
            is_nullable = col.get("is_nullable", True)
            line = f"    {colname} {coltype}"
            if not is_nullable:
                line += " NOT NULL"
            if default:
                line += f" DEFAULT {default}"
        lines.append(line)
    table_name_quoted = sql_table_name(table_name)
    create_clause = "CREATE TABLE IF NOT EXISTS" if if_not_exists else "CREATE TABLE"
    return (
        f"{create_clause} {schema}.{table_name_quoted} (\n"
        + ",\n".join(lines)
        + "\n);\n"
    )


def render_sql_create_view(view, schema):
    view_name = view["table_name"]
    view_name_quoted = sql_table_name(view_name)
    return f"-- View: {schema}.{view_name_quoted}\nCREATE VIEW {schema}.{view_name_quoted} AS /* definition omitted */;\n"


def render_sql_extensions(extensions):
    lines = []
    for ext in extensions:
        name = ext["name"]
        version = ext["version"]
        lines.append(f"CREATE EXTENSION IF NOT EXISTS {name} WITH VERSION '{version}';")
    return "\n".join(lines) + "\n"


def render_cql_create_table(table, cql_keyspace="public"):
    table_name = cql_table_name(table["table_name"])
    columns = table["columns"]
    lines = []
    pk = None
    for col in columns:
        colname = quote_cql_identifier(col["column_name"])
        coltype = map_pg_type_to_cql(col["data_type"])
        lines.append(f"    {colname} {coltype}")
        if pk is None and col["column_name"] in ("id", "uuid"):
            pk = colname
    if not pk and columns:
        pk = quote_cql_identifier(columns[0]["column_name"])
    cql = f"CREATE TABLE IF NOT EXISTS {cql_keyspace}.{table_name} (\n"
    cql += ",\n".join(lines)
    if pk:
        cql += f",\n    PRIMARY KEY ({pk})"
    cql += "\n);\n"
    return cql


def write_seed_files(
    schema_json, sql_path="seed.sql", cql_path="seed.cql", if_not_exists=False
):
    schema = schema_json.get("schema", [])
    extensions = schema_json.get("extensions", [])

    # Only process tables and views in the public schema
    tables = [
        t
        for t in schema
        if t.get("table_type") == "table" and t.get("table_schema") == "public"
    ]
    views = [
        v
        for v in schema
        if v.get("table_type") == "view" and v.get("table_schema") == "public"
    ]

    sql_out = ""
    cql_out = ""
    for table in tables:
        sql_out += (
            render_sql_create_table(
                table, table["table_schema"], if_not_exists=if_not_exists
            )
            + "\n"
        )
        cql_out += render_cql_create_table(table) + "\n"

    with open(sql_path, "w", encoding="utf-8") as f:
        f.write(sql_out)
    with open(cql_path, "w", encoding="utf-8") as f:
        f.write(cql_out)

    # Write views.sql and extensions.sql (only public views)
    views_sql = "\n".join([render_sql_create_view(v, v["table_schema"]) for v in views])
    exts_sql = render_sql_extensions(extensions)

    with open("views.sql", "w", encoding="utf-8") as f:
        f.write(views_sql)
    with open("extensions.sql", "w", encoding="utf-8") as f:
        f.write(exts_sql)

    print(f"Wrote {sql_path}, {cql_path}, views.sql, extensions.sql")


def _extract_table_constraints(table):
    constraints = (
        table.get("constraints")
        or table.get("table_constraints")
        or table.get("constraints_info")
        or []
    )
    return constraints if isinstance(constraints, list) else []


def _format_fk_rule(rule):
    if not rule:
        return ""
    rule_upper = str(rule).strip().upper()
    if rule_upper in {"NO ACTION", "RESTRICT", "CASCADE", "SET NULL", "SET DEFAULT"}:
        return rule_upper
    return ""


def render_table_constraints_sql(table, schema):
    table_name = sql_table_name(table["table_name"])
    constraints = _extract_table_constraints(table)
    non_fk_sql = []
    fk_sql = []

    for c in constraints:
        ctype = (c.get("constraint_type") or c.get("type") or "").upper()
        name = c.get("constraint_name") or c.get("name")
        columns = (
            c.get("columns")
            or c.get("column_names")
            or c.get("constrained_columns")
            or []
        )

        col_list = ", ".join(quote_sql_identifier(col) for col in columns)
        constraint_name_sql = f" {quote_sql_identifier(name)}" if name else ""

        if ctype == "PRIMARY KEY" and columns:
            non_fk_sql.append(
                f"ALTER TABLE {schema}.{table_name} ADD CONSTRAINT{constraint_name_sql} PRIMARY KEY ({col_list});"
            )
            continue

        if ctype == "UNIQUE" and columns:
            non_fk_sql.append(
                f"ALTER TABLE {schema}.{table_name} ADD CONSTRAINT{constraint_name_sql} UNIQUE ({col_list});"
            )
            continue

        if ctype == "FOREIGN KEY" and columns:
            ref_table = (
                c.get("foreign_table")
                or c.get("referenced_table")
                or c.get("foreign_table_name")
            )
            ref_schema = (
                c.get("foreign_table_schema")
                or c.get("referenced_schema")
                or c.get("schema")
                or "public"
            )
            ref_columns = c.get("foreign_columns") or c.get("referenced_columns") or []

            if ref_table and ref_columns:
                ref_cols_sql = ", ".join(
                    quote_sql_identifier(col) for col in ref_columns
                )
                fk_stmt = (
                    f"ALTER TABLE {schema}.{table_name} ADD CONSTRAINT{constraint_name_sql} "
                    f"FOREIGN KEY ({col_list}) REFERENCES {ref_schema}.{sql_table_name(ref_table)} ({ref_cols_sql})"
                )
                on_delete = _format_fk_rule(
                    c.get("on_delete") or c.get("delete_rule") or c.get("delete")
                )
                on_update = _format_fk_rule(
                    c.get("on_update") or c.get("update_rule") or c.get("update")
                )
                if on_delete:
                    fk_stmt += f" ON DELETE {on_delete}"
                if on_update:
                    fk_stmt += f" ON UPDATE {on_update}"
                fk_stmt += ";"
                fk_sql.append(fk_stmt)

    return non_fk_sql, fk_sql


def write_constraints_files(schema_json, base_constraints_path="constraints.sql"):
    schema = schema_json.get("schema", [])
    tables = [
        t
        for t in schema
        if t.get("table_type") == "table" and t.get("table_schema") == "public"
    ]

    non_fk_statements = []
    fk_statements = []

    for table in tables:
        non_fk, fks = render_table_constraints_sql(table, table["table_schema"])
        non_fk_statements.extend(non_fk)
        fk_statements.extend(fks)

    non_fk_path = "constraints_nofk.sql"
    fk_path = "constraints_fk.sql"

    with open(non_fk_path, "w", encoding="utf-8") as f:
        f.write("\n".join(non_fk_statements) + ("\n" if non_fk_statements else ""))

    with open(fk_path, "w", encoding="utf-8") as f:
        f.write("\n".join(fk_statements) + ("\n" if fk_statements else ""))

    with open(base_constraints_path, "w", encoding="utf-8") as f:
        combined = []
        combined.extend(non_fk_statements)
        combined.extend(fk_statements)
        f.write("\n".join(combined) + ("\n" if combined else ""))

    print(f"Wrote {base_constraints_path}, {non_fk_path}, {fk_path}")


def main():
    parser = argparse.ArgumentParser(
        description="Fetch full schema from Supabase and generate seed.sql, seed.cql, views.sql, and extensions.sql"
    )
    parser.add_argument("--sql", default="seed.sql", help="Output SQL file")
    parser.add_argument("--cql", default="seed.cql", help="Output CQL file")
    parser.add_argument(
        "--include-constraints-sql",
        action="store_true",
        help="Also generate constraints.sql, constraints_nofk.sql, and constraints_fk.sql",
    )
    parser.add_argument(
        "--if-not-exist-table",
        action="store_true",
        help="Use CREATE TABLE IF NOT EXISTS in SQL output",
    )
    args = parser.parse_args()

    schema_json = fetch_schema_json()
    if isinstance(schema_json, list) and len(schema_json) == 1:
        schema_json = schema_json[0]

    write_seed_files(
        schema_json,
        sql_path=args.sql,
        cql_path=args.cql,
        if_not_exists=args.if_not_exist_table,
    )

    if args.include_constraints_sql:
        write_constraints_files(schema_json, base_constraints_path="constraints.sql")


if __name__ == "__main__":
    main()