From 291a97a07855603a0e4feb595ddcc376ee98dc18 Mon Sep 17 00:00:00 2001 From: mike12345567 Date: Wed, 18 Oct 2023 18:57:30 +0100 Subject: [PATCH] Moving getters. --- packages/server/src/sdk/app/tables/getters.ts | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/packages/server/src/sdk/app/tables/getters.ts b/packages/server/src/sdk/app/tables/getters.ts index e69de29bb2..ef7af67f32 100644 --- a/packages/server/src/sdk/app/tables/getters.ts +++ b/packages/server/src/sdk/app/tables/getters.ts @@ -0,0 +1,73 @@ +import { context } from "@budibase/backend-core" +import { BudibaseInternalDB, getTableParams } from "../../../db/utils" +import { + breakExternalTableId, + isExternalTable, + isSQL, +} from "../../../integrations/utils" +import { + Database, + Table, + TableResponse, + TableViewsResponse, +} from "@budibase/types" +import datasources from "../datasources" +import sdk from "../../../sdk" + +export async function getAllInternalTables(db?: Database): Promise { + if (!db) { + db = context.getAppDB() + } + const internalTables = await db.allDocs( + getTableParams(null, { + include_docs: true, + }) + ) + return internalTables.rows.map((tableDoc: any) => ({ + ...tableDoc.doc, + type: "internal", + sourceId: tableDoc.doc.sourceId || BudibaseInternalDB._id, + })) +} + +export async function getAllExternalTables( + datasourceId: any +): Promise> { + const datasource = await datasources.get(datasourceId, { enriched: true }) + if (!datasource || !datasource.entities) { + throw "Datasource is not configured fully." + } + return datasource.entities +} + +export async function getExternalTable( + datasourceId: any, + tableName: any +): Promise { + const entities = await getAllExternalTables(datasourceId) + return entities[tableName] +} + +export async function getTable(tableId: any): Promise
{ + const db = context.getAppDB() + if (isExternalTable(tableId)) { + let { datasourceId, tableName } = breakExternalTableId(tableId) + const datasource = await datasources.get(datasourceId!) + const table = await getExternalTable(datasourceId, tableName) + return { ...table, sql: isSQL(datasource) } + } else { + return db.get(tableId) + } +} + +export function enrichViewSchemas(table: Table): TableResponse { + return { + ...table, + views: Object.values(table.views ?? []) + .map(v => sdk.views.enrichSchema(v, table.schema)) + .reduce((p, v) => { + p[v.name] = v + return p + }, {} as TableViewsResponse), + } +}