Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

5.2 KB
Raw Blame
import { MakeLogicType, afterMount, connect, kea, key, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
import { teamLogic } from 'scenes/teamLogic'

import { DatabaseSchemaQueryResponse, DatabaseSchemaTable } from '~/queries/schema/schema-general'
import { DataWarehouseViewLink } from '~/types'

import { dataCatalogRelationshipProposalsList } from 'products/data_catalog/frontend/generated/api'
import { DataCatalogRelationshipProposalApi } from 'products/data_catalog/frontend/generated/api.schemas'
import { warehouseSavedQueriesRetrieve } from 'products/data_warehouse/frontend/generated/api'

import { biSourceMetadataLogic } from './biSourceMetadataLogic'

export interface BISourceContextProps {
    table: DatabaseSchemaTable
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface biSourceContextLogicValues {
    database: Required<DatabaseSchemaQueryResponse> | null // databaseTableListLogic
    contextError: boolean
    description: string
    descriptionLoading: boolean
    joins: DataWarehouseViewLink[]
    relationships: {
        hasMore: boolean
        results: DataCatalogRelationshipProposalApi[]
    } | null
    relationshipsLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface biSourceContextLogicActions {
    loadHealth: (_?: void | undefined) => void // biSourceMetadataLogic
    loadDescription: () => any
    loadDescriptionFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadDescriptionSuccess: (
        description: string,
        payload?: any
    ) => {
        description: string
        payload?: any
    }
    loadRelationships: () => any
    loadRelationshipsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadRelationshipsSuccess: (
        relationships: {
            hasMore: boolean
            results: DataCatalogRelationshipProposalApi[]
        },
        payload?: any
    ) => {
        relationships: {
            hasMore: boolean
            results: DataCatalogRelationshipProposalApi[]
        }
        payload?: any
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface biSourceContextLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        joins: (database: Required<DatabaseSchemaQueryResponse> | null, arg: any) => DataWarehouseViewLink[]
    }
}

export type biSourceContextLogicType = MakeLogicType<
    biSourceContextLogicValues,
    biSourceContextLogicActions,
    BISourceContextProps,
    biSourceContextLogicMeta
>

export const biSourceContextLogic = kea<biSourceContextLogicType>([
    props({} as BISourceContextProps),
    key(({ table }) => table.id + ':' + table.name),
    path((key) => ['products', 'business_intelligence', 'biSourceContextLogic', key]),
    connect((props: BISourceContextProps) => ({
        values: [databaseTableListLogic, ['database']],
        actions: [biSourceMetadataLogic(props), ['loadHealth']],
    })),
    loaders(({ props, values }) => ({
        description: [
            '',
            {
                loadDescription: async (): Promise<string> => {
                    const project = String(teamLogic.values.currentTeamId)
                    if (props.table.type === 'view' || props.table.type === 'materialized_view') {
                        return (await warehouseSavedQueriesRetrieve(project, props.table.id)).description ?? ''
                    }
                    return ''
                },
            },
        ],
        relationships: [
            null as { results: DataCatalogRelationshipProposalApi[]; hasMore: boolean } | null,
            {
                loadRelationships: async (): Promise<{
                    results: DataCatalogRelationshipProposalApi[]
                    hasMore: boolean
                }> => {
                    const existing = values.relationships?.results ?? []
                    const result = await dataCatalogRelationshipProposalsList(String(teamLogic.values.currentTeamId), {
                        table_name: props.table.name,
                        limit: 20,
                        offset: existing.length,
                    })
                    return { results: [...existing, ...result.results], hasMore: !!result.next }
                },
            },
        ],
    })),
    reducers({
        contextError: [
            false,
            {
                loadRelationships: () => false,
                loadRelationshipsFailure: () => true,
            },
        ],
    }),
    selectors({
        joins: [
            (s) => [s.database, (_, props) => props.table.name],
            (database: Required<DatabaseSchemaQueryResponse> | null, name) =>
                database?.joins?.filter(
                    (join) => join.source_table_name === name || join.joining_table_name === name
                ) ?? [],
        ],
    }),
    afterMount(({ actions }) => {
        actions.loadDescription()
        actions.loadRelationships()
        actions.loadHealth()
    }),
])