This repository has been archived by the owner on Mar 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
import.js
93 lines (77 loc) · 2.18 KB
/
import.js
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
import fs from "fs"
import path from "path"
import readline from "readline"
import sqlite3 from "sqlite3"
import { open } from "sqlite"
import { Parse, Store } from "n3.ts"
import { parseSchemaString, parse } from "apg"
import { createTables } from "./lib/createTables.js"
import { importInstance } from "./lib/import.js"
function invalidParameters() {
throw new Error(
"Usage: node lib/import.js -s path-to-schema.nq -i path-to-data.nq -o output-path.sqlite"
)
}
let schemaPath = "",
inputPath = null,
outputPath = ""
if (process.argv.length === 8) {
if (
process.argv[2] === "-s" &&
process.argv[4] === "-i" &&
process.argv[6] === "-o"
) {
schemaPath = process.argv[3]
inputPath = process.argv[5]
outputPath = process.argv[7]
} else {
invalidParameters()
}
} else if (process.argv.length === 6) {
if (process.argv[2] === "-s" && process.argv[4] === "-o") {
schemaPath = process.argv[3]
inputPath = null
outputPath = process.argv[5]
} else {
invalidParameters()
}
} else {
invalidParameters()
}
const filename = path.resolve(outputPath)
if (fs.existsSync(filename)) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
const answer = await new Promise((resolve) => {
console.log(`The file ${outputPath} already exists!`)
rl.question(
"Press Enter to delete it and continue; or Ctrl-C to abort:",
resolve
)
})
fs.unlinkSync(filename)
rl.close()
}
const schemaFile = fs.readFileSync(schemaPath, "utf-8")
const schema = parseSchemaString(schemaFile)
if (schema._tag === "Left") {
console.error(schema.left)
throw new Error("schema did not parse")
}
const db = await open({ filename, driver: sqlite3.Database })
// await db.exec("PRAGMA foreign_keys = ON")
await db.exec(createTables(schema.right))
if (inputPath === null) {
process.exit(0)
}
const inputFile = fs.readFileSync(path.resolve(inputPath), "utf-8")
const store = new Store(Parse(inputFile))
const instance = parse(store, schema.right)
if (instance._tag === "Left") {
console.error(instance.left)
console.error(JSON.stringify(instance.left.errors, null, " "))
throw new Error("Instance did not parse")
}
importInstance(db, schema.right, instance.right)