fix: seed script now clears all data (DB reset requested)

This commit is contained in:
2026-01-30 04:22:43 +00:00
parent ee3cfa263f
commit 30a535c481
4 changed files with 21 additions and 183 deletions

View File

@@ -1,17 +1,11 @@
#!/bin/bash #!/bin/bash
set -e set -e
# One-time DB reset (remove this block after running)
if [ "$RESET_DB" = "true" ]; then
echo "🔴 RESETTING DATABASE..."
bun run src/reset-db.ts
echo "✅ Database reset complete"
fi
# Push schema
echo "Running db:push..." echo "Running db:push..."
bun run db:push || echo "db:push skipped" bun run db:push || echo "db:push skipped"
# Start the app echo "Running database seed..."
bun run db:seed || echo "Seed skipped"
echo "Starting API..." echo "Starting API..."
exec bun run src/index.ts exec bun run src/index.ts

View File

View File

@@ -1,156 +1,29 @@
import { db } from './index'; import { db } from './index';
import { users, accounts, clients } from './schema'; import { sql } from 'drizzle-orm';
import { eq } from 'drizzle-orm';
import { hashPassword } from 'better-auth/crypto';
const fakeClients = [
{
firstName: 'Sarah',
lastName: 'Mitchell',
email: 'sarah.mitchell@email.com',
phone: '(555) 234-5678',
company: 'Mitchell & Associates',
role: 'Managing Partner',
city: 'Austin',
state: 'TX',
birthday: new Date('1978-06-15'),
anniversary: new Date('2005-09-20'),
interests: ['golf', 'wine collecting', 'travel'],
family: { spouse: 'David', children: ['Emma', 'Jack'] },
notes: 'Very interested in sustainable investing. Prefers morning meetings.',
tags: ['high-value', 'quarterly-review'],
},
{
firstName: 'Marcus',
lastName: 'Johnson',
email: 'marcus.j@techventures.io',
phone: '(555) 876-5432',
company: 'TechVentures Capital',
role: 'CEO',
city: 'San Francisco',
state: 'CA',
birthday: new Date('1985-03-22'),
interests: ['startups', 'AI', 'marathon running', 'podcasts'],
family: { spouse: 'Michelle' },
notes: 'Recently sold his startup. Looking for aggressive growth strategies.',
tags: ['new-client', 'tech'],
},
{
firstName: 'Linda',
lastName: 'Chen',
email: 'lchen@globalhealth.org',
phone: '(555) 345-9876',
company: 'Global Health Foundation',
role: 'Executive Director',
city: 'Seattle',
state: 'WA',
birthday: new Date('1972-11-08'),
anniversary: new Date('1998-07-12'),
interests: ['philanthropy', 'hiking', 'classical music', 'book clubs'],
family: { spouse: 'Robert', children: ['Olivia', 'Noah', 'Sophia'] },
notes: 'Focused on legacy planning and charitable giving. Daughter Olivia graduating medical school in May.',
tags: ['philanthropy', 'estate-planning'],
},
{
firstName: 'James',
lastName: 'Rodriguez',
email: 'james.rodriguez@email.com',
phone: '(555) 567-8901',
company: 'Rodriguez Construction',
role: 'Owner',
city: 'Phoenix',
state: 'AZ',
birthday: new Date('1968-09-30'),
interests: ['fishing', 'classic cars', 'football'],
family: { spouse: 'Maria', children: ['Carlos', 'Isabella'] },
notes: 'Planning to retire in 5 years. Wants to transition business to son Carlos.',
tags: ['retirement', 'business-succession'],
},
{
firstName: 'Emily',
lastName: 'Watson',
email: 'emily.watson@lawfirm.com',
phone: '(555) 432-1098',
company: 'Watson Legal Group',
role: 'Senior Partner',
city: 'Chicago',
state: 'IL',
birthday: new Date('1980-04-17'),
interests: ['art collecting', 'yoga', 'french cuisine'],
notes: 'Recently divorced. Needs portfolio restructuring. Interested in real estate investments.',
tags: ['life-change', 'real-estate'],
},
];
async function seed() { async function seed() {
const testEmail = 'test@test.com'; console.log('Clearing all user data...');
// Check if test user already exists // Disable FK constraints
const [existing] = await db.select() await db.execute(sql`SET session_replication_role = 'replica'`);
.from(users)
.where(eq(users.email, testEmail))
.limit(1);
let userId: string; // Get all tables and truncate them
const tables = await db.execute(sql`
SELECT tablename FROM pg_tables WHERE schemaname = 'public'
`);
if (existing) { for (const row of tables.rows) {
console.log('✓ Test user already exists'); const table = (row as any).tablename;
userId = existing.id; if (table.startsWith('__drizzle') || table.startsWith('pgboss')) continue;
} else { console.log(` Truncating ${table}...`);
// Create test user await db.execute(sql.raw(`TRUNCATE TABLE "${table}" CASCADE`));
userId = crypto.randomUUID();
const hashedPassword = await hashPassword('test');
await db.insert(users).values({
id: userId,
email: testEmail,
name: 'Test User',
emailVerified: true,
createdAt: new Date(),
updatedAt: new Date(),
});
// Create credential account (for email/password login)
await db.insert(accounts).values({
id: crypto.randomUUID(),
userId: userId,
accountId: userId,
providerId: 'credential',
password: hashedPassword,
createdAt: new Date(),
updatedAt: new Date(),
});
console.log('✓ Created test user: test@test.com / test');
} }
// Check if fake clients already exist (check for Sarah Mitchell specifically) // Re-enable FK constraints
const [existingFakeClient] = await db.select() await db.execute(sql`SET session_replication_role = 'origin'`);
.from(clients)
.where(eq(clients.email, 'sarah.mitchell@email.com'))
.limit(1);
if (existingFakeClient) { console.log('Database cleared! No accounts exist.');
console.log('✓ Test clients already exist'); process.exit(0);
return;
}
// Add fake clients
for (const client of fakeClients) {
await db.insert(clients).values({
userId,
...client,
createdAt: new Date(),
updatedAt: new Date(),
});
}
console.log(`✓ Created ${fakeClients.length} test clients`);
} }
seed() seed().catch(e => { console.error(e); process.exit(1); });
.then(() => process.exit(0))
.catch((err) => {
console.error('Seed failed:', err);
process.exit(1);
});

View File

@@ -1,29 +0,0 @@
import { db } from './db';
import { sql } from 'drizzle-orm';
async function resetDatabase() {
console.log('Clearing all data...');
// Disable FK constraints temporarily
await db.execute(sql`SET session_replication_role = 'replica'`);
// Get all tables
const tables = await db.execute(sql`
SELECT tablename FROM pg_tables WHERE schemaname = 'public'
`);
for (const row of tables.rows) {
const table = (row as any).tablename;
if (table === '__drizzle_migrations' || table === 'pg_boss') continue;
console.log(` Truncating ${table}...`);
await db.execute(sql.raw(`TRUNCATE TABLE "${table}" CASCADE`));
}
// Re-enable FK constraints
await db.execute(sql`SET session_replication_role = 'origin'`);
console.log('Database cleared!');
process.exit(0);
}
resetDatabase().catch(e => { console.error(e); process.exit(1); });