-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmigrate_sqlite_to_teable.py
More file actions
427 lines (350 loc) Β· 13 KB
/
migrate_sqlite_to_teable.py
File metadata and controls
427 lines (350 loc) Β· 13 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
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
419
420
421
422
423
424
425
426
427
#!/usr/bin/env python3
"""
Migrate data from SQLite (users.db) to Teable.
This script migrates the following tables:
- users
- admins
- admin_permissions
- api_keys
- apps
Tables that remain in SQLite (ephemeral/temporary):
- email_codes, verification_tokens, opt_out_tokens, oauth_tokens, api_key_usage
"""
import sqlite3
import json
import sys
from typing import Dict, List, Any
from utils.teable import (
create_records_batch,
get_records,
check_teable_config,
count_records
)
from models.api_key import hash_api_key
def get_sqlite_users() -> List[Dict[str, Any]]:
"""Get all users from SQLite."""
conn = sqlite3.connect('users.db')
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
try:
cursor.execute("SELECT * FROM users")
users = cursor.fetchall()
return [dict(row) for row in users]
except sqlite3.OperationalError as e:
print(f"β Error reading users table: {e}")
return []
finally:
conn.close()
def get_sqlite_admins() -> List[Dict[str, Any]]:
"""Get all admins from SQLite."""
conn = sqlite3.connect('users.db')
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
try:
cursor.execute("SELECT * FROM admins")
admins = cursor.fetchall()
return [dict(row) for row in admins]
except sqlite3.OperationalError as e:
print(f"β οΈ Admins table not found or empty: {e}")
return []
finally:
conn.close()
def get_sqlite_admin_permissions() -> List[Dict[str, Any]]:
"""Get all admin permissions from SQLite."""
conn = sqlite3.connect('users.db')
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
try:
cursor.execute("SELECT * FROM admin_permissions")
permissions = cursor.fetchall()
return [dict(row) for row in permissions]
except sqlite3.OperationalError as e:
print(f"β οΈ Admin permissions table not found or empty: {e}")
return []
finally:
conn.close()
def get_sqlite_api_keys() -> List[Dict[str, Any]]:
"""Get all API keys from SQLite."""
conn = sqlite3.connect('users.db')
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
try:
cursor.execute("SELECT * FROM api_keys")
keys = cursor.fetchall()
return [dict(row) for row in keys]
except sqlite3.OperationalError as e:
print(f"β οΈ API keys table not found or empty: {e}")
return []
finally:
conn.close()
def get_sqlite_apps() -> List[Dict[str, Any]]:
"""Get all apps from SQLite."""
conn = sqlite3.connect('users.db')
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
try:
cursor.execute("SELECT * FROM apps")
apps = cursor.fetchall()
return [dict(row) for row in apps]
except sqlite3.OperationalError as e:
print(f"β οΈ Apps table not found or empty: {e}")
return []
finally:
conn.close()
def migrate_users(users: List[Dict[str, Any]], dry_run: bool = False) -> int:
"""Migrate users to Teable."""
if not users:
print(" No users to migrate")
return 0
print(f"\nπ¦ Migrating {len(users)} users...")
if dry_run:
print(" [DRY RUN] Would migrate users")
return len(users)
# Prepare records for Teable (remove SQLite-specific fields like 'id')
teable_records = []
for user in users:
record = {
"email": user.get("email", ""),
"legal_name": user.get("legal_name", ""),
"preferred_name": user.get("preferred_name", ""),
"pronouns": user.get("pronouns", ""),
"dob": user.get("dob", ""),
"discord_id": user.get("discord_id", ""),
"events": user.get("events", "[]") # Already JSON string from SQLite
}
teable_records.append(record)
# Batch insert (100 at a time)
BATCH_SIZE = 100
inserted = 0
for i in range(0, len(teable_records), BATCH_SIZE):
batch = teable_records[i:i + BATCH_SIZE]
result = create_records_batch('users', batch)
if result:
inserted += len(batch)
print(f" β
Migrated batch {i//BATCH_SIZE + 1}: {len(batch)} users")
else:
print(f" β Failed to migrate batch {i//BATCH_SIZE + 1}")
return inserted
def migrate_admins(admins: List[Dict[str, Any]], dry_run: bool = False) -> int:
"""Migrate admins to Teable."""
if not admins:
print(" No admins to migrate")
return 0
print(f"\nπ Migrating {len(admins)} admins...")
if dry_run:
print(" [DRY RUN] Would migrate admins")
return len(admins)
# Prepare records for Teable
teable_records = []
for admin in admins:
record = {
"email": admin.get("email", ""),
"added_by": admin.get("added_by", ""),
"is_active": bool(admin.get("is_active", True)) # Convert SQLite integer to boolean
}
teable_records.append(record)
# Batch insert
result = create_records_batch('admins', teable_records)
if result:
print(f" β
Migrated {len(teable_records)} admins")
return len(teable_records)
else:
print(f" β Failed to migrate admins")
return 0
def migrate_admin_permissions(permissions: List[Dict[str, Any]], dry_run: bool = False) -> int:
"""Migrate admin permissions to Teable."""
if not permissions:
print(" No admin permissions to migrate")
return 0
print(f"\nπ Migrating {len(permissions)} admin permissions...")
if dry_run:
print(" [DRY RUN] Would migrate admin permissions")
return len(permissions)
# Prepare records for Teable
teable_records = []
for perm in permissions:
record = {
"admin_email": perm.get("admin_email", ""),
"permission_type": perm.get("permission_type", ""),
"permission_value": perm.get("permission_value", ""),
"access_level": perm.get("access_level", "read"),
"granted_by": perm.get("granted_by", "")
}
teable_records.append(record)
# Batch insert
result = create_records_batch('admin_permissions', teable_records)
if result:
print(f" β
Migrated {len(teable_records)} admin permissions")
return len(teable_records)
else:
print(f" β Failed to migrate admin permissions")
return 0
def migrate_api_keys(keys: List[Dict[str, Any]], dry_run: bool = False) -> int:
"""Migrate API keys to Teable."""
if not keys:
print(" No API keys to migrate")
return 0
print(f"\nπ Migrating {len(keys)} API keys...")
if dry_run:
print(" [DRY RUN] Would migrate API keys")
return len(keys)
# Prepare records for Teable
teable_records = []
for key in keys:
key_value = key.get("key", "")
key_hash = hash_api_key(key_value) if key_value else ""
record = {
"name": key.get("name", ""),
"key": key_hash,
"created_by": key.get("created_by", ""),
"last_used_at": key.get("last_used_at", ""),
"permissions": key.get("permissions", "[]"), # JSON string
"metadata": key.get("metadata", "{}"), # JSON string
"rate_limit_rpm": key.get("rate_limit_rpm", 60)
}
teable_records.append(record)
# Batch insert
result = create_records_batch('api_keys', teable_records)
if result:
print(f" β
Migrated {len(teable_records)} API keys")
return len(teable_records)
else:
print(f" β Failed to migrate API keys")
return 0
def migrate_apps(apps: List[Dict[str, Any]], dry_run: bool = False) -> int:
"""Migrate apps to Teable."""
if not apps:
print(" No apps to migrate")
return 0
print(f"\nπ± Migrating {len(apps)} apps...")
if dry_run:
print(" [DRY RUN] Would migrate apps")
return len(apps)
# Prepare records for Teable
teable_records = []
for app in apps:
record = {
"name": app.get("name", ""),
"icon": app.get("icon", ""),
"redirect_url_template": app.get("redirect_url_template", ""),
"created_by": app.get("created_by", ""),
"allow_anyone": bool(app.get("allow_anyone", False)), # Convert SQLite integer to boolean
"is_active": bool(app.get("is_active", True)) # Convert SQLite integer to boolean
}
teable_records.append(record)
# Batch insert
result = create_records_batch('apps', teable_records)
if result:
print(f" β
Migrated {len(teable_records)} apps")
return len(teable_records)
else:
print(f" β Failed to migrate apps")
return 0
def show_migration_summary():
"""Show what will be migrated from SQLite."""
print("\n" + "="*60)
print("π SQLITE DATABASE SUMMARY")
print("="*60)
users = get_sqlite_users()
admins = get_sqlite_admins()
permissions = get_sqlite_admin_permissions()
keys = get_sqlite_api_keys()
apps = get_sqlite_apps()
print(f" π€ Users: {len(users)}")
print(f" π Admins: {len(admins)}")
print(f" π Admin Permissions: {len(permissions)}")
print(f" π API Keys: {len(keys)}")
print(f" π± Apps: {len(apps)}")
print("="*60)
return {
'users': users,
'admins': admins,
'permissions': permissions,
'keys': keys,
'apps': apps
}
def show_teable_summary():
"""Show current Teable state."""
print("\n" + "="*60)
print("π CURRENT TEABLE STATE")
print("="*60)
tables = ['users', 'admins', 'admin_permissions', 'api_keys', 'apps']
for table in tables:
try:
count = count_records(table)
print(f" {table}: {count} records")
except Exception as e:
print(f" {table}: Error - {str(e)}")
print("="*60)
def main():
"""Main migration function."""
print("\n" + "="*60)
print("π SQLITE TO TEABLE MIGRATION")
print("="*60)
# Check if running in dry-run mode
dry_run = '--dry-run' in sys.argv
if dry_run:
print("\nβ οΈ DRY RUN MODE - No data will be written to Teable\n")
# Validate Teable configuration
print("\nπ Checking Teable configuration...")
config = check_teable_config()
if not config['configured']:
print("β Teable is not properly configured!")
print("Missing environment variables:")
for var in config['missing']:
print(f" - {var}")
print("\nPlease run teable_setup.py first and add the table IDs to your .env file")
sys.exit(1)
print("β
Teable configuration verified")
# Show current state
show_teable_summary()
# Show what will be migrated
sqlite_data = show_migration_summary()
total_records = sum(len(v) for v in sqlite_data.values())
if total_records == 0:
print("\nβ οΈ No data found in SQLite database to migrate")
sys.exit(0)
# Confirm migration
if not dry_run:
print("\nβ οΈ WARNING: This will add data to Teable.")
print("β οΈ If you have existing data in Teable, this may create duplicates.")
print("\nOptions:")
print(" 1. Run with --dry-run first to see what would be migrated")
print(" 2. Manually clear Teable tables before migrating")
print(" 3. Proceed with migration (may create duplicates)")
response = input("\nProceed with migration? (yes/no): ").strip().lower()
if response != 'yes':
print("β Migration cancelled")
sys.exit(0)
# Perform migration
print("\n" + "="*60)
print("π STARTING MIGRATION")
print("="*60)
migrated_counts = {}
# Migrate each table
migrated_counts['users'] = migrate_users(sqlite_data['users'], dry_run)
migrated_counts['admins'] = migrate_admins(sqlite_data['admins'], dry_run)
migrated_counts['permissions'] = migrate_admin_permissions(sqlite_data['permissions'], dry_run)
migrated_counts['keys'] = migrate_api_keys(sqlite_data['keys'], dry_run)
migrated_counts['apps'] = migrate_apps(sqlite_data['apps'], dry_run)
# Summary
print("\n" + "="*60)
print("β
MIGRATION COMPLETE")
print("="*60)
print(f" π€ Users: {migrated_counts['users']}")
print(f" π Admins: {migrated_counts['admins']}")
print(f" π Admin Permissions: {migrated_counts['permissions']}")
print(f" π API Keys: {migrated_counts['keys']}")
print(f" π± Apps: {migrated_counts['apps']}")
print(f"\nTotal records migrated: {sum(migrated_counts.values())}")
print("="*60)
if dry_run:
print("\nπ‘ This was a dry run. Run without --dry-run to actually migrate data.")
else:
print("\nπ Data successfully migrated to Teable!")
print("\nπ Next steps:")
print(" 1. Verify data in Teable dashboard")
print(" 2. Update your application to use Teable models")
print(" 3. Keep users.db as backup until fully migrated")
if __name__ == "__main__":
main()