|
| 1 | +import { useMemo, useCallback } from "react"; |
| 2 | +import { useQueryClient } from "@tanstack/react-query"; |
| 3 | +import { toast } from "sonner"; |
| 4 | +import { useFullSchema } from "@/hooks/useDbQueries"; |
| 5 | +import { |
| 6 | + useProjectSchema, |
| 7 | + projectKeys, |
| 8 | +} from "@/hooks/useProjectQueries"; |
| 9 | +import { bridgeApi } from "@/services/bridgeApi"; |
| 10 | +import { snapshotToSchemaDetails, schemaGroupsToSnapshots } from "@/lib/schemaConverters"; |
| 11 | +import type { DatabaseSchemaDetails } from "@/types/database"; |
| 12 | + |
| 13 | +// ================================================================ |
| 14 | +// useSchemaExplorerData |
| 15 | +// |
| 16 | +// Smart data source for the Schema Explorer that: |
| 17 | +// |
| 18 | +// 1. OFFLINE-FIRST: Loads from project files (schema.json) even |
| 19 | +// when the database is not connected. |
| 20 | +// |
| 21 | +// 2. LIVE FALLBACK: Falls back to live DB schema via useFullSchema |
| 22 | +// when project files are empty or projectId is not provided. |
| 23 | +// |
| 24 | +// 3. SYNC: Provides a `syncFromDatabase` callback that pulls fresh |
| 25 | +// schema from the live DB and saves it to project files. |
| 26 | +// ================================================================ |
| 27 | + |
| 28 | +export interface UseSchemaExplorerDataReturn { |
| 29 | + /** The resolved schema data for the explorer to render */ |
| 30 | + schemaData: DatabaseSchemaDetails | null; |
| 31 | + |
| 32 | + /** True while initial data is loading */ |
| 33 | + isLoading: boolean; |
| 34 | + |
| 35 | + /** Data source: "live" = from DB, "project" = from project files */ |
| 36 | + dataSource: "live" | "project" | "none"; |
| 37 | + |
| 38 | + /** Whether live DB schema is available (for sync button state) */ |
| 39 | + hasLiveSchema: boolean; |
| 40 | + |
| 41 | + /** Pull fresh schema from DB → save to project files → reload */ |
| 42 | + syncFromDatabase: () => Promise<void>; |
| 43 | + |
| 44 | + /** Refetch from existing source (not a DB sync — just re-queries) */ |
| 45 | + refetch: () => void; |
| 46 | +} |
| 47 | + |
| 48 | +export function useSchemaExplorerData( |
| 49 | + dbId: string | undefined, |
| 50 | + projectId: string | null | undefined |
| 51 | +): UseSchemaExplorerDataReturn { |
| 52 | + const queryClient = useQueryClient(); |
| 53 | + |
| 54 | + // ---- Live DB schema ---- |
| 55 | + const { |
| 56 | + data: liveSchema, |
| 57 | + isLoading: liveLoading, |
| 58 | + error: liveError, |
| 59 | + refetch: refetchLive, |
| 60 | + } = useFullSchema(dbId); |
| 61 | + |
| 62 | + // ---- Project files ---- |
| 63 | + const { |
| 64 | + data: projectSchemaFile, |
| 65 | + isLoading: projectSchemaLoading, |
| 66 | + refetch: refetchProject, |
| 67 | + } = useProjectSchema(projectId ?? undefined); |
| 68 | + |
| 69 | + // ---- Determine the best schema source ---- |
| 70 | + const { schemaData, dataSource } = useMemo(() => { |
| 71 | + // Prefer live DB if available (most up-to-date, has FK/index data) |
| 72 | + if (liveSchema && liveSchema.schemas?.some((s) => s.tables?.length)) { |
| 73 | + return { schemaData: liveSchema, dataSource: "live" as const }; |
| 74 | + } |
| 75 | + |
| 76 | + // Fall back to project cached schema (offline mode) |
| 77 | + if (projectSchemaFile?.schemas?.length) { |
| 78 | + const converted = snapshotToSchemaDetails( |
| 79 | + projectSchemaFile.databaseId || "Database", |
| 80 | + projectSchemaFile.schemas |
| 81 | + ); |
| 82 | + if (converted.schemas.some((s) => s.tables?.length)) { |
| 83 | + return { schemaData: converted, dataSource: "project" as const }; |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + return { schemaData: null, dataSource: "none" as const }; |
| 88 | + }, [liveSchema, projectSchemaFile]); |
| 89 | + |
| 90 | + // ---- Loading state ---- |
| 91 | + const isLoading = liveLoading || projectSchemaLoading; |
| 92 | + const hasLiveSchema = !!liveSchema && !liveError; |
| 93 | + |
| 94 | + // ---- Refetch from current source ---- |
| 95 | + const refetch = useCallback(() => { |
| 96 | + if (dataSource === "live") { |
| 97 | + refetchLive(); |
| 98 | + } else if (dataSource === "project") { |
| 99 | + refetchProject(); |
| 100 | + } else { |
| 101 | + refetchLive(); |
| 102 | + refetchProject(); |
| 103 | + } |
| 104 | + }, [dataSource, refetchLive, refetchProject]); |
| 105 | + |
| 106 | + // ---- Sync from Database ---- |
| 107 | + const syncFromDatabase = useCallback(async () => { |
| 108 | + if (!dbId) { |
| 109 | + toast.error("No database connected"); |
| 110 | + return; |
| 111 | + } |
| 112 | + |
| 113 | + if (!projectId) { |
| 114 | + toast.error("No project linked to this database"); |
| 115 | + return; |
| 116 | + } |
| 117 | + |
| 118 | + try { |
| 119 | + // 1. Fetch fresh schema from live database |
| 120 | + const freshSchema = await bridgeApi.getSchema(dbId); |
| 121 | + |
| 122 | + if (!freshSchema?.schemas?.length) { |
| 123 | + toast.warning("Database returned no schemas"); |
| 124 | + return; |
| 125 | + } |
| 126 | + |
| 127 | + // 2. Convert to snapshots and save to project schema.json |
| 128 | + const snapshots = schemaGroupsToSnapshots(freshSchema.schemas); |
| 129 | + await bridgeApi.saveProjectSchema(projectId, snapshots); |
| 130 | + |
| 131 | + // 3. Invalidate React Query caches to trigger re-render |
| 132 | + queryClient.invalidateQueries({ |
| 133 | + queryKey: projectKeys.schema(projectId), |
| 134 | + }); |
| 135 | + queryClient.invalidateQueries({ |
| 136 | + queryKey: ["fullSchema", dbId], |
| 137 | + }); |
| 138 | + |
| 139 | + toast.success("Schema synced from database", { |
| 140 | + description: `${freshSchema.schemas.reduce( |
| 141 | + (acc, s) => acc + (s.tables?.length || 0), |
| 142 | + 0 |
| 143 | + )} tables across ${freshSchema.schemas.length} schemas`, |
| 144 | + }); |
| 145 | + } catch (err: any) { |
| 146 | + console.error("[SchemaExplorerData] Sync failed:", err); |
| 147 | + toast.error("Schema sync failed", { |
| 148 | + description: err.message || "Could not pull schema from database", |
| 149 | + }); |
| 150 | + } |
| 151 | + }, [dbId, projectId, queryClient]); |
| 152 | + |
| 153 | + return { |
| 154 | + schemaData, |
| 155 | + isLoading, |
| 156 | + dataSource, |
| 157 | + hasLiveSchema, |
| 158 | + syncFromDatabase, |
| 159 | + refetch, |
| 160 | + }; |
| 161 | +} |
0 commit comments