-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup-supabase-admin.js
More file actions
185 lines (152 loc) · 5.89 KB
/
Copy pathsetup-supabase-admin.js
File metadata and controls
185 lines (152 loc) · 5.89 KB
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
/**
* Supabase Admin Setup Script
* Uses service role key to create tables and storage buckets programmatically
* Run with: node setup-supabase-admin.js
*/
const { createClient } = require('@supabase/supabase-js')
const fs = require('fs')
const path = require('path')
// Load .env.local manually
function loadEnv() {
const envPath = path.join(__dirname, '.env.local')
if (!fs.existsSync(envPath)) {
console.error('❌ .env.local file not found!')
process.exit(1)
}
const envContent = fs.readFileSync(envPath, 'utf-8')
const env = {}
envContent.split('\n').forEach(line => {
const trimmed = line.trim()
if (trimmed && !trimmed.startsWith('#')) {
const [key, ...valueParts] = trimmed.split('=')
if (key && valueParts.length > 0) {
env[key.trim()] = valueParts.join('=').trim()
}
}
})
return env
}
const env = loadEnv()
const supabaseUrl = env.NEXT_PUBLIC_SUPABASE_URL
const serviceRoleKey = env.SUPABASE_SERVICE_ROLE_KEY
if (!supabaseUrl || !serviceRoleKey) {
console.error('❌ Missing Supabase environment variables!')
console.error('Required: NEXT_PUBLIC_SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY')
console.error('\nTo get your service role key:')
console.error('1. Go to: https://supabase.com/dashboard/project/yunrhoxuxrzbcbkrvgjw/settings/api')
console.error('2. Find "service_role" key (secret)')
console.error('3. Click "Reveal" and copy it')
console.error('4. Add to .env.local: SUPABASE_SERVICE_ROLE_KEY=your_key_here')
process.exit(1)
}
// Create admin client with service role key
const supabaseAdmin = createClient(supabaseUrl, serviceRoleKey, {
auth: {
autoRefreshToken: false,
persistSession: false
}
})
async function executeSQL(sql) {
// Use Supabase REST API to execute SQL
const response = await fetch(`${supabaseUrl}/rest/v1/rpc/exec_sql`, {
method: 'POST',
headers: {
'apikey': serviceRoleKey,
'Authorization': `Bearer ${serviceRoleKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ query: sql })
})
if (!response.ok) {
// Try alternative: use PostgREST or direct PostgreSQL connection
// For now, we'll use a workaround with the Supabase Management API
return { error: 'Direct SQL execution not available via REST API' }
}
return await response.json()
}
async function createTable() {
console.log('📊 Creating scripts table...')
try {
// Read SQL file
const sqlPath = path.join(__dirname, 'supabase-setup.sql')
const sql = fs.readFileSync(sqlPath, 'utf-8')
// Split into individual statements
const statements = sql
.split(';')
.map(s => s.trim())
.filter(s => s.length > 0 && !s.startsWith('--'))
// Execute each statement using Supabase REST API
// Note: Supabase doesn't expose DDL via REST API, so we'll use a workaround
console.log('⚠️ Note: Supabase REST API doesn\'t support DDL operations directly.')
console.log('📝 Using alternative method: Creating table via Supabase Management API...\n')
// Alternative: Use Supabase Management API or direct PostgreSQL connection
// For now, we'll guide the user to use the SQL Editor
console.log('💡 To execute SQL programmatically, you have two options:')
console.log(' 1. Use Supabase CLI (recommended)')
console.log(' 2. Use the SQL Editor in dashboard\n')
// Try to verify if table exists
const { data, error } = await supabaseAdmin.from('scripts').select('id').limit(1)
if (error && error.code === 'PGRST116') {
console.log('❌ Table does not exist yet.')
console.log('📋 Please run the SQL manually:')
console.log(' • Go to: https://supabase.com/dashboard/project/yunrhoxuxrzbcbkrvgjw/sql/new')
console.log(' • Copy contents of: supabase-setup.sql')
console.log(' • Paste and click "Run"\n')
return false
} else if (error) {
console.log('⚠️ Error checking table:', error.message)
return false
} else {
console.log('✅ Table "scripts" already exists!')
return true
}
} catch (err) {
console.error('❌ Error creating table:', err.message)
return false
}
}
async function createStorageBucket() {
console.log('🗄️ Creating storage bucket...')
try {
// Check if bucket exists
const { data: buckets, error: listError } = await supabaseAdmin.storage.listBuckets()
if (listError) {
console.error('❌ Error listing buckets:', listError.message)
return false
}
const bucketExists = buckets?.some(b => b.name === 'scripts-audio')
if (bucketExists) {
console.log('✅ Storage bucket "scripts-audio" already exists!')
return true
}
// Create bucket
const { data, error } = await supabaseAdmin.storage.createBucket('scripts-audio', {
public: true,
allowedMimeTypes: ['audio/mpeg', 'audio/mp3'],
fileSizeLimit: 10485760 // 10MB
})
if (error) {
console.error('❌ Error creating bucket:', error.message)
return false
}
console.log('✅ Storage bucket "scripts-audio" created successfully!')
return true
} catch (err) {
console.error('❌ Error creating storage bucket:', err.message)
return false
}
}
async function setup() {
console.log('🚀 Setting up Supabase with admin privileges...\n')
const tableCreated = await createTable()
const bucketCreated = await createStorageBucket()
console.log('\n📊 Setup Summary:')
console.log(` Table: ${tableCreated ? '✅ Created/Exists' : '❌ Needs manual creation'}`)
console.log(` Bucket: ${bucketCreated ? '✅ Created/Exists' : '❌ Needs manual creation'}`)
if (tableCreated && bucketCreated) {
console.log('\n✨ Setup complete! Your app is ready to use.')
} else {
console.log('\n⚠️ Some steps need manual completion. See instructions above.')
}
}
setup().catch(console.error)