File size: 4,301 Bytes
5534d69
8aa5ded
5534d69
 
 
 
 
 
6f88283
5534d69
 
8aa5ded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5534d69
8aa5ded
5534d69
 
8aa5ded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5534d69
 
 
 
 
 
 
 
 
 
 
8aa5ded
5534d69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8aa5ded
5534d69
8aa5ded
 
 
 
 
 
 
5534d69
 
 
 
8aa5ded
 
5534d69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8aa5ded
 
 
 
5534d69
 
8aa5ded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5534d69
 
 
 
 
8aa5ded
 
 
 
 
 
 
 
 
5534d69
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import { AsyncDuckDB, AsyncDuckDBConnection } from "@duckdb/duckdb-wasm";
import { useCallback, useEffect, useRef, useState } from "react";

// https://duckdb.org/docs/api/wasm/query#arrow-table-to-json
// TODO: import the arrow lib and use the correct type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const arrowResultToJson = (arrowResult: any) => {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  return arrowResult.toArray().map((row: any) => row.toJSON()) || [];
};

export const useParquetTable = (
  db: AsyncDuckDB | null,
  {
    datasetUrl,
    datasetQuery,
    setDatasetQuery: _setDatasetQuery,
    onQueryChanged,
  }: {
    datasetUrl: string;
    datasetQuery: string;
    setDatasetQuery: (query: string) => void;
    onQueryChanged?: (query: string) => void;
  }
) => {
  const [datasetLoaded, setDatasetLoaded] = useState(false);
  const [loading, setLoading] = useState(false);
  const [querying, setQuerying] = useState(false);
  const [dataset, setDataset] = useState<null>(null);
  const [error, setError] = useState<string | null>(null);
  const onQueryChangedRef = useRef(onQueryChanged);
  useEffect(() => {
    onQueryChangedRef.current = onQueryChanged;
  }, [onQueryChanged]);
  const datasetQueryRef = useRef(datasetQuery);
  useEffect(() => {
    datasetQueryRef.current = datasetQuery;
  }, [datasetQuery]);
  const setDatasetQuery = useCallback(
    (query: string) => {
      _setDatasetQuery(query);
      onQueryChangedRef.current?.(query);
    },
    [_setDatasetQuery, onQueryChangedRef]
  );

  const clearDataset = useCallback(() => {
    setDataset(null);
    setError(null);
  }, []);

  const loadDataset = useCallback(() => {
    if (db && datasetUrl) {
      setLoading(true);
      setDataset(null);
      setError(null);
      setDatasetLoaded(false);
      console.log("Loading", datasetUrl);
      const status: { conn: AsyncDuckDBConnection | null; killed: boolean } = {
        conn: null,
        killed: false,
      };
      db.connect().then((conn) => {
        if (status.killed) {
          conn.close();
          return;
        }
        status.conn = conn;
        conn
          // we get httpfs for free with cors restrictions
          // we get parquet downloaded as we load it
          // https://duckdb.org/docs/api/wasm/extensions
          // https://duckdb.org/docs/api/wasm/data_ingestion#parquet
          .query(
            `LOAD parquet;LOAD httpfs;DROP TABLE IF EXISTS dataset;CREATE TABLE dataset AS SELECT * FROM '${datasetUrl}';`
          )
          .then(() => {
            setDatasetLoaded(true);
            if (!datasetQueryRef.current) {
              console.log("Setting default query");
              setDatasetQuery(`SELECT * FROM dataset LIMIT 10;`);
            }
          })
          .catch((err) => {
            console.error(err);
            setError(err.message);
            setDataset(null);
            setDatasetLoaded(false);
            setDatasetQuery("");
          })
          .finally(() => {
            conn.close();
            setLoading(false);
          });
      });

      return () => {
        status.killed = true;
        if (status.conn) {
          console.log("Closing connection");
          status.conn.close();
        }
      };
    } else if (db) {
      console.log("Resetting db");
      setDataset(null);
      setError(null);
      setDatasetLoaded(false);
      setDatasetQuery("");
      db.reset();
    }
  }, [db, datasetUrl, setDatasetQuery, datasetQueryRef]);

  const performQuery = useCallback(
    (query: string) => {
      if (db && datasetLoaded) {
        setQuerying(true);
        db.connect()
          .then((conn) => {
            conn
              .query(query)
              .then((result) => setDataset(arrowResultToJson(result)))
              .catch(setError);
          })
          .finally(() => setQuerying(false));
      }
    },
    [db, datasetLoaded]
  );

  useEffect(() => {
    if (datasetLoaded && datasetQuery) {
      performQuery(datasetQuery);
    }
  }, [datasetLoaded, datasetQuery, performQuery]);

  useEffect(() => {
    loadDataset();
  }, [loadDataset]);

  return {
    loading,
    dataset,
    error,
    clearDataset,
    loadDataset,
    querying,
    performQuery,
  };
};