Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

4.4 KB
Raw Blame
import { useCallback, useEffect } from "react";
import { useExecuteSQL } from "@/hooks/useExecuteSQL";
import { ReadonlyModeNotSupported } from "@/modules/sql-editor/components/ReadonlyModeNotSupported";
import { useConnectionOfCurrentSQLEditorTab } from "@/modules/sql-editor/hooks/useSQLEditorState";
import { sqlEditorEvents } from "@/modules/sql-editor/model/events";
import {
  getSQLEditorTabsState,
  useIsDisconnected,
  useSQLEditorTabState,
} from "@/modules/sql-editor/store/tab";
import { useAppStore } from "@/stores/app";
import type { SQLEditorQueryParams } from "@/types";
import { Engine } from "@/types/proto-es/v1/common_pb";
import { getInstanceResource, instanceV1HasReadonlyMode } from "@/utils";
import { EditorAction } from "../EditorAction";
import { ExecutingHintModal } from "../ExecutingHintModal";
import { SaveSheetModal } from "../SaveSheetModal";
import { Welcome } from "../Welcome";
import { SQLEditor } from "./SQLEditor";
import { activeStatementRef } from "./state";

interface EditorMainProps {
  /** Open the connection drawer (hosted by SQLEditorHomePage). */
  onChangeConnection: () => void;
}

/**
 * SavedQuery shell:
 *  - Top toolbar (`EditorAction`)
 *  - Body: `SQLEditor` when there's a tab, `Welcome` otherwise
 *  - Two hidden React modal mounts (`ExecutingHintModal`, `SaveSheetModal`)
 *
 * The AI side pane lives in `StandardPanel`.
 */
export function EditorMain({ onChangeConnection }: EditorMainProps) {
  const { instance } = useConnectionOfCurrentSQLEditorTab();

  const tabId = useSQLEditorTabState((s) => s.tabsById.get(s.currentTabId)?.id);
  const isDisconnected = useIsDisconnected();
  const engine = instance.engine;

  const allowReadonlyMode =
    !isDisconnected && instanceV1HasReadonlyMode(engine ?? Engine.MYSQL);

  const { execute } = useExecuteSQL();

  const handleExecute = useCallback(
    ({ params, newTab }: { params: SQLEditorQueryParams; newTab: boolean }) => {
      if (newTab) {
        const tabsState = getSQLEditorTabsState();
        tabsState.cloneTab(tabsState.currentTabId, {
          statement: params.statement,
        });
      }
      requestAnimationFrame(() => {
        void execute(params);
      });
    },
    [execute]
  );

  // Run-from-toolbar: pull the active statement that `SQLEditor`
  // published to `activeStatementRef`.
  const handleExecuteFromActionBar = useCallback(
    (params: SQLEditorQueryParams) => {
      const tabsState = getSQLEditorTabsState();
      const tab = tabsState.tabsById.get(tabsState.currentTabId);
      if (!tab) return;
      const statement =
        activeStatementRef.value || tab.statement || params.statement;
      handleExecute({ params: { ...params, statement }, newTab: false });
    },
    [handleExecute]
  );

  // execute-sql event (fired e.g. from the schema-pane "run" affordance)
  useEffect(() => {
    const off = sqlEditorEvents.on(
      "execute-sql",
      async ({ data: { connection, statement, batchQueryContext } }) => {
        const database = await useAppStore
          .getState()
          .getOrFetchDatabaseByName(connection.database);
        const newTab = getSQLEditorTabsState().addTab(
          { connection, statement, batchQueryContext },
          /* beside */ true
        );
        requestAnimationFrame(() => {
          void execute({
            connection: { ...newTab.connection },
            statement,
            engine: getInstanceResource(database).engine,
            explain: false,
            selection: null,
          });
        });
      }
    );
    return () => {
      off();
    };
  }, [execute]);

  if (!isDisconnected && !allowReadonlyMode) {
    // Connected to an instance without a read-only data source —
    // surface the admin-mode CTA.
    return <ReadonlyModeNotSupported />;
  }

  return (
    <div className="h-full flex flex-col overflow-hidden">
      <EditorAction onExecute={handleExecuteFromActionBar} />
      {tabId ? (
        <div className="flex-1 min-h-0">
          <SQLEditor
            onExecute={(params, newTab) => handleExecute({ params, newTab })}
          />
        </div>
      ) : (
        <div className="flex-1 flex flex-col min-h-0">
          <Welcome onChangeConnection={onChangeConnection} />
        </div>
      )}
      {/* Hidden React modal mounts — their Dialogs portal to overlay
          layer; the inline mounts must not occupy flex space. */}
      <div className="hidden">
        <ExecutingHintModal />
        <SaveSheetModal />
      </div>
    </div>
  );
}