Last active
November 11, 2023 10:56
-
-
Save clodal/8c038974233696b695288146b4e02689 to your computer and use it in GitHub Desktop.
Fetch Supabase Postgres Schema String to Pass to OpenAI Assistant for SQL Queries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** Use this function to get a one-time dump of the database tables and columns to pass to OpenAI to come up with SQL queries. | |
* @link https://cookbook.openai.com/examples/how_to_call_functions_with_chat_models#executing-sql-queries | |
*/ | |
const fetchSupabaseSchemaString = async () => { | |
// make a get request to this route: | |
const schemaResponse = await fetch( | |
`${process.env.NEXT_PUBLIC_SUPABASE_URL}/rest/v1/?apikey=${process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY}`, | |
) | |
const schemaResponseData = await schemaResponse.json() | |
const schemaDefinitions = schemaResponseData.definitions | |
const schemaObject = Object.entries(schemaDefinitions).reduce( | |
(acc, [tableName, tableDefinition]) => { | |
const { properties, required } = tableDefinition | |
const nextProperties = Object.entries(properties).reduce( | |
(acc, [key, value]) => { | |
return { ...acc, [key]: value.type } | |
}, | |
{}, | |
) | |
return { | |
...acc, | |
[tableName]: { properties: nextProperties, required }, | |
} | |
}, | |
{}, | |
) | |
const schemaString = JSON.stringify(schemaObject) | |
return schemaString.replaceAll('"', "'") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment