Spaces:
Sleeping
Sleeping
File size: 6,566 Bytes
a477044 |
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 |
"""
Create admin_rules table in Supabase programmatically.
This script uses the Supabase Python client to set up the table.
"""
import os
import sys
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()
def create_table_using_supabase_client():
"""
Create the admin_rules table using Supabase client.
Since Supabase doesn't allow direct SQL execution via REST API,
we'll use a workaround or provide clear instructions.
"""
supabase_url = os.getenv("SUPABASE_URL")
supabase_key = os.getenv("SUPABASE_SERVICE_KEY")
if not supabase_url or not supabase_key:
print("β Missing Supabase credentials!")
print(" Set SUPABASE_URL and SUPABASE_SERVICE_KEY in .env file")
return False
try:
from supabase import create_client
import httpx
print("π Connecting to Supabase...")
client = create_client(supabase_url, supabase_key)
# Read SQL from file
sql_file = Path(__file__).parent / "supabase_admin_rules_table.sql"
if not sql_file.exists():
print(f"β SQL file not found: {sql_file}")
return False
with open(sql_file, "r", encoding="utf-8") as f:
sql_content = f.read()
print("π Attempting to create table via Supabase API...")
# Method 1: Try using Supabase Management API (if available)
# This requires the project to have pg_net extension enabled
try:
# Use the REST API to execute SQL via a custom function
# First, check if we can use the SQL execution endpoint
response = httpx.post(
f"{supabase_url}/rest/v1/rpc/exec_sql",
headers={
"apikey": supabase_key,
"Authorization": f"Bearer {supabase_key}",
"Content-Type": "application/json",
"Prefer": "return=representation"
},
json={"query": sql_content},
timeout=30
)
if response.status_code in [200, 201, 204]:
print("β
Table created successfully via API!")
return True
else:
print(f"β οΈ API method returned: {response.status_code}")
print(f" Response: {response.text[:200]}")
except Exception as e:
print(f"β οΈ API method failed: {e}")
# Method 2: Try using Supabase Python client's table operations
# This won't work for DDL, but we can verify if table exists
print("\nπ Checking if table already exists...")
try:
result = client.table("admin_rules").select("id").limit(1).execute()
print("β
Table 'admin_rules' already exists!")
return True
except Exception as e:
error_str = str(e).lower()
if "relation" in error_str or "does not exist" in error_str:
print("β οΈ Table does not exist yet.")
else:
print(f"β οΈ Error checking table: {e}")
# Method 3: Since direct SQL execution isn't supported, show instructions
print("\n" + "=" * 70)
print("π MANUAL SETUP REQUIRED")
print("=" * 70)
print("\nSupabase doesn't allow programmatic SQL execution for security.")
print("Please run the SQL manually in Supabase Dashboard:\n")
print("1. Go to: https://app.supabase.com")
print("2. Select your project")
print("3. Click 'SQL Editor' (left sidebar)")
print("4. Click 'New query'")
print("5. Copy the SQL below and paste it:")
print("\n" + "-" * 70)
print(sql_content)
print("-" * 70)
print("\n6. Click 'Run' button (or press Ctrl+Enter)")
print("7. Wait for success confirmation")
print("\nβ
After running, the table will be created automatically!")
return False
except ImportError:
print("β Supabase client not installed")
print(" Run: pip install supabase")
return False
except Exception as e:
print(f"β Error: {e}")
import traceback
traceback.print_exc()
return False
def create_table_via_psql():
"""
Alternative: Use psql (PostgreSQL client) to execute SQL directly.
This requires POSTGRESQL_URL to be set.
"""
postgres_url = os.getenv("POSTGRESQL_URL")
if not postgres_url:
print("β οΈ POSTGRESQL_URL not set, skipping psql method")
return False
sql_file = Path(__file__).parent / "supabase_admin_rules_table.sql"
if not sql_file.exists():
return False
try:
import subprocess
print("π Attempting to create table via psql...")
# Execute SQL using psql
result = subprocess.run(
["psql", postgres_url, "-f", str(sql_file)],
capture_output=True,
text=True,
timeout=30
)
if result.returncode == 0:
print("β
Table created successfully via psql!")
return True
else:
print(f"β οΈ psql failed: {result.stderr}")
return False
except FileNotFoundError:
print("β οΈ psql not found in PATH")
return False
except Exception as e:
print(f"β οΈ psql method failed: {e}")
return False
if __name__ == "__main__":
print("=" * 70)
print("Supabase Admin Rules Table Creator")
print("=" * 70)
print()
# Try Method 1: Supabase client
success = create_table_using_supabase_client()
if not success:
# Try Method 2: psql (if available)
print("\n" + "=" * 70)
print("Trying alternative method: psql")
print("=" * 70)
success = create_table_via_psql()
if success:
print("\n" + "=" * 70)
print("β
SUCCESS!")
print("=" * 70)
print("\nThe admin_rules table has been created in Supabase.")
print("RulesStore will now use Supabase instead of SQLite.")
else:
print("\n" + "=" * 70)
print("π Manual Setup Required")
print("=" * 70)
print("\nPlease run the SQL manually in Supabase SQL Editor.")
print("The SQL script is ready in: supabase_admin_rules_table.sql")
print("\nAfter creating the table, RulesStore will automatically use Supabase.")
|