Edits history of script submission #22647 for ' Execute SQL Statement (databricks)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    export type DynSelect_warehouse_id = string
    
    // Dropdown of the workspace's SQL warehouses so users pick by name instead of typing the id.
    export async function warehouse_id(auth: RT.Databricks) {
      const base = auth.workspace_url.replace(/\/$/, "")
      const response = await fetch(`${base}/api/2.0/sql/warehouses`, {
        headers: {
          Authorization: `Bearer ${auth.token}`,
          Accept: "application/json",
        },
      })
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
      const { warehouses } = (await response.json()) as {
        warehouses?: { id: string; name?: string; state?: string }[]
      }
      return (warehouses ?? []).map((w) => ({
        value: w.id,
        label: `${w.name ?? w.id} (${w.state ?? "?"})`,
      }))
    }
    
    /**
     * Execute SQL Statement
     * Run a SQL statement on a SQL warehouse. If it finishes within wait_timeout (5s-50s, e.g. "30s") results are returned inline under result.data_array; otherwise the response carries a statement_id with status.state PENDING/RUNNING — poll Get SQL Statement until SUCCEEDED.
     */
    export async function main(
      auth: RT.Databricks,
      warehouse_id: DynSelect_warehouse_id,
      statement: string,
      catalog: string | undefined,
      schema: string | undefined,
      wait_timeout: string | undefined
    ) {
      const base = auth.workspace_url.replace(/\/$/, "")
      const url = new URL(`${base}/api/2.0/sql/statements/`)
    
      const body: { [key: string]: any } = { warehouse_id, statement }
      if (catalog !== undefined && catalog !== "") body.catalog = catalog
      if (schema !== undefined && schema !== "") body.schema = schema
      if (wait_timeout !== undefined && wait_timeout !== "")
        body.wait_timeout = wait_timeout
    
      const response = await fetch(url, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${auth.token}`,
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify(body),
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 5 days ago