All files / kernel-ui/src/components DatabaseInspector.tsx

100% Statements 33/33
90% Branches 18/20
100% Functions 18/18
100% Lines 33/33

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215                                        3x 44x 44x 44x 44x 44x 44x   44x 3x   2x 2x     1x         44x 6x     2x               44x 11x 4x         44x 7x   6x 6x     1x       44x                               1x           15x                                                                     24x     25x 1x               2x                                               8x                                       7x           8x                                                  
import {
  Button,
  ButtonVariant,
  ButtonSize,
  Box,
  Text as TextComponent,
  TextVariant,
  TextColor,
  FontWeight,
  IconName,
} from '@metamask/design-system-react';
import { useEffect, useState, useCallback } from 'react';
 
import { usePanelContext } from '../context/PanelContext.tsx';
import { useDatabase } from '../hooks/useDatabase.ts';
import { Input } from './shared/Input.tsx';
 
/**
 * @returns - The DatabaseInspector component
 */
export const DatabaseInspector: React.FC = () => {
  const { logMessage } = usePanelContext();
  const [sqlQuery, setSqlQuery] = useState('');
  const [tables, setTables] = useState<string[]>([]);
  const [selectedTable, setSelectedTable] = useState<string>('');
  const [tableData, setTableData] = useState<Record<string, string>[]>([]);
  const { fetchTables, fetchTableData, executeQuery } = useDatabase();
 
  const onExecuteQuery = useCallback(() => {
    executeQuery(sqlQuery)
      .then((data: Record<string, string>[]) => {
        setSelectedTable('');
        return setTableData(data);
      })
      .catch((error: Error) =>
        logMessage(`Failed to execute query: ${error.message}`, 'error'),
      );
  }, [executeQuery, logMessage, sqlQuery]);
 
  // Refresh data for selected table
  const refreshData = useCallback(() => {
    fetchTableData(selectedTable)
      .then(setTableData)
      .catch((error: Error) =>
        logMessage(
          `Failed to fetch data for table ${selectedTable}: ${error.message}`,
          'error',
        ),
      );
  }, [fetchTableData, logMessage, selectedTable]);
 
  // Load table data when selected table changes
  useEffect(() => {
    if (selectedTable) {
      refreshData();
    }
  }, [selectedTable, refreshData]);
 
  // Initial load of tables
  useEffect(() => {
    fetchTables()
      .then((tableNames: string[]) => {
        setTables(tableNames);
        return setSelectedTable(tableNames?.[0] ?? '');
      })
      .catch((error: Error) =>
        logMessage(`Failed to fetch tables: ${error.message}`, 'error'),
      );
  }, [fetchTables, logMessage]);
 
  return (
    <Box>
      <Box className="mb-6">
        <Box className="flex flex-col md:flex-row gap-6">
          <Box className="flex flex-col gap-3">
            <TextComponent
              variant={TextVariant.BodySm}
              fontWeight={FontWeight.Medium}
              color={TextColor.TextDefault}
            >
              Select Table
            </TextComponent>
            <Box className="flex gap-3">
              <select
                className="flex items-center h-9 px-3 rounded border border-border-default text-sm bg-background-default text-text-default cursor-pointer transition-colors hover:bg-background-hover focus:outline-none focus:ring-2 focus:ring-primary-default"
                value={selectedTable}
                onChange={(event) => setSelectedTable(event.target.value)}
              >
                <option value="" disabled>
                  Select a table
                </option>
                {tables.map((table) => (
                  <option key={table} value={table}>
                    {table}
                  </option>
                ))}
              </select>
              <Button
                variant={ButtonVariant.Secondary}
                size={ButtonSize.Md}
                startIconName={IconName.Refresh}
                onClick={refreshData}
                isDisabled={!selectedTable}
                className="rounded-md h-9"
                data-testid="refresh-button"
              >
                <TextComponent
                  variant={TextVariant.BodySm}
                  fontWeight={FontWeight.Medium}
                  className="select-none"
                >
                  Refresh
                </TextComponent>
              </Button>
            </Box>
          </Box>
          <Box className="flex flex-col gap-3 flex-1">
            <TextComponent
              variant={TextVariant.BodySm}
              fontWeight={FontWeight.Medium}
              color={TextColor.TextDefault}
            >
              SQL Query
            </TextComponent>
            <Box className="flex gap-3">
              <Input
                value={sqlQuery}
                onChange={(event) => setSqlQuery(event.target.value)}
                placeholder="Enter SQL query..."
                onKeyDown={(event) => {
                  if (event.key === 'Enter' && sqlQuery.trim()) {
                    onExecuteQuery();
                  }
                }}
                data-testid="sql-query-input"
              />
              <Button
                variant={ButtonVariant.Primary}
                size={ButtonSize.Md}
                onClick={() => onExecuteQuery()}
                isDisabled={!sqlQuery.trim()}
                className="rounded-md h-9"
                data-testid="execute-query-button"
              >
                <TextComponent
                  variant={TextVariant.BodySm}
                  fontWeight={FontWeight.Medium}
                  color={TextColor.PrimaryInverse}
                  className="select-none"
                >
                  Execute Query
                </TextComponent>
              </Button>
            </Box>
          </Box>
        </Box>
      </Box>
 
      <Box className="w-full">
        <table className="w-full border-collapse border-t border-muted">
          <thead>
            <tr className="border-b border-muted">
              {Object.keys(tableData[0] ?? {}).map((column, index, array) => (
                <th
                  key={column}
                  className={`text-left py-2 px-3 ${
                    index < array.length - 1 ? 'border-r border-muted' : ''
                  }`}
                >
                  <TextComponent
                    variant={TextVariant.BodyXs}
                    fontWeight={FontWeight.Medium}
                    color={TextColor.TextMuted}
                  >
                    {column}
                  </TextComponent>
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {tableData.map(
              (row, i) =>
                row && (
                  <tr
                    key={i}
                    className="hover:bg-alternative border-b border-muted"
                  >
                    {Object.entries(row).map(([key, value], index, array) => (
                      <td
                        key={key}
                        className={`py-1 px-3 ${
                          index < array.length - 1
                            ? 'border-r border-muted'
                            : ''
                        } ${value?.length > 100 ? 'break-all' : ''}`}
                      >
                        <TextComponent
                          variant={TextVariant.BodyXs}
                          color={TextColor.TextDefault}
                        >
                          {value ?? ''}
                        </TextComponent>
                      </td>
                    ))}
                  </tr>
                ),
            )}
          </tbody>
        </table>
      </Box>
    </Box>
  );
};