mirror of
https://github.com/bitbaum/evig.git
synced 2026-12-03 20:27:02 +01:00
fix: database SSOT violations — migrations, TABLE_NAMES, transactions, indexes
- Renumber 8 duplicate migration files (002, 004, 005, 008, 020, 027, 040) that caused silent skipping during execution - Clean TABLE_NAMES: add 12 missing schema tables, keep legacy raw-SQL tables with clear comments, remove truly phantom entries - Wrap bulk import product+inventory in transaction (was 2 separate writes) - Wrap marketplace conversation+message+metadata in transaction (race fix) - Add missing indexes: listings(verifiedAt), listings(priceChf), users(isStaff, createdAt) + migration 055 - Sync Drizzle schema with new indexes Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
14 files changed
+126
-73
No files matched your search
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,17 @@
|
||||
-- Migration 055: Add missing indexes for common query patterns
|
||||
--
|
||||
-- These columns are frequently filtered/sorted but lack indexes:
|
||||
-- - listings.verified_at (IS NOT NULL filter for verified listings)
|
||||
-- - listings.price_chf (range filters)
|
||||
-- - users(is_staff, created_at) (admin user listing with sort)
|
||||
|
||||
-- Listings: verified filter
|
||||
CREATE INDEX IF NOT EXISTS idx_listings_verified_at ON listings (verified_at)
|
||||
WHERE verified_at IS NOT NULL;
|
||||
|
||||
-- Listings: price range filter
|
||||
CREATE INDEX IF NOT EXISTS idx_listings_price_chf ON listings (price_chf);
|
||||
|
||||
-- Users: staff listing sorted by join date
|
||||
CREATE INDEX IF NOT EXISTS idx_users_staff_created ON users (is_staff, created_at DESC)
|
||||
WHERE is_staff = true;
|
||||
@@ -67,31 +67,34 @@ export const POST = withAdmin('products', async (request: NextRequest) => {
|
||||
|
||||
for (const product of products) {
|
||||
try {
|
||||
// Insert into ai_extracted_products
|
||||
const [productRow] = await db
|
||||
.insert(aiExtractedProducts)
|
||||
.values({
|
||||
itemUuid: sql`gen_random_uuid()::text`,
|
||||
productName: product.title,
|
||||
brand: product.brand,
|
||||
shortDescription: product.description,
|
||||
estimatedPriceChf: String(product.price),
|
||||
category: product.category,
|
||||
condition: 'unknown',
|
||||
status: MARKETPLACE_STATUS.DRAFT,
|
||||
})
|
||||
.returning({ id: aiExtractedProducts.id });
|
||||
// Transaction ensures product + inventory are created atomically
|
||||
const productId = await db.transaction(async (tx) => {
|
||||
const [productRow] = await tx
|
||||
.insert(aiExtractedProducts)
|
||||
.values({
|
||||
itemUuid: sql`gen_random_uuid()::text`,
|
||||
productName: product.title,
|
||||
brand: product.brand,
|
||||
shortDescription: product.description,
|
||||
estimatedPriceChf: String(product.price),
|
||||
category: product.category,
|
||||
condition: 'unknown',
|
||||
status: MARKETPLACE_STATUS.DRAFT,
|
||||
})
|
||||
.returning({ id: aiExtractedProducts.id });
|
||||
|
||||
// Insert into inventory_items
|
||||
await db
|
||||
.insert(inventoryItems)
|
||||
.values({
|
||||
aiProductId: productRow.id,
|
||||
quantityAvailable: 1,
|
||||
marketplaceStatus: MARKETPLACE_STATUS.DRAFT,
|
||||
});
|
||||
await tx
|
||||
.insert(inventoryItems)
|
||||
.values({
|
||||
aiProductId: productRow.id,
|
||||
quantityAvailable: 1,
|
||||
marketplaceStatus: MARKETPLACE_STATUS.DRAFT,
|
||||
});
|
||||
|
||||
createdProducts.push({ id: productRow.id, title: product.title });
|
||||
return productRow.id;
|
||||
});
|
||||
|
||||
createdProducts.push({ id: productId, title: product.title });
|
||||
|
||||
} catch (error) {
|
||||
logger.error(`Error creating product "${product.title}"`, { error, product });
|
||||
|
||||
@@ -68,61 +68,65 @@ export const POST = withAuth<{ id: string }>(async (
|
||||
const participant_1 = session.user.id < listing.sellerId ? session.user.id : listing.sellerId;
|
||||
const participant_2 = session.user.id < listing.sellerId ? listing.sellerId : session.user.id;
|
||||
|
||||
// Find or create marketplace conversation for this listing
|
||||
const [existingConv] = await db
|
||||
.select({ id: conversations.id })
|
||||
.from(conversations)
|
||||
.where(and(
|
||||
eq(conversations.participant1, participant_1),
|
||||
eq(conversations.participant2, participant_2),
|
||||
eq(conversations.type, CONVERSATION_TYPES.MARKETPLACE),
|
||||
eq(conversations.contextId, id)
|
||||
));
|
||||
// Transaction: find-or-create conversation + send message + update metadata
|
||||
const { conversationId, newMessage } = await db.transaction(async (tx) => {
|
||||
// Find or create marketplace conversation for this listing
|
||||
const [existingConv] = await tx
|
||||
.select({ id: conversations.id })
|
||||
.from(conversations)
|
||||
.where(and(
|
||||
eq(conversations.participant1, participant_1),
|
||||
eq(conversations.participant2, participant_2),
|
||||
eq(conversations.type, CONVERSATION_TYPES.MARKETPLACE),
|
||||
eq(conversations.contextId, id)
|
||||
));
|
||||
|
||||
let conversationId: string;
|
||||
let convId: string;
|
||||
|
||||
if (existingConv) {
|
||||
conversationId = existingConv.id;
|
||||
} else {
|
||||
// Create new marketplace conversation
|
||||
const [newConv] = await db
|
||||
.insert(conversations)
|
||||
if (existingConv) {
|
||||
convId = existingConv.id;
|
||||
} else {
|
||||
const [newConv] = await tx
|
||||
.insert(conversations)
|
||||
.values({
|
||||
participant1: participant_1,
|
||||
participant2: participant_2,
|
||||
type: CONVERSATION_TYPES.MARKETPLACE,
|
||||
contextId: id,
|
||||
title: listing.title,
|
||||
lastMessagePreview: message.substring(0, 100),
|
||||
})
|
||||
.returning({ id: conversations.id });
|
||||
convId = newConv.id;
|
||||
}
|
||||
|
||||
// Send the message
|
||||
const [msg] = await tx
|
||||
.insert(messages)
|
||||
.values({
|
||||
participant1: participant_1,
|
||||
participant2: participant_2,
|
||||
type: CONVERSATION_TYPES.MARKETPLACE,
|
||||
contextId: id,
|
||||
title: listing.title,
|
||||
lastMessagePreview: message.substring(0, 100),
|
||||
conversationId: convId,
|
||||
senderId: session.user.id,
|
||||
recipientId: listing.sellerId,
|
||||
content: message,
|
||||
})
|
||||
.returning({ id: conversations.id });
|
||||
conversationId = newConv.id;
|
||||
}
|
||||
.returning({ id: messages.id, createdAt: messages.createdAt });
|
||||
|
||||
// Send the message
|
||||
const [newMessage] = await db
|
||||
.insert(messages)
|
||||
.values({
|
||||
conversationId,
|
||||
senderId: session.user.id,
|
||||
recipientId: listing.sellerId,
|
||||
content: message,
|
||||
})
|
||||
.returning({ id: messages.id, createdAt: messages.createdAt });
|
||||
// Update conversation metadata
|
||||
const unreadField = session.user.id === participant_1 ? 'unread_count_2' : 'unread_count_1';
|
||||
await tx
|
||||
.update(conversations)
|
||||
.set({
|
||||
lastMessageAt: sql`CURRENT_TIMESTAMP`,
|
||||
lastMessagePreview: message.substring(0, 100),
|
||||
...(unreadField === 'unread_count_2'
|
||||
? { unreadCount2: sql`${conversations.unreadCount2} + 1` }
|
||||
: { unreadCount1: sql`${conversations.unreadCount1} + 1` }),
|
||||
updatedAt: sql`CURRENT_TIMESTAMP`,
|
||||
})
|
||||
.where(eq(conversations.id, convId));
|
||||
|
||||
// Update conversation metadata
|
||||
const unreadField = session.user.id === participant_1 ? 'unread_count_2' : 'unread_count_1';
|
||||
await db
|
||||
.update(conversations)
|
||||
.set({
|
||||
lastMessageAt: sql`CURRENT_TIMESTAMP`,
|
||||
lastMessagePreview: message.substring(0, 100),
|
||||
...(unreadField === 'unread_count_2'
|
||||
? { unreadCount2: sql`${conversations.unreadCount2} + 1` }
|
||||
: { unreadCount1: sql`${conversations.unreadCount1} + 1` }),
|
||||
updatedAt: sql`CURRENT_TIMESTAMP`,
|
||||
})
|
||||
.where(eq(conversations.id, conversationId));
|
||||
return { conversationId: convId, newMessage: msg };
|
||||
});
|
||||
|
||||
logger.info('Marketplace message sent', {
|
||||
conversationId,
|
||||
|
||||
+25
-1
@@ -60,7 +60,10 @@ export const TABLE_NAMES = {
|
||||
BLOG_CATEGORIES: 'blog_categories',
|
||||
STATIC_PAGES: 'static_pages',
|
||||
|
||||
// User Roles & Permissions
|
||||
// Applications
|
||||
APPLICATIONS: 'applications',
|
||||
|
||||
// Legacy Role & Permission tables (raw SQL, no Drizzle schema)
|
||||
USER_ROLES: 'user_roles',
|
||||
ROLE_PERMISSIONS: 'role_permissions',
|
||||
PERMISSIONS: 'permissions',
|
||||
@@ -152,6 +155,27 @@ export const TABLE_NAMES = {
|
||||
|
||||
// Organizational Numbers (shared SSOT)
|
||||
ORG_NUMBERS: 'org_numbers',
|
||||
|
||||
// Messaging (extended)
|
||||
MESSAGE_REACTIONS: 'message_reactions',
|
||||
USER_NOTIFICATION_PREFERENCES: 'user_notification_preferences',
|
||||
|
||||
// Order History
|
||||
ORDER_STATUS_HISTORY: 'order_status_history',
|
||||
|
||||
// Payment (extended)
|
||||
PAYMENT_ANALYTICS: 'payment_analytics',
|
||||
PAYMENT_METHODS: 'payment_methods',
|
||||
|
||||
// Subscription Pools
|
||||
SUBSCRIPTION_POOLS: 'subscription_pools',
|
||||
POOL_MEMBERSHIPS: 'pool_memberships',
|
||||
POOL_CONTRIBUTIONS: 'pool_contributions',
|
||||
POOL_VOTES: 'pool_votes',
|
||||
|
||||
// Product Taxonomy
|
||||
PRODUCT_ATTRIBUTES: 'product_attributes',
|
||||
PRODUCT_CATEGORIES: 'product_categories',
|
||||
} as const;
|
||||
|
||||
/**
|
||||
|
||||
@@ -28,6 +28,8 @@ export const users = pgTable('users', {
|
||||
index('idx_users_is_staff').on(table.isStaff),
|
||||
index('idx_users_staff_permissions').using('gin', table.staffPermissions),
|
||||
index('idx_users_is_super_admin').on(table.isSuperAdmin),
|
||||
// 055: admin user listing sorted by join date
|
||||
index('idx_users_staff_created').on(table.isStaff, table.createdAt),
|
||||
])
|
||||
|
||||
export type User = typeof users.$inferSelect
|
||||
|
||||
@@ -65,6 +65,9 @@ export const listings = pgTable('listings', {
|
||||
index('idx_listings_seller').on(table.sellerId, table.status),
|
||||
// 041: status filter for active listings
|
||||
index('idx_listings_status_created').on(table.status, table.createdAt),
|
||||
// 055: verified listings filter + price range queries
|
||||
index('idx_listings_verified_at').on(table.verifiedAt),
|
||||
index('idx_listings_price_chf').on(table.priceChf),
|
||||
])
|
||||
|
||||
export type Listing = typeof listings.$inferSelect
|
||||
|
||||
Reference in new issue
Block a user