Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
import type { ChangeEvent, ReactNode } from "react";
import { useCallback, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useAppStore } from "@/stores/app";
import { MAX_UPLOAD_FILE_SIZE_MB } from "@/utils";
import { FileContentPreviewModal } from "./FileContentPreviewModal";
interface SQLUploadButtonProps {
iconOnly?: boolean;
className?: string;
children?: ReactNode;
onUpdateSql: (text: string, filename: string) => void;
}
/**
* Hidden `<input type="file">` triggered by clicking the button. After
* the user picks a file, mounts a preview modal that decodes + shows
* the content; the parent receives the final text via `onUpdateSql`.
*/
export function SQLUploadButton({
iconOnly,
className,
children,
onUpdateSql,
}: SQLUploadButtonProps) {
const { t } = useTranslation();
const inputRef = useRef<HTMLInputElement>(null);
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const cleanup = useCallback(() => {
setSelectedFile(null);
if (inputRef.current) {
inputRef.current.value = "";
}
}, []);
const handleClick = useCallback(() => {
inputRef.current?.click();
}, []);
const handleUpload = useCallback(
(event: ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
const cleanupInput = () => {
// Selecting the same file twice doesn't fire `change` again,
// so reset the value here too.
if (inputRef.current) {
inputRef.current.value = "";
}
};
if (!file) {
cleanupInput();
return;
}
if (file.size > MAX_UPLOAD_FILE_SIZE_MB * 1024 * 1024) {
useAppStore.getState().notify({
module: "bytebase",
style: "CRITICAL",
title: t("issue.upload-sql-file-max-size-exceeded", {
size: `${MAX_UPLOAD_FILE_SIZE_MB}MB`,
}),
});
cleanupInput();
return;
}
setSelectedFile(file);
cleanupInput();
},
[t]
);
const handleConfirm = useCallback(
(statement: string) => {
if (selectedFile) {
onUpdateSql(statement, selectedFile.name);
}
cleanup();
},
[onUpdateSql, selectedFile, cleanup]
);
return (
<>
<Button
type="button"
appearance="secondary"
size="sm"
className={className}
onClick={handleClick}
>
{children}
{iconOnly ? null : (
<span className="ml-1">{t("sql-editor.upload-file")}</span>
)}
</Button>
<Input
ref={inputRef}
type="file"
accept=".sql,.txt,application/sql,text/plain"
className="hidden"
onChange={handleUpload}
/>
{selectedFile ? (
<FileContentPreviewModal
file={selectedFile}
open
onCancel={cleanup}
onConfirm={handleConfirm}
/>
) : null}
</>
);
}