@@ -60,27 +60,55 @@ export async function query(token: string, sql: string): Promise<QueryResult> {
6060 return data ;
6161}
6262
63- export async function checkToolState ( token : string , datasource : string ) : Promise < ToolState > {
63+ export async function checkToolState ( token : string , datasource ? : string ) : Promise < Record < string , ToolState > > {
6464 try {
65- // First check if data source exists
65+ // Get all data sources
6666 const sources = await listDataSources ( token ) ;
67- const exists = sources . some ( source => source . name === datasource ) ;
67+ const sourceNames = new Set ( sources . map ( source => source . name ) ) ;
68+
69+ // If a specific datasource is requested, only check that one
70+ if ( datasource ) {
71+ let state : ToolState = 'available' ;
72+ if ( sourceNames . has ( datasource ) ) {
73+ state = 'installed' ;
74+ const rows = await query ( token , `SELECT count(*) as count FROM ${ datasource } FORMAT JSON` ) ;
75+ if ( rows . data [ 0 ] ?. count > 0 ) {
76+ state = 'configured' ;
77+ }
78+ }
79+ return { [ datasource ] : state } ;
80+ }
6881
69- if ( ! exists ) {
70- return 'available' ;
82+ // Build a query to check counts for all sources at once
83+ const sourcesArray = Array . from ( sourceNames ) ;
84+ if ( sourcesArray . length === 0 ) {
85+ return { } ;
7186 }
7287
73- // Then check if it has data
74- const result = await query ( token , `SELECT count(*) as count FROM ${ datasource } FORMAT JSON` ) ;
75- const hasData = result . data [ 0 ] ?. count > 0 ;
88+ const unionQuery = sourcesArray
89+ . map ( name => `SELECT '${ name } ' as source, count(*) as count FROM ${ name } ` )
90+ . join ( ' UNION ALL ' ) ;
91+
92+ console . log ( unionQuery ) ;
93+
94+ const result = await query ( token , `${ unionQuery } FORMAT JSON` ) ;
95+ console . log ( result ) ;
96+
97+ // Convert results to state map
98+ const stateMap : Record < string , ToolState > = { } ;
99+ result . data . forEach ( row => {
100+ stateMap [ row . source ] = row . count > 0 ? 'configured' : 'installed' ;
101+ } ) ;
102+ console . log ( stateMap ) ;
76103
77- return hasData ? 'configured' : 'installed' ;
104+ // Add available state for any datasource not in Tinybird
105+ return stateMap ;
78106 } catch ( error ) {
79107 if ( error instanceof InvalidTokenError ) {
80108 throw error ;
81109 }
82- console . error ( 'Error checking tool state :' , error ) ;
83- return 'available' ;
110+ console . error ( 'Error checking tool states :' , error ) ;
111+ return { } ;
84112 }
85113}
86114
0 commit comments