-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmigrate-http.js
More file actions
346 lines (278 loc) · 10.6 KB
/
Copy pathmigrate-http.js
File metadata and controls
346 lines (278 loc) · 10.6 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
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
// HTTP-based Supabase Migration Script
// This script uses only built-in Node.js modules to avoid dependency issues
require('dotenv').config();
const https = require('https');
const fs = require('fs');
const path = require('path');
const Database = require('better-sqlite3');
// SQLite connection
const sqliteDb = new Database('./db/elriel.db', { verbose: console.log });
// Supabase connection details
const supabaseUrl = process.env.SUPABASE_URL.replace('https://', '');
const supabaseKey = process.env.SUPABASE_SERVICE_KEY;
// Helper to pause execution when needed
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
// Function to make a request to Supabase REST API
function supabaseRequest(method, path, data = null) {
return new Promise((resolve, reject) => {
const options = {
hostname: supabaseUrl,
path: path,
method: method,
headers: {
'Content-Type': 'application/json',
'apikey': supabaseKey,
'Authorization': `Bearer ${supabaseKey}`
}
};
if (data) {
options.headers['Content-Length'] = Buffer.byteLength(JSON.stringify(data));
}
const req = https.request(options, (res) => {
let responseData = '';
res.on('data', (chunk) => {
responseData += chunk;
});
res.on('end', () => {
try {
const parsedData = responseData ? JSON.parse(responseData) : {};
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve(parsedData);
} else {
reject({
statusCode: res.statusCode,
error: parsedData
});
}
} catch (error) {
reject({
statusCode: res.statusCode,
error: error.message,
data: responseData
});
}
});
});
req.on('error', (error) => {
reject(error);
});
if (data) {
req.write(JSON.stringify(data));
}
req.end();
});
}
// Function to format data from SQLite for Supabase
const formatForSupabase = (data) => {
// Convert SQLite timestamps to ISO format for PostgreSQL
const formattedData = {...data};
for (const key in formattedData) {
if (typeof formattedData[key] === 'string' &&
(key.includes('_at') || key.includes('date') || key === 'created_at' || key === 'updated_at' || key === 'last_login')) {
try {
// Try to parse as date if it looks like a timestamp
if (formattedData[key] && !formattedData[key].includes('Z') &&
(formattedData[key].includes('-') || formattedData[key].includes(':'))) {
const date = new Date(formattedData[key]);
if (!isNaN(date.getTime())) {
formattedData[key] = date.toISOString();
}
}
} catch (e) {
// Keep original value if parsing fails
console.warn(`Failed to parse date for ${key}: ${formattedData[key]}`);
}
}
}
return formattedData;
};
// Migration functions for each table
async function migrateUsers() {
console.log('Migrating users table...');
const users = sqliteDb.prepare('SELECT * FROM users').all();
console.log(`Found ${users.length} users to migrate.`);
if (users.length === 0) return;
// Migrate in batches to avoid rate limits
const batchSize = 5;
for (let i = 0; i < users.length; i += batchSize) {
const batch = users.slice(i, i + batchSize);
const formattedBatch = batch.map(user => formatForSupabase(user));
try {
await supabaseRequest('POST', '/rest/v1/users', formattedBatch);
console.log(`Migrated users ${i + 1} to ${Math.min(i + batchSize, users.length)}`);
} catch (error) {
console.error('Error inserting users batch:', error);
}
// Avoid rate limiting
await sleep(1000);
}
console.log('Users migration completed.');
}
async function migrateDistricts() {
console.log('Migrating districts table...');
const districts = sqliteDb.prepare('SELECT * FROM districts').all();
console.log(`Found ${districts.length} districts to migrate.`);
if (districts.length === 0) return;
for (const district of districts) {
const formattedDistrict = formatForSupabase(district);
try {
await supabaseRequest('POST', '/rest/v1/districts', [formattedDistrict]);
console.log(`Migrated district: ${district.name}`);
} catch (error) {
console.error('Error inserting district:', error);
}
// Avoid rate limiting
await sleep(500);
}
console.log('Districts migration completed.');
}
async function migrateGlyphs() {
console.log('Migrating glyphs table...');
const glyphs = sqliteDb.prepare('SELECT * FROM glyphs').all();
console.log(`Found ${glyphs.length} glyphs to migrate.`);
if (glyphs.length === 0) return;
// Migrate in batches
const batchSize = 3; // Smaller batch size as glyphs may contain large SVG data
for (let i = 0; i < glyphs.length; i += batchSize) {
const batch = glyphs.slice(i, i + batchSize);
const formattedBatch = batch.map(glyph => formatForSupabase(glyph));
try {
await supabaseRequest('POST', '/rest/v1/glyphs', formattedBatch);
console.log(`Migrated glyphs ${i + 1} to ${Math.min(i + batchSize, glyphs.length)}`);
} catch (error) {
console.error('Error inserting glyphs batch:', error);
}
// Avoid rate limiting - longer pause for potentially larger data
await sleep(1500);
}
console.log('Glyphs migration completed.');
}
async function migrateProfiles() {
console.log('Migrating profiles table...');
const profiles = sqliteDb.prepare('SELECT * FROM profiles').all();
console.log(`Found ${profiles.length} profiles to migrate.`);
if (profiles.length === 0) return;
// Migrate in batches
const batchSize = 5;
for (let i = 0; i < profiles.length; i += batchSize) {
const batch = profiles.slice(i, i + batchSize);
const formattedBatch = batch.map(profile => formatForSupabase(profile));
try {
await supabaseRequest('POST', '/rest/v1/profiles', formattedBatch);
console.log(`Migrated profiles ${i + 1} to ${Math.min(i + batchSize, profiles.length)}`);
} catch (error) {
console.error('Error inserting profiles batch:', error);
}
// Avoid rate limiting
await sleep(1000);
}
console.log('Profiles migration completed.');
}
async function migratePosts() {
console.log('Migrating posts table...');
const posts = sqliteDb.prepare('SELECT * FROM posts').all();
console.log(`Found ${posts.length} posts to migrate.`);
if (posts.length === 0) return;
// Migrate in batches
const batchSize = 5;
for (let i = 0; i < posts.length; i += batchSize) {
const batch = posts.slice(i, i + batchSize);
const formattedBatch = batch.map(post => formatForSupabase(post));
try {
await supabaseRequest('POST', '/rest/v1/posts', formattedBatch);
console.log(`Migrated posts ${i + 1} to ${Math.min(i + batchSize, posts.length)}`);
} catch (error) {
console.error('Error inserting posts batch:', error);
}
// Avoid rate limiting
await sleep(1000);
}
console.log('Posts migration completed.');
}
async function migrateWhispers() {
console.log('Migrating whispers table...');
const whispers = sqliteDb.prepare('SELECT * FROM whispers').all();
console.log(`Found ${whispers.length} whispers to migrate.`);
if (whispers.length === 0) return;
// Migrate in batches
const batchSize = 5;
for (let i = 0; i < whispers.length; i += batchSize) {
const batch = whispers.slice(i, i + batchSize);
const formattedBatch = batch.map(whisper => formatForSupabase(whisper));
try {
await supabaseRequest('POST', '/rest/v1/whispers', formattedBatch);
console.log(`Migrated whispers ${i + 1} to ${Math.min(i + batchSize, whispers.length)}`);
} catch (error) {
console.error('Error inserting whispers batch:', error);
}
// Avoid rate limiting
await sleep(1000);
}
console.log('Whispers migration completed.');
}
async function migrateAnnouncements() {
console.log('Migrating announcements table...');
const announcements = sqliteDb.prepare('SELECT * FROM announcements').all();
console.log(`Found ${announcements.length} announcements to migrate.`);
if (announcements.length === 0) return;
for (const announcement of announcements) {
const formattedAnnouncement = formatForSupabase(announcement);
try {
await supabaseRequest('POST', '/rest/v1/announcements', [formattedAnnouncement]);
console.log(`Migrated announcement: ${announcement.title}`);
} catch (error) {
console.error('Error inserting announcement:', error);
}
// Avoid rate limiting
await sleep(500);
}
console.log('Announcements migration completed.');
}
// Main migration function
async function migrateAllData() {
try {
console.log('Starting migration from SQLite to Supabase...');
console.log('Using Supabase URL:', `https://${supabaseUrl}`);
console.log('--------------------------------');
// First check if we can connect to Supabase
try {
await supabaseRequest('GET', '/rest/v1/users?select=count', null);
console.log('Successfully connected to Supabase');
} catch (error) {
console.error('Error connecting to Supabase. Please check your credentials:', error);
return;
}
console.log('--------------------------------');
// Migrate tables in order to respect foreign key constraints
// First tables without dependencies
await migrateUsers();
console.log('--------------------------------');
await migrateDistricts();
console.log('--------------------------------');
await migrateGlyphs();
console.log('--------------------------------');
// Then tables with dependencies
await migrateProfiles();
console.log('--------------------------------');
await migratePosts();
console.log('--------------------------------');
await migrateWhispers();
console.log('--------------------------------');
await migrateAnnouncements();
console.log('--------------------------------');
console.log('Migration completed successfully!');
} catch (err) {
console.error('Migration failed:', err);
} finally {
// Close SQLite connection
sqliteDb.close();
}
}
// Check that we have the required environment variables
if (!supabaseUrl || !supabaseKey) {
console.error('Error: Missing Supabase credentials in environment variables.');
console.error('Please set SUPABASE_URL and SUPABASE_SERVICE_KEY in your .env file.');
process.exit(1);
}
// Execute the migration
migrateAllData();