datapeek 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,361 @@
1
+ import {
2
+ connect,
3
+ disconnect,
4
+ executeQuery,
5
+ getConnection,
6
+ testConnection
7
+ } from "./chunk-7G2KHS5I.js";
8
+
9
+ // src/server/index.ts
10
+ import express from "express";
11
+ import cors from "cors";
12
+ import path from "path";
13
+ import { fileURLToPath } from "url";
14
+
15
+ // src/server/routes/connection.ts
16
+ import { Router } from "express";
17
+ var connectionRoutes = Router();
18
+ connectionRoutes.post("/test", async (req, res) => {
19
+ const timeout = setTimeout(() => {
20
+ if (!res.headersSent) {
21
+ res.status(408).json({
22
+ success: false,
23
+ message: "Connection test timeout"
24
+ });
25
+ }
26
+ }, 1e4);
27
+ try {
28
+ const config = req.body;
29
+ await testConnection(config);
30
+ clearTimeout(timeout);
31
+ if (!res.headersSent) {
32
+ res.json({ success: true, message: "Connection successful" });
33
+ }
34
+ } catch (error) {
35
+ clearTimeout(timeout);
36
+ if (!res.headersSent) {
37
+ res.status(400).json({
38
+ success: false,
39
+ message: error.message || "Connection failed"
40
+ });
41
+ }
42
+ }
43
+ });
44
+ connectionRoutes.get("/provided", (req, res) => {
45
+ const connString = getProvidedConnectionString();
46
+ res.json({ connectionString: connString || null });
47
+ });
48
+ connectionRoutes.post("/", async (req, res) => {
49
+ const timeout = setTimeout(() => {
50
+ if (!res.headersSent) {
51
+ res.status(408).json({
52
+ success: false,
53
+ message: "Connection timeout"
54
+ });
55
+ }
56
+ }, 15e3);
57
+ try {
58
+ const config = req.body;
59
+ await connect(config);
60
+ clearTimeout(timeout);
61
+ if (!res.headersSent) {
62
+ res.json({ success: true, message: "Connected" });
63
+ }
64
+ } catch (error) {
65
+ clearTimeout(timeout);
66
+ if (!res.headersSent) {
67
+ res.status(400).json({
68
+ success: false,
69
+ message: error.message || "Connection failed"
70
+ });
71
+ }
72
+ }
73
+ });
74
+ connectionRoutes.delete("/", async (req, res) => {
75
+ try {
76
+ await disconnect();
77
+ res.json({ success: true, message: "Disconnected" });
78
+ } catch (error) {
79
+ res.status(500).json({
80
+ success: false,
81
+ message: error.message || "Disconnect failed"
82
+ });
83
+ }
84
+ });
85
+ connectionRoutes.get("/status", async (req, res) => {
86
+ try {
87
+ const { getConnection: getConnection2, executeQuery: executeQuery2 } = await import("./mssql-7KV6MCZK.js");
88
+ const pool = getConnection2();
89
+ if (pool && pool.connected) {
90
+ try {
91
+ const result = await executeQuery2("SELECT DB_NAME() as databaseName");
92
+ const databaseName = result[0]?.databaseName || null;
93
+ res.json({ connected: true, databaseName });
94
+ } catch {
95
+ res.json({ connected: true, databaseName: null });
96
+ }
97
+ } else {
98
+ res.json({ connected: false });
99
+ }
100
+ } catch {
101
+ res.json({ connected: false });
102
+ }
103
+ });
104
+
105
+ // src/server/routes/tables.ts
106
+ import { Router as Router2 } from "express";
107
+ import sql from "mssql";
108
+ var tableRoutes = Router2();
109
+ tableRoutes.get("/", async (req, res) => {
110
+ try {
111
+ const pool = getConnection();
112
+ if (!pool || !pool.connected) {
113
+ return res.status(400).json({ error: "Not connected to database" });
114
+ }
115
+ const query = `
116
+ SELECT
117
+ TABLE_SCHEMA as schemaName,
118
+ TABLE_NAME as tableName
119
+ FROM INFORMATION_SCHEMA.TABLES
120
+ WHERE TABLE_TYPE = 'BASE TABLE'
121
+ ORDER BY TABLE_SCHEMA, TABLE_NAME
122
+ `;
123
+ const result = await executeQuery(query);
124
+ res.json(result);
125
+ } catch (error) {
126
+ res.status(500).json({ error: error.message || "Failed to fetch tables" });
127
+ }
128
+ });
129
+ tableRoutes.get("/:schema/:table", async (req, res) => {
130
+ try {
131
+ const { schema, table } = req.params;
132
+ const pool = getConnection();
133
+ if (!pool || !pool.connected) {
134
+ return res.status(400).json({ error: "Not connected to database" });
135
+ }
136
+ const query = `
137
+ SELECT
138
+ c.COLUMN_NAME as columnName,
139
+ c.DATA_TYPE as dataType,
140
+ c.CHARACTER_MAXIMUM_LENGTH as maxLength,
141
+ c.IS_NULLABLE as isNullable,
142
+ c.COLUMN_DEFAULT as defaultValue,
143
+ CASE WHEN pk.COLUMN_NAME IS NOT NULL THEN 1 ELSE 0 END as isPrimaryKey
144
+ FROM INFORMATION_SCHEMA.COLUMNS c
145
+ LEFT JOIN (
146
+ SELECT ku.TABLE_SCHEMA, ku.TABLE_NAME, ku.COLUMN_NAME
147
+ FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
148
+ INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE ku
149
+ ON tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
150
+ AND tc.CONSTRAINT_NAME = ku.CONSTRAINT_NAME
151
+ ) pk ON c.TABLE_SCHEMA = pk.TABLE_SCHEMA
152
+ AND c.TABLE_NAME = pk.TABLE_NAME
153
+ AND c.COLUMN_NAME = pk.COLUMN_NAME
154
+ WHERE c.TABLE_SCHEMA = @schema
155
+ AND c.TABLE_NAME = @table
156
+ ORDER BY c.ORDINAL_POSITION
157
+ `;
158
+ const result = await executeQuery(query, [
159
+ { name: "schema", value: schema, type: sql.NVarChar },
160
+ { name: "table", value: table, type: sql.NVarChar }
161
+ ]);
162
+ res.json(result);
163
+ } catch (error) {
164
+ res.status(500).json({ error: error.message || "Failed to fetch table structure" });
165
+ }
166
+ });
167
+ tableRoutes.get("/:schema/:table/data", async (req, res) => {
168
+ try {
169
+ const { schema, table } = req.params;
170
+ const page = parseInt(req.query.page) || 1;
171
+ const pageSize = Math.min(parseInt(req.query.pageSize) || 100, 1e3);
172
+ const sortColumn = req.query.sortColumn;
173
+ const sortDirection = req.query.sortDirection || "asc";
174
+ const offset = (page - 1) * pageSize;
175
+ const pool = getConnection();
176
+ if (!pool || !pool.connected) {
177
+ return res.status(400).json({ error: "Not connected to database" });
178
+ }
179
+ const countQuery = `SELECT COUNT(*) as total FROM [${schema}].[${table}]`;
180
+ const countResult = await executeQuery(countQuery);
181
+ const total = countResult[0]?.total || 0;
182
+ let orderByColumn = sortColumn || "";
183
+ let orderByDirection = sortDirection?.toUpperCase() === "DESC" ? "DESC" : "ASC";
184
+ if (orderByColumn) {
185
+ try {
186
+ const validateQuery = `
187
+ SELECT COLUMN_NAME
188
+ FROM INFORMATION_SCHEMA.COLUMNS
189
+ WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @table AND COLUMN_NAME = @column
190
+ `;
191
+ const validateResult = await executeQuery(validateQuery, [
192
+ { name: "schema", value: schema, type: sql.NVarChar },
193
+ { name: "table", value: table, type: sql.NVarChar },
194
+ { name: "column", value: orderByColumn, type: sql.NVarChar }
195
+ ]);
196
+ if (validateResult.length === 0) {
197
+ orderByColumn = "";
198
+ }
199
+ } catch (e) {
200
+ orderByColumn = "";
201
+ }
202
+ }
203
+ if (!orderByColumn) {
204
+ try {
205
+ const structureQuery = `
206
+ SELECT TOP 1 COLUMN_NAME
207
+ FROM INFORMATION_SCHEMA.COLUMNS
208
+ WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @table
209
+ ORDER BY ORDINAL_POSITION
210
+ `;
211
+ const structureResult = await executeQuery(structureQuery, [
212
+ { name: "schema", value: schema, type: sql.NVarChar },
213
+ { name: "table", value: table, type: sql.NVarChar }
214
+ ]);
215
+ if (structureResult.length > 0) {
216
+ orderByColumn = structureResult[0].COLUMN_NAME;
217
+ }
218
+ } catch (e) {
219
+ }
220
+ }
221
+ let data;
222
+ let generatedQuery = "";
223
+ if (orderByColumn) {
224
+ generatedQuery = `SELECT * FROM [${schema}].[${table}]
225
+ ORDER BY [${orderByColumn}] ${orderByDirection}
226
+ OFFSET ${offset} ROWS
227
+ FETCH NEXT ${pageSize} ROWS ONLY`;
228
+ const dataQuery = `
229
+ SELECT * FROM [${schema}].[${table}]
230
+ ORDER BY [${orderByColumn}] ${orderByDirection}
231
+ OFFSET @offset ROWS
232
+ FETCH NEXT @pageSize ROWS ONLY
233
+ `;
234
+ data = await executeQuery(dataQuery, [
235
+ { name: "offset", value: offset, type: sql.Int },
236
+ { name: "pageSize", value: pageSize, type: sql.Int }
237
+ ]);
238
+ } else {
239
+ generatedQuery = `SELECT * FROM (
240
+ SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) as rn
241
+ FROM [${schema}].[${table}]
242
+ ) t
243
+ WHERE rn > ${offset} AND rn <= ${offset + pageSize}
244
+ ORDER BY rn`;
245
+ const dataQuery = `
246
+ SELECT * FROM (
247
+ SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) as rn
248
+ FROM [${schema}].[${table}]
249
+ ) t
250
+ WHERE rn > @offset AND rn <= @offset + @pageSize
251
+ ORDER BY rn
252
+ `;
253
+ data = await executeQuery(dataQuery, [
254
+ { name: "offset", value: offset, type: sql.Int },
255
+ { name: "pageSize", value: pageSize, type: sql.Int }
256
+ ]);
257
+ data = data.map((row) => {
258
+ const { rn, ...rest } = row;
259
+ return rest;
260
+ });
261
+ }
262
+ res.json({
263
+ data,
264
+ query: generatedQuery,
265
+ pagination: {
266
+ page,
267
+ pageSize,
268
+ total,
269
+ totalPages: Math.ceil(total / pageSize)
270
+ }
271
+ });
272
+ } catch (error) {
273
+ console.error("Error fetching table data:", error);
274
+ const errorMessage = error.message || "Failed to fetch table data";
275
+ const errorDetails = error.originalError?.message || error.originalError?.info?.message || "";
276
+ res.status(500).json({
277
+ error: errorMessage,
278
+ details: errorDetails
279
+ });
280
+ }
281
+ });
282
+
283
+ // src/server/routes/query.ts
284
+ import { Router as Router3 } from "express";
285
+ var queryRoutes = Router3();
286
+ queryRoutes.post("/", async (req, res) => {
287
+ try {
288
+ const { query: sqlQuery } = req.body;
289
+ if (!sqlQuery || typeof sqlQuery !== "string") {
290
+ return res.status(400).json({ error: "Query is required" });
291
+ }
292
+ const trimmedQuery = sqlQuery.trim().toUpperCase();
293
+ if (!trimmedQuery.startsWith("SELECT")) {
294
+ return res.status(400).json({
295
+ error: "Only SELECT queries are allowed (read-only mode)"
296
+ });
297
+ }
298
+ const dangerousKeywords = ["DROP", "DELETE", "INSERT", "UPDATE", "ALTER", "CREATE", "TRUNCATE", "EXEC", "EXECUTE"];
299
+ const hasDangerousKeyword = dangerousKeywords.some(
300
+ (keyword) => trimmedQuery.includes(keyword)
301
+ );
302
+ if (hasDangerousKeyword) {
303
+ return res.status(400).json({
304
+ error: "Query contains prohibited keywords. Only SELECT queries are allowed."
305
+ });
306
+ }
307
+ const result = await executeQuery(sqlQuery);
308
+ res.json({ data: result });
309
+ } catch (error) {
310
+ res.status(500).json({
311
+ error: error.message || "Query execution failed",
312
+ details: error.originalError?.message
313
+ });
314
+ }
315
+ });
316
+
317
+ // src/server/index.ts
318
+ var __filename = fileURLToPath(import.meta.url);
319
+ var __dirname = path.dirname(__filename);
320
+ var providedConnectionString;
321
+ async function startServer(port, connectionString) {
322
+ providedConnectionString = connectionString;
323
+ const app = express();
324
+ app.use(cors());
325
+ app.use(express.json());
326
+ app.use("/api/connect", connectionRoutes);
327
+ app.use("/api/tables", tableRoutes);
328
+ app.use("/api/query", queryRoutes);
329
+ if (process.env.NODE_ENV === "production") {
330
+ const clientDist = path.join(__dirname, "../client");
331
+ app.use(express.static(clientDist));
332
+ app.get("*", (req, res) => {
333
+ if (req.path.startsWith("/api")) {
334
+ return res.status(404).json({ error: "Not found" });
335
+ }
336
+ res.sendFile(path.join(clientDist, "index.html"));
337
+ });
338
+ }
339
+ app.get("/api/health", (req, res) => {
340
+ res.json({ status: "ok", hasConnectionString: !!providedConnectionString });
341
+ });
342
+ return new Promise((resolve, reject) => {
343
+ const server = app.listen(port, () => {
344
+ resolve(app);
345
+ });
346
+ server.on("error", (error) => {
347
+ if (error.code === "EADDRINUSE") {
348
+ reject(new Error(`Port ${port} is already in use`));
349
+ } else {
350
+ reject(error);
351
+ }
352
+ });
353
+ });
354
+ }
355
+ function getProvidedConnectionString() {
356
+ return providedConnectionString;
357
+ }
358
+ export {
359
+ getProvidedConnectionString,
360
+ startServer
361
+ };
@@ -0,0 +1,16 @@
1
+ import {
2
+ connect,
3
+ disconnect,
4
+ executeQuery,
5
+ getConnection,
6
+ parseConnectionString,
7
+ testConnection
8
+ } from "./chunk-7G2KHS5I.js";
9
+ export {
10
+ connect,
11
+ disconnect,
12
+ executeQuery,
13
+ getConnection,
14
+ parseConnectionString,
15
+ testConnection
16
+ };
@@ -0,0 +1,16 @@
1
+ import {
2
+ connect,
3
+ disconnect,
4
+ executeQuery,
5
+ getConnection,
6
+ parseConnectionString,
7
+ testConnection
8
+ } from "./chunk-XMPF5YCJ.js";
9
+ export {
10
+ connect,
11
+ disconnect,
12
+ executeQuery,
13
+ getConnection,
14
+ parseConnectionString,
15
+ testConnection
16
+ };
package/package.json ADDED
@@ -0,0 +1,67 @@
1
+ {
2
+ "name": "datapeek",
3
+ "version": "0.1.1",
4
+ "description": "A local SQL database browser CLI tool",
5
+ "type": "module",
6
+ "bin": {
7
+ "datapeek": "./dist/cli/index.js"
8
+ },
9
+ "engines": {
10
+ "node": ">=18.0.0"
11
+ },
12
+ "main": "./dist/server/index.js",
13
+ "files": [
14
+ "dist",
15
+ "package.json",
16
+ "README.md"
17
+ ],
18
+ "scripts": {
19
+ "dev": "concurrently -n server,client -c blue,green \"npm run dev:server\" \"npm run dev:client\"",
20
+ "dev:server": "tsup src/server/dev.ts && concurrently --kill-others \"tsup src/server/dev.ts --watch\" \"nodemon dist/server/dev.js\"",
21
+ "dev:client": "vite --open",
22
+ "build": "npm run build:client && npm run build:server",
23
+ "build:client": "vite build",
24
+ "build:server": "tsup",
25
+ "prepublishOnly": "npm run build"
26
+ },
27
+ "keywords": [
28
+ "sql",
29
+ "database",
30
+ "browser",
31
+ "cli",
32
+ "mssql"
33
+ ],
34
+ "author": "",
35
+ "license": "MIT",
36
+ "dependencies": {
37
+ "commander": "^12.1.0",
38
+ "cors": "^2.8.5",
39
+ "express": "^4.21.2",
40
+ "mssql": "^11.0.1",
41
+ "open": "^10.1.0"
42
+ },
43
+ "devDependencies": {
44
+ "@monaco-editor/react": "^4.6.0",
45
+ "@tanstack/react-query": "^5.62.11",
46
+ "@tanstack/react-table": "^8.20.5",
47
+ "@types/cors": "^2.8.17",
48
+ "@types/express": "^5.0.0",
49
+ "@types/node": "^22.10.5",
50
+ "@types/react": "^18.3.18",
51
+ "@types/react-dom": "^18.3.5",
52
+ "@vitejs/plugin-react": "^4.3.4",
53
+ "autoprefixer": "^10.4.20",
54
+ "clsx": "^2.1.1",
55
+ "concurrently": "^9.1.2",
56
+ "nodemon": "^3.1.9",
57
+ "lucide-react": "^0.468.0",
58
+ "postcss": "^8.4.49",
59
+ "react": "^18.3.1",
60
+ "react-dom": "^18.3.1",
61
+ "tailwindcss": "^3.4.17",
62
+ "tailwindcss-animate": "^1.0.7",
63
+ "tsup": "^8.3.5",
64
+ "typescript": "^5.7.2",
65
+ "vite": "^6.0.5"
66
+ }
67
+ }