Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix loading a schema from registry #489

Merged
merged 16 commits into from
Jan 8, 2024
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
151 changes: 84 additions & 67 deletions frontend/src/components/Editor/Editor.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ import { ForkIndexerModal } from "../Modals/ForkIndexerModal";
import { getLatestBlockHeight } from "../../utils/getLatestBlockHeight";
import { IndexerDetailsContext } from '../../contexts/IndexerDetailsContext';
import { PgSchemaTypeGen } from "../../utils/pgSchemaTypeGen";
import { validateSQLSchema } from "@/utils/validators";
import { validateJSCode, validateSQLSchema } from "@/utils/validators";
import { useDebouncedCallback } from "use-debounce";

const BLOCKHEIGHT_LIMIT = 3600;

Expand Down Expand Up @@ -67,6 +68,7 @@ const Editor = ({
const [diffView, setDiffView] = useState(false);
const [blockView, setBlockView] = useState(false);


const [isExecutingIndexerFunction, setIsExecutingIndexerFunction] = useState(false);

const { height, selectedTab, currentUserAccountId } = useInitialPayload();
Expand All @@ -81,15 +83,53 @@ const Editor = ({
const indexerRunner = useMemo(() => new IndexerRunner(handleLog), []);
const pgSchemaTypeGen = new PgSchemaTypeGen();
const disposableRef = useRef(null);
const debouncedValidateSQLSchema = useDebouncedCallback((_schema) => {
const { error: schemaError } = validateSQLSchema(_schema);
if (!schemaError) {
setError();
}
}, 500);

useEffect(() => {
if (!indexerDetails.code || !indexerDetails.schema) return
const { formattedCode, formattedSchema } = reformatAll(indexerDetails.code, indexerDetails.schema)
setOriginalSQLCode(formattedSchema)
setOriginalIndexingCode(formattedCode)
setIndexingCode(formattedCode)
setSchema(formattedSchema)
}, [indexerDetails.code, indexerDetails.schema]);
if (indexerDetails.code != null) {
(async () => {
const { data: formattedCode, error: codeError } = await validateJSCode(indexerDetails.code)

if (codeError) {
setError("There was an error while formatting your code. Please check the console for more details")
}

setOriginalIndexingCode(formattedCode)
setIndexingCode(formattedCode)
})()
}

}, [indexerDetails.code]);

useEffect(() => {
if (indexerDetails.schema != null) {
(async () => {
const { data: formattedSchema, error: schemaError } = await validateSQLSchema(indexerDetails.schema);
if (schemaError) {
setError("There was an error in your schema. Please check the console for more details")
}

setSchema(formattedSchema)
})();
}
}, [indexerDetails.schema])

useEffect(() => {
(async () => {
const { error: schemaError } = await validateSQLSchema(schema);
const { error: codeError } = await validateJSCode(indexingCode);

if (schemaError) setError("There is an error in your schema. Please check the console for more details")
else if (codeError) setError("There is an error in your code. Please check the console for more details")
else setError();
})()

}, [fileName])

useEffect(() => {
const savedSchema = localStorage.getItem(SCHEMA_STORAGE_KEY);
Expand All @@ -111,23 +151,6 @@ const Editor = ({
attachTypesToMonaco();
}, [schemaTypes, monacoMount]);

const requestLatestBlockHeight = async () => {
const blockHeight = getLatestBlockHeight()
return blockHeight
}

useEffect(() => {
if (fileName === "indexingLogic.js") {
try {
setSchemaTypes(pgSchemaTypeGen.generateTypes(schema));
setError(undefined);
} catch (error) {
console.error("Error generating types for saved schema.\n", error.message);
setError("There was an error with your schema. Check the console for more details.");
}
}
}, [fileName]);

useEffect(() => {
localStorage.setItem(DEBUG_LIST_STORAGE_KEY, heights);
}, [heights]);
Expand All @@ -149,7 +172,6 @@ const Editor = ({
}
}


const forkIndexer = async (indexerName) => {
let code = indexingCode;
setAccountId(currentUserAccountId)
Expand All @@ -163,9 +185,9 @@ const Editor = ({
}

const registerFunction = async (indexerName, indexerConfig) => {
const { data: formattedSchema, error } = await validateSQLSchema(schema);
const { data: formattedSchema, error: schemaError } = await validateSQLSchema(schema);

if (error) {
if (schemaError) {
setError("There was an error in your schema, please check the console for more details");
return;
}
Expand Down Expand Up @@ -217,7 +239,9 @@ const Editor = ({
setSchema(unformatted_schema);
}

reformatAll(unformatted_wrapped_indexing_code, unformatted_schema);
const { formattedCode, formattedSchema } = reformatAll(unformatted_wrapped_indexing_code, unformatted_schema);
setIndexingCode(formattedCode);
setSchema(formattedSchema);
} catch (formattingError) {
console.log(formattingError);
}
Expand All @@ -231,53 +255,38 @@ const Editor = ({
return isUserIndexer ? actionButtonText : "Fork Indexer";
};

const reformatAll = (indexingCode, schema) => {
let formattedCode = indexingCode
let formattedSql = schema;
try {
formattedCode = formatIndexingCode(indexingCode);
setError(undefined);
} catch (error) {
console.error("error", error)
const reformatAll = async (indexingCode, schema) => {
let { formattedCode, codeError } = await validateJSCode(indexingCode);

if (codeError) {
formattedCode = indexingCode
setError("Oh snap! We could not format your code. Make sure it is proper Javascript code.");
}
try {
formattedSql = formatSQL(schema);
setError(undefined);
} catch (error) {
console.error(error);
setError("Could not format your SQL schema. Make sure it is proper SQL DDL");

let { data: formattedSchema, error: schemaError } = await validateSQLSchema(schema);

if (schemaError) {
formattedSchema = schema;
setError("There was an error in your SQL schema. Make sure it is proper SQL DDL");
}
setIndexingCode(formattedCode);
setSchema(formattedSql);
return { formattedCode, formattedSql }

return { formattedCode, formattedSchema }
};

function handleCodeGen() {
try {
setSchemaTypes(pgSchemaTypeGen.generateTypes(schema));
attachTypesToMonaco(); // Just in case schema types have been updated but weren't added to monaco
setError(undefined);
} catch (error) {
console.error("Error generating types for saved schema.\n", error);
} catch (_error) {
console.error("Error generating types for saved schema.\n", _error);
setError("Oh snap! We could not generate types for your SQL schema. Make sure it is proper SQL DDL.");
}
}

async function handleFormating() {
await reformatAll(indexingCode, schema);
}

function handleEditorMount(editor) {
const modifiedEditor = editor.getModifiedEditor();
modifiedEditor.onDidChangeModelContent((_) => {
if (fileName == "indexingLogic.js") {
setIndexingCode(modifiedEditor.getValue());
}
if (fileName == "schema.sql") {
setSchema(modifiedEditor.getValue());
}
});
const { formattedCode, formattedSchema } = await reformatAll(indexingCode, schema);
setIndexingCode(formattedCode);
setSchema(formattedSchema);
}

function handleEditorWillMount(monaco) {
Expand Down Expand Up @@ -306,12 +315,21 @@ const Editor = ({
await indexerRunner.start(startingBlockHeight, indexingCode, schema, schemaName, option)
break
case "latest":
const latestHeight = await requestLatestBlockHeight()
const latestHeight = await getLatestBlockHeight();
if (latestHeight) await indexerRunner.start(latestHeight - 10, indexingCode, schema, schemaName, option)
}
setIsExecutingIndexerFunction(() => false)
}

function handleOnChangeSchema(_schema) {
setSchema(_schema);
debouncedValidateSQLSchema(_schema);
}

function handleOnChangeCode(_code) {
setIndexingCode(_code);
}

return (
<div
style={{
Expand Down Expand Up @@ -364,7 +382,7 @@ const Editor = ({
}}
>
{error && (
<Alert dismissible="true" onClose={() => setError(undefined)} className="px-3 pt-3" variant="danger">
<Alert dismissible="true" onClose={() => setError()} className="px-3 pt-3" variant="danger">
{error}
</Alert>
)}
Expand All @@ -390,15 +408,14 @@ const Editor = ({
indexingCode={indexingCode}
blockView={blockView}
diffView={diffView}
setIndexingCode={setIndexingCode}
setSchema={setSchema}
onChangeCode={handleOnChangeCode}
onChangeSchema={handleOnChangeSchema}
block_details={block_details}
originalSQLCode={originalSQLCode}
originalIndexingCode={originalIndexingCode}
schema={schema}
isCreateNewIndexer={isCreateNewIndexer}
handleEditorWillMount={handleEditorWillMount}
handleEditorMount={handleEditorMount}
/>
</div>
</>}
Expand Down
27 changes: 8 additions & 19 deletions frontend/src/components/Editor/ResizableLayoutEditor.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { defaultCode, defaultSchema } from "../../utils/formatters";
import { useDragResize } from "../../utils/resize";
import GraphqlPlayground from "./../Playground";
import { validateSQLSchema } from "@/utils/validators";
import { useDebouncedCallback } from "use-debounce";

// Define styles as separate objects
const containerStyle = {
Expand Down Expand Up @@ -40,15 +39,14 @@ const ResizableEditor = ({
blockView,
diffView,
consoleView,
setIndexingCode,
setSchema,
onChangeCode,
onChangeSchema,
block_details,
originalSQLCode,
originalIndexingCode,
schema,
indexingCode,
handleEditorWillMount,
handleEditorMount,
isCreateNewIndexer
}) => {
const { firstRef, secondRef, dragBarRef } = useDragResize({
Expand All @@ -59,15 +57,6 @@ const ResizableEditor = ({
sizeThresholdSecond: 60,
});

const debouncedValidateSQLSchema = useDebouncedCallback((_schema) => {
validateSQLSchema(_schema)
}, 1000);

const handleOnChangeSchema = (_schema) => {
setSchema(_schema);
debouncedValidateSQLSchema(_schema);
}

// Render logic based on fileName
const editorComponents = {
GraphiQL: () => <GraphqlPlayground />,
Expand All @@ -88,7 +77,7 @@ const ResizableEditor = ({
defaultValue={defaultCode}
defaultLanguage="typescript"
readOnly={false}
onChange={(text) => setIndexingCode(text)}
onChange={onChangeCode}
handleEditorWillMount={handleEditorWillMount}
/>
),
Expand All @@ -109,7 +98,7 @@ const ResizableEditor = ({
defaultValue={defaultSchema}
defaultLanguage="sql"
readOnly={isCreateNewIndexer === true ? false : false}
onChange={handleOnChangeSchema}
onChange={onChangeSchema}
handleEditorWillMount={undefined}
/>
),
Expand All @@ -136,8 +125,8 @@ export default function ResizableLayoutEditor({
blockView,
diffView,
consoleView,
setIndexingCode,
setSchema,
onChangeCode,
onChangeSchema,
block_details,
originalSQLCode,
originalIndexingCode,
Expand Down Expand Up @@ -169,8 +158,8 @@ export default function ResizableLayoutEditor({
indexingCode={indexingCode}
blockView={blockView}
diffView={diffView}
setIndexingCode={setIndexingCode}
setSchema={setSchema}
onChangeCode={onChangeCode}
onChangeSchema={onChangeSchema}
block_details={block_details}
originalSQLCode={originalSQLCode}
originalIndexingCode={originalIndexingCode}
Expand Down
4 changes: 3 additions & 1 deletion frontend/src/utils/pgSchemaTypeGen.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,10 @@ export class PgSchemaTypeGen {
const schemaSyntaxTree = this.parser.astify(sqlSchema, { database: "Postgresql" });
const dbSchema = {};

const statements = Array.isArray(schemaSyntaxTree) ? schemaSyntaxTree : [schemaSyntaxTree];

// Process each statement in the schema
for (const statement of schemaSyntaxTree) {
for (const statement of statements) {
if (statement.type === "create" && statement.keyword === "table") {
// Process CREATE TABLE statements
const tableName = statement.table[0].table;
Expand Down
30 changes: 27 additions & 3 deletions frontend/src/utils/validators.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { formatSQL } from "./formatters";
import { defaultSchema, formatIndexingCode, formatSQL } from "./formatters";
import { PgSchemaTypeGen } from "./pgSchemaTypeGen";
import { CONTRACT_NAME_REGEX } from '../constants/RegexExp';

Expand All @@ -22,16 +22,40 @@ export function validateContractIds(accountIds) {
* @returns {{ data: string | null, error: string | null }} - An object containing the formatted schema and error (if any).
*/
export async function validateSQLSchema(schema) {
if (!schema) return { data: null, error: null };

if (schema === formatSQL(defaultSchema)) return { data: schema, error: null };

const pgSchemaTypeGen = new PgSchemaTypeGen();

try {
const formattedSchema = await formatSQL(schema);
const formattedSchema = formatSQL(schema);
pgSchemaTypeGen.generateTypes(formattedSchema); // Sanity check

return { data: formattedSchema, error: null }
} catch (error) {

console.error(error.message)
return { data: null, error };
return { data: schema, error };
}
};

/**
* Asynchronously validates and formats JavaScript code.
*
* @param {string} code - The JavaScript code to be validated and formatted.
* @returns {{ data: string | null, error: string | null }} An object containing either the formatted code or an error.
*/
export async function validateJSCode(code) {

if (!code) return { data: null, error: null };

try {
const formattedCode = await formatIndexingCode(code);
return { data: formattedCode, error: null }

} catch (error) {
console.error(error.message)
return { data: schema, error };
}
};