-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSqlMinifierAndFormatter.html
More file actions
510 lines (432 loc) · 15.5 KB
/
Copy pathSqlMinifierAndFormatter.html
File metadata and controls
510 lines (432 loc) · 15.5 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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SQL压缩/格式化工具 - JustHTML 只需网页</title>
<script>
/**
* 动态加载(强制去除缓存) CSS 的函数
* @param {string} src - 要加载的 CSS 的 src 链接
* @returns {Promise} 返回一个 Promise 对象,用于处理异步加载
*/
function loadStyle(src) {
return new Promise((resolve, reject) => {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = src + '?v=' + new Date().getTime(); // 使用时间戳避免缓存
link.async = true;
link.onload = resolve;
link.onerror = reject;
document.head.appendChild(link);
});
}
/**
* 动态加载(强制去除缓存) JS 的函数
* @param {string} src - 要加载的 JS 的 src 链接
* @returns {Promise} 返回一个 Promise 对象,用于处理异步加载
*/
function loadScript(src) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = src + '?v=' + new Date().getTime(); // 使用时间戳避免缓存
script.async = true;
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
}
</script>
<script>
loadStyle('../assets/style.css')
let scriptArray = [
"../assets/AddHeader_Tools.js",
"../assets/AddFooter.js",
"../assets/AddIco.js",
"../assets/AutoRun.js",
]
scriptArray.forEach(script => {
loadScript(script);
});
</script>
<script src="../package/Vue/code/vue.global.prod.js"></script>
<script type="module" src="../package/Sober/code/main.js"></script>
<style>
.converter-container {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}
.converter-section {
display: flex;
flex-direction: column;
}
.converter-section textarea {
flex: 1;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin: 15px 0;
}
.info-box {
background-color: var(--bg-tertiary);
padding: 10px;
border-radius: var(--border-radius);
margin: 10px 0;
}
.stats-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 15px;
margin: 15px 0;
}
.stat-item {
padding: 10px;
background-color: var(--bg-secondary);
border-radius: var(--border-radius);
text-align: center;
}
.stat-value {
font-size: 1.5em;
font-weight: bold;
color: var(--accent-color);
}
.stat-label {
font-size: 0.9em;
color: var(--text-secondary);
}
.options-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 15px;
margin: 15px 0;
}
.option-item {
display: flex;
align-items: center;
}
.option-item input[type="checkbox"] {
margin-right: 8px;
}
@media (max-width: 768px) {
.converter-container {
grid-template-columns: 1fr;
}
}
</style>
</head>
<body>
<div id="app">
<div class="container">
<a href="../index.html" class="back-link">← 返回首页</a>
<div class="tool-section">
<h2>SQL压缩/格式化工具</h2>
<p>格式化或压缩SQL代码,使其更易读或更紧凑</p>
<div class="info-box">
<p><strong>功能说明:</strong></p>
<p>• 格式化:使SQL代码结构清晰,易于阅读和编辑</p>
<p>• 压缩:移除不必要的空白和换行,减少文件大小</p>
<p>• 验证:检查SQL代码的基本语法</p>
</div>
<div class="stats-container">
<div class="stat-item">
<div class="stat-value">{{ inputSize }}</div>
<div class="stat-label">原始大小 (字符)</div>
</div>
<div class="stat-item">
<div class="stat-value">{{ outputSize }}</div>
<div class="stat-label">处理后大小 (字符)</div>
</div>
<div class="stat-item">
<div class="stat-value">{{ savedSize }}</div>
<div class="stat-label">节省大小 (字符)</div>
</div>
<div class="stat-item">
<div class="stat-value">{{ savedPercent }}%</div>
<div class="stat-label">压缩率</div>
</div>
</div>
<div class="options-container">
<div class="option-item">
<input type="checkbox" id="uppercaseKeywords" v-model="options.uppercaseKeywords">
<label for="uppercaseKeywords">关键字大写</label>
</div>
<div class="option-item">
<input type="checkbox" id="preserveComments" v-model="options.preserveComments">
<label for="preserveComments">保留注释</label>
</div>
<div class="option-item">
<input type="checkbox" id="indentWithSpaces" v-model="options.indentWithSpaces" checked>
<label for="indentWithSpaces">使用空格缩进</label>
</div>
</div>
<div class="converter-container">
<div class="converter-section">
<h3>原始SQL</h3>
<textarea
v-model="inputSql"
placeholder="在此输入SQL代码..."
rows="15"
></textarea>
</div>
<div class="converter-section">
<h3>处理后的SQL</h3>
<textarea
v-model="outputSql"
placeholder="格式化/压缩后的SQL代码将在这里显示"
rows="15"
readonly
></textarea>
</div>
</div>
<div class="controls">
<button @click="formatSql">格式化SQL</button>
<button @click="minifySql">压缩SQL</button>
<button @click="validateSql">验证SQL</button>
<button @click="copyResult">复制结果</button>
<button @click="clearAll">清空</button>
</div>
<div class="result" v-if="result">
{{ result }}
</div>
<div class="result" v-if="error" style="color: #ff6b6b;">
{{ error }}
</div>
</div>
</div>
</div>
<script>
const { createApp, ref, computed } = Vue;
createApp({
setup() {
const inputSql = ref('');
const outputSql = ref('');
const result = ref('');
const error = ref('');
const options = ref({
uppercaseKeywords: false,
preserveComments: true,
indentWithSpaces: true
});
// 计算属性:统计信息
const inputSize = computed(() => inputSql.value.length);
const outputSize = computed(() => outputSql.value.length);
const savedSize = computed(() => inputSize.value - outputSize.value);
const savedPercent = computed(() => {
if (inputSize.value === 0) return 0;
return Math.round((savedSize.value / inputSize.value) * 100);
});
// 格式化SQL
const formatSql = () => {
error.value = '';
result.value = '';
try {
if (!inputSql.value.trim()) {
outputSql.value = '';
result.value = '输入为空';
return;
}
let sql = inputSql.value;
let comments = [];
// 提取注释(如果需要保留)
if (options.value.preserveComments) {
// 提取 -- 注释
sql = sql.replace(/(--[^\n\r]*)/g, (match) => {
comments.push(match);
return ` /*COMMENT_${comments.length-1}*/ `;
});
// 提取 /* */ 注释
sql = sql.replace(/(\/\*[\s\S]*?\*\/)/g, (match) => {
comments.push(match);
return ` /*COMMENT_${comments.length-1}*/ `;
});
}
// 规范化空格
sql = sql.replace(/\s+/g, ' ').trim();
// 在SQL关键字前后添加换行和适当的缩进
const keywords = [
'SELECT', 'FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'HAVING',
'JOIN', 'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'FULL OUTER JOIN',
'UNION', 'UNION ALL', 'INSERT INTO', 'UPDATE', 'DELETE FROM',
'CREATE TABLE', 'ALTER TABLE', 'DROP TABLE', 'AS'
];
keywords.forEach(keyword => {
const regex = new RegExp(`\\b${keyword}\\b`, 'gi');
sql = sql.replace(regex, `\n${keyword} `);
});
// 特殊处理JOIN相关
sql = sql.replace(/\s+(LEFT|RIGHT|INNER|OUTER)?\s*JOIN\s+/gi, '\n$1 JOIN ');
// 在逗号后换行并增加缩进
sql = sql.replace(/,/g, ',\n ');
// 格式化缩进
let lines = sql.split('\n');
let formattedLines = [];
let indentLevel = 0;
const indent = options.value.indentWithSpaces ? ' ' : '\t';
for (let line of lines) {
line = line.trim();
if (!line) continue;
// 减少缩进
if (line.toUpperCase().includes('FROM') ||
line.toUpperCase().includes('WHERE') ||
line.toUpperCase().includes('GROUP BY') ||
line.toUpperCase().includes('ORDER BY') ||
line.toUpperCase().includes('HAVING')) {
indentLevel = Math.max(0, indentLevel - 1);
}
formattedLines.push(indent.repeat(indentLevel) + line);
// 增加缩进
if (line.toUpperCase().includes('SELECT')) {
indentLevel++;
}
}
sql = formattedLines.join('\n');
// 处理关键字大小写
if (options.value.uppercaseKeywords) {
const sqlKeywords = [
'SELECT', 'FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'HAVING',
'JOIN', 'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'FULL OUTER JOIN',
'UNION', 'UNION ALL', 'INSERT INTO', 'UPDATE', 'DELETE FROM',
'CREATE TABLE', 'ALTER TABLE', 'DROP TABLE', 'AS', 'ON', 'AND', 'OR', 'NOT',
'IN', 'EXISTS', 'BETWEEN', 'LIKE', 'IS NULL', 'IS NOT NULL'
];
sqlKeywords.forEach(keyword => {
const regExp = new RegExp('\\b' + keyword + '\\b', 'gi');
sql = sql.replace(regExp, keyword.toUpperCase());
});
}
// 恢复注释
if (options.value.preserveComments && comments.length > 0) {
for (let i = 0; i < comments.length; i++) {
sql = sql.replace(`/*COMMENT_${i}*/`, comments[i]);
}
}
outputSql.value = sql;
result.value = 'SQL已成功格式化';
} catch (e) {
error.value = `格式化错误: ${e.message}`;
}
};
// 压缩SQL
const minifySql = () => {
error.value = '';
result.value = '';
try {
if (!inputSql.value.trim()) {
outputSql.value = '';
result.value = '输入为空';
return;
}
let sql = inputSql.value;
// 移除注释(如果选项未选择保留)
if (!options.value.preserveComments) {
// 移除 -- 注释
sql = sql.replace(/--.*$/gm, '');
// 移除 /* */ 注释
sql = sql.replace(/\/\*[\s\S]*?\*\//g, '');
}
// 将多个空格替换为单个空格
sql = sql.replace(/\s+/g, ' ');
// 移除括号周围的多余空格
sql = sql.replace(/\s*\(\s*/g, '(');
// 移除分号前的空格
sql = sql.replace(/\s*;/g, ';');
// 移除逗号前的空格
sql = sql.replace(/\s*,/g, ',');
// 移除逗号后的空格
sql = sql.replace(/,\s*/g, ', ');
// 移除换行符
sql = sql.replace(/\n/g, ' ').replace(/\r/g, ' ');
// 清理多余的空格
sql = sql.trim().replace(/\s+/g, ' ');
outputSql.value = sql;
result.value = 'SQL已成功压缩';
} catch (e) {
error.value = `压缩错误: ${e.message}`;
}
};
// 验证SQL
const validateSql = () => {
error.value = '';
result.value = '';
try {
if (!inputSql.value.trim()) {
result.value = '请输入SQL语句';
return;
}
// 简单的SQL语法验证
const upperSql = inputSql.value.toUpperCase();
// 检查是否有基本的SQL结构
if (
!upperSql.includes('SELECT') &&
!upperSql.includes('INSERT') &&
!upperSql.includes('UPDATE') &&
!upperSql.includes('DELETE') &&
!upperSql.includes('CREATE') &&
!upperSql.includes('ALTER') &&
!upperSql.includes('DROP')
) {
result.value = '警告: 未检测到常见的SQL命令 (SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP)';
return;
}
// 检查括号是否匹配
let parenCount = 0;
for (let char of inputSql.value) {
if (char === '(') parenCount++;
if (char === ')') parenCount--;
if (parenCount < 0) break;
}
if (parenCount !== 0) {
error.value = '错误: 括号不匹配';
return;
}
result.value = '✓ SQL语法检查通过';
} catch (e) {
error.value = `验证错误: ${e.message}`;
}
};
// 复制结果
const copyResult = () => {
if (outputSql.value) {
navigator.clipboard.writeText(outputSql.value)
.then(() => {
result.value = 'SQL代码已复制到剪贴板!';
})
.catch(err => {
console.error('复制失败: ', err);
error.value = '复制失败';
});
} else {
error.value = '没有可复制的结果';
}
};
// 清空所有
const clearAll = () => {
inputSql.value = '';
outputSql.value = '';
result.value = '';
error.value = '';
};
return {
inputSql,
outputSql,
result,
error,
options,
inputSize,
outputSize,
savedSize,
savedPercent,
formatSql,
minifySql,
validateSql,
copyResult,
clearAll
};
}
}).mount('#app');
</script>
</body>
</html>