File size: 1,813 Bytes
6491ad4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useEffect, useReducer } from "react";
async function readMigrationFiles({ journal, migrations }) {
  const migrationQueries = [];
  for await (const journalEntry of journal.entries) {
    const query = migrations[`m${journalEntry.idx.toString().padStart(4, "0")}`];
    if (!query) {
      throw new Error(`Missing migration: ${journalEntry.tag}`);
    }
    try {
      const result = query.split("--> statement-breakpoint").map((it) => {
        return it;
      });
      migrationQueries.push({
        sql: result,
        bps: journalEntry.breakpoints,
        folderMillis: journalEntry.when,
        hash: ""
      });
    } catch {
      throw new Error(`Failed to parse migration: ${journalEntry.tag}`);
    }
  }
  return migrationQueries;
}
async function migrate(db, config) {
  const migrations = await readMigrationFiles(config);
  return db.dialect.migrate(migrations, db.session);
}
const useMigrations = (db, migrations) => {
  const initialState = {
    success: false,
    error: void 0
  };
  const fetchReducer = (state2, action) => {
    switch (action.type) {
      case "migrating": {
        return { ...initialState };
      }
      case "migrated": {
        return { ...initialState, success: action.payload };
      }
      case "error": {
        return { ...initialState, error: action.payload };
      }
      default: {
        return state2;
      }
    }
  };
  const [state, dispatch] = useReducer(fetchReducer, initialState);
  useEffect(() => {
    dispatch({ type: "migrating" });
    migrate(db, migrations).then(() => {
      dispatch({ type: "migrated", payload: true });
    }).catch((error) => {
      dispatch({ type: "error", payload: error });
    });
  }, []);
  return state;
};
export {
  migrate,
  useMigrations
};
//# sourceMappingURL=migrator.js.map