-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuploadLexicon.js
More file actions
178 lines (159 loc) · 4.85 KB
/
uploadLexicon.js
File metadata and controls
178 lines (159 loc) · 4.85 KB
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
const fs = require("fs");
const csv = require("csv-parser");
const { Client } = require("pg");
// PostgreSQL connection
const client = new Client({
connectionString:
"postgresql://postgres:pwordQ@mainline.proxy.rlwy.net:28582/railway",
});
// Configurable defaults
const TYPE = "lexicon";
const DEFAULT_ALIASES = [];
const DEFAULT_VIDEO_URL = "";
const SUBMITTER_NAME = "Roma";
const SUBMITTER_EMAIL = "roma@f3nation.com";
// 🧱 Ensure required tables exist
async function ensureSchema() {
const schema = `
CREATE TABLE IF NOT EXISTS entries (
id SERIAL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
definition TEXT NOT NULL,
type VARCHAR(50) NOT NULL,
aliases JSONB DEFAULT '[]'::jsonb,
video_url VARCHAR(255) DEFAULT ''
);
CREATE TABLE IF NOT EXISTS tags (
id SERIAL PRIMARY KEY,
name VARCHAR(255) UNIQUE NOT NULL
);
CREATE TABLE IF NOT EXISTS user_submissions (
id SERIAL PRIMARY KEY,
submission_type VARCHAR(50) NOT NULL,
data JSONB NOT NULL,
submitter_name VARCHAR(255),
submitter_email VARCHAR(255),
timestamp TIMESTAMP NOT NULL DEFAULT now(),
status VARCHAR(50) NOT NULL DEFAULT 'pending'
);
`;
try {
await client.query(schema);
console.log("Database schema ensured.");
} catch (error) {
console.error("❌ Error ensuring database schema:", error);
throw error; // Re-throw to halt execution
}
}
async function insertEntry(title, definition) {
try {
const res = await client.query(
`INSERT INTO entries (title, definition, type, aliases, video_url)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT DO NOTHING
RETURNING id`,
[
title,
definition,
TYPE,
JSON.stringify(DEFAULT_ALIASES),
DEFAULT_VIDEO_URL,
],
);
if (res.rows.length) {
console.log(
`✅ Inserted entry for "${title}" with ID: ${res.rows[0].id}`,
);
} else {
console.log(
`⚠️ Entry for "${title}" already exists, skipping insertion.`,
);
}
return res.rows.length ? res.rows[0].id : null;
} catch (e) {
console.error(`❌ Error inserting entry for "${title}":`, e.message);
throw e; // Re-throw to handle errors in calling function
}
}
async function insertSubmission(payload) {
try {
await client.query(
`INSERT INTO user_submissions (submission_type, data, submitter_name, submitter_email)
VALUES ($1, $2, $3, $4)`,
["xicon_upload", payload, SUBMITTER_NAME, SUBMITTER_EMAIL],
);
console.log(`✅ Inserted submission for "${payload.title}".`);
} catch (error) {
console.error(
`❌ Error inserting submission for "${payload.title}":`,
error.message,
);
throw error; // Re-throw to handle errors in calling function
}
}
function cleanQuotes(text) {
if (typeof text !== "string") {
return "";
}
return text
.replace(/’/g, `'`)
.replace(/“|â€/g, `"`)
.replace(/—|–/g, "-")
.replace(/â€/g, "")
.replace(/\uFFFD/g, "");
}
async function readCsvFile(filePath) {
return new Promise((resolve, reject) => {
const entries = [];
fs.createReadStream(filePath)
.pipe(csv({ mapHeaders: ({ header }) => header.trim() }))
.on("data", (row) => entries.push(row))
.on("end", () => resolve(entries))
.on("error", (error) => reject(error));
});
}
async function processCSV(filePath) {
try {
await client.connect();
console.log("Database connected.");
await ensureSchema();
const entries = await readCsvFile(filePath);
console.log(`Read ${entries.length} entries from CSV.`);
for (const row of entries) {
const title = row["Title"]?.trim();
const definition = cleanQuotes(row["Text"]?.trim() || "");
const tags = []; // Lexicon has no tags
if (!title || !definition) {
console.warn(`⚠️ Skipping row with missing title or definition:`, row);
continue;
}
// We don't need the entryId for the submission in this case,
// but insertEntry still ensures the entry exists.
await insertEntry(title, definition);
const payload = {
title,
definition,
type: TYPE,
tags,
aliases: DEFAULT_ALIASES,
video_url: DEFAULT_VIDEO_URL,
};
await insertSubmission(payload);
}
console.log("🎉 Lexicon upload complete.");
} catch (error) {
console.error("❌ An error occurred during the CSV processing:", error);
} finally {
await client.end();
console.log("Database connection closed.");
}
}
// 🚀 Run it
(async () => {
const filePath = "lexicon.csv"; // Make sure this is the correct path
if (!fs.existsSync(filePath)) {
console.error(`❌ Error: File not found at ${filePath}`);
process.exit(1); // Exit with an error code
}
await processCSV(filePath);
})();