-
Notifications
You must be signed in to change notification settings - Fork 374
/
Copy pathconnection.mjs
461 lines (418 loc) · 13.5 KB
/
connection.mjs
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
import mysql from 'mysql'
import Logger from './logger.mjs'
import fs from 'node:fs'
import path from 'node:path'
import dotenv from 'dotenv'
const logger = new Logger('buildMaterials')
// 先构造出.env*文件的绝对路径
const appDirectory = fs.realpathSync(process.cwd())
const resolveApp = (relativePath) => path.resolve(appDirectory, relativePath)
const pathsDotenv = resolveApp('.env')
// 加载.env.local
dotenv.config({ path: `${pathsDotenv}.local` })
const { SQL_HOST, SQL_PORT, SQL_USER, SQL_PASSWORD, SQL_DATABASE } = process.env
// 组件表名称
const componentsTableName = 't_component'
// 组件关联到物料资产包的id
const materialHistoryId = 1
// 数据库配置
const mysqlConfig = {
host: SQL_HOST, // 主机名(服务器地址)
port: SQL_PORT, // 端口号
user: SQL_USER, // 用户名
password: SQL_PASSWORD, // 密码
database: SQL_DATABASE // 数据库名称
}
class MysqlConnection {
constructor(config) {
this.config = config || mysqlConfig
// 是否连接上了数据库
this.connected = false
this.connection = mysql.createConnection(this.config)
}
connect() {
return new Promise((resolve, reject) => {
this.connection.connect((error) => {
if (error) {
logger.warn('unable to connect to the database, please check the database configuration is correct.')
reject()
} else {
logger.success('database connected.')
this.connected = true
resolve()
}
})
})
}
/**
* 执行sql语句,更新数据库
* @param {string} sql sql语句
* @param {string} componentName 组件名称
*/
query(sql) {
return new Promise((resolve, reject) => {
this.connection.query(sql, (error, result) => {
if (error) {
reject(error)
} else {
resolve(result)
}
})
})
}
/**
* 组件字段映射
* @param {string} field 字段名
* @returns 映射后的字段名
*/
fieldTransform(field) {
const fieldMap = {
docUrl: 'doc_url',
devMode: 'dev_mode',
schema: 'schema_fragment'
}
return fieldMap[field] || field
}
/**
* 格式化单引号
* @param {string} str 待格式化的字符串
* @returns 格式化后的字符串
*/
formatSingleQuoteValue(str) {
if (typeof str !== 'string') {
return str
}
return str.replace(/'/g, "\\'")
}
/**
* 校验组件数据是否有效
* @param {object} component 组件数据
* @returns boolean 校验组件字段是否失败,false-有字段出错
*/
isValid(component, file) {
const longTextFields = ['name', 'npm', 'snippets', 'schema_fragment', 'configure', 'component_metadata']
return Object.entries(component).every(([key, value]) => {
if (longTextFields.includes(key) && value !== null && typeof value !== 'object') {
logger.error(`the value of "${key}" is not valid JSON at ${file}.`)
return false
}
return true
})
}
/**
* 生成更新组件的sql语句
* @param {object} component 组件数据
* @returns 更新组件的sql语句
*/
updateComponent(component, file) {
const valid = this.isValid(component, file)
if (!valid) {
return
}
const values = []
let sqlContent = `update ${componentsTableName} set `
Object.keys(component).forEach((key) => {
const { [key]: value } = component
const fields = [
'version',
'name',
'component',
'icon',
'description',
'docUrl',
'screenshot',
'tags',
'keywords',
'devMode',
'npm',
'group',
'category',
'priority',
'snippets',
'schema',
'configure',
'public',
'framework',
'isOfficial',
'isDefault',
'tiny_reserved',
'tenant',
'createBy',
'updatedBy'
]
if (!fields.includes(key)) {
return
}
const field = this.fieldTransform(key)
let updateContent = ''
if (['id', 'component'].includes(field)) {
return
}
if (value === void 0) {
return
}
if (typeof value === 'string') {
const formatValue = this.formatSingleQuoteValue(value)
updateContent = `\`${field}\` = '${formatValue}'`
} else if (typeof field === 'number' || field === null) {
updateContent = `\`${field}\` = ${value}`
} else {
const formatValue = this.formatSingleQuoteValue(JSON.stringify(value))
updateContent = `\`${field}\` = '${formatValue}'`
}
values.push(updateContent)
})
sqlContent += values.join()
sqlContent += ` where component = '${component.component}';`
this.query(sqlContent, component.component)
.then(() => {
logger.success(`${component.component} updated.`)
})
.catch((error) => {
logger.error(`failed to update ${component.component}: ${error}.`)
})
}
/**
* 新建的组件关联物料资产包
* @deprecated 物料资产包已废弃,使用relationMaterialHistory替代
* @param {number} id 新建的组件id
*/
relationMaterialBlockHistory(id) {
const uniqSql = `SELECT * FROM \`material_histories_components__user_components_mhs\` WHERE \`material-history_id\`=${materialHistoryId} AND \`user-component_id\`=${id}`
this.query(uniqSql).then((result) => {
if (!result.length) {
const sqlContent = `INSERT INTO \`material_histories_components__user_components_mhs\` (\`material-history_id\`, \`user-component_id\`) VALUES (${materialHistoryId}, ${id})`
this.query(sqlContent)
}
})
}
/**
* 新建的组件关联物料资产包
* @param {number} id 新建的组件id
*/
relationMaterialHistory(id) {
const uniqSql = `SELECT * FROM \`r_material_history_component\` WHERE \`material_history_id\`=${materialHistoryId} AND \`component_id\`=${id}`
this.query(uniqSql).then((result) => {
if (!result.length) {
const sqlContent = `INSERT INTO \`r_material_history_component\` (\`material_history_id\`, \`component_id\`) VALUES (${materialHistoryId}, ${id})`
this.query(sqlContent)
}
})
}
/**
* 生成新增组件的sql语句
* @param {object} component 组件数据
* @returns 新增组件的sql语句
*/
insertComponent(component, file) {
const valid = this.isValid(component, file)
if (!valid) {
return
}
const defaultName = {
zh_CN: component.component
}
const defaultNpm = {
package: '',
exportName: '',
version: '1.0.0',
destructuring: true
}
const defaultConfigure = {
loop: true,
condition: true,
styles: true,
isContainer: true,
isModal: false,
nestingRule: {
childWhiteList: '',
parentWhiteList: '',
descendantBlacklist: '',
ancestorWhitelist: ''
},
isNullNode: false,
isLayout: false,
rootSelector: '',
shortcuts: {
properties: ['value', 'disabled']
},
contextMenu: {
actions: ['create symbol'],
disable: ['copy', 'remove']
}
}
const {
version = '1.0.0',
name = defaultName,
component: componentName,
icon,
description,
docUrl,
screenshot,
tags,
keywords,
devMode = 'proCode',
npm = defaultNpm,
group,
category = 'general',
priority = 1,
snippets = [{}],
schema = {},
configure = defaultConfigure,
public: publicRight = 0,
framework = 'vue',
isOfficial = 0,
isDefault = 0,
tiny_reserved = 0,
component_metadata = null,
library_id = 1,
tenant_id = 1,
renter_id = 1,
site_id = 1,
created_by = 1,
last_updated_by = 1
} = component
const values = `('${version}',
'${this.formatSingleQuoteValue(JSON.stringify(name))}',
'${componentName}',
'${icon}',
'${this.formatSingleQuoteValue(description)}',
'${docUrl}',
'${screenshot}',
'${tags}',
'${keywords}',
'${devMode}',
'${this.formatSingleQuoteValue(JSON.stringify(npm))}',
'${group}',
'${category}',
'${priority}',
'${this.formatSingleQuoteValue(JSON.stringify(snippets))}',
'${this.formatSingleQuoteValue(JSON.stringify(schema))}',
'${this.formatSingleQuoteValue(JSON.stringify(configure))}',
'${publicRight}',
'${framework}',
'${isOfficial}',
'${isDefault}',
'${tiny_reserved}',
'${component_metadata}',
'${library_id}',
'${tenant_id}',
'${renter_id}',
'${site_id}',
'${created_by}',
'${last_updated_by}'
);`
const sqlContent = `INSERT INTO ${componentsTableName} (version, name, name_en, icon, description, doc_url,
screenshot, tags, keywords, dev_mode, npm, \`group\`, \`category\`, priority, snippets,
schema_fragment, configure, \`public\`, framework, is_official, is_default, tiny_reserved,component_metadata,
library_id, tenant_id,renter_id,site_id, created_by, last_updated_by) VALUES ${values}`.replace(/\n/g, '')
this.query(sqlContent, componentName)
.then((result) => {
const id = result.insertId
logger.success(`${component.component} added.`)
this.relationMaterialHistory(id)
})
.catch((error) => {
logger.error(`add ${component.component} failed:${error}.`)
})
}
/**
* 初始化数据库数据,判断是否已存在组件,不存在时执行新增组件
* @param {object} component 组件数据
*/
initDB(component) {
const selectSqlContent = `SELECT * FROM ${this.config.database}.${componentsTableName} WHERE name_en = '${component.component}'`
this.query(selectSqlContent)
.then((result) => {
if (!result.length) {
this.insertComponent(component)
}
})
.catch((error) => {
logger.error(`query ${component.component} failed:${error}.`)
})
}
/**
* 创建组件表
* @returns promise
*/
createUserComponentsTable() {
const sqlContent = `
CREATE TABLE ${componentsTableName} (
id int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
version varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
name longtext CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
component varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
icon varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
description varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
doc_url varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
screenshot varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
tags varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
keywords varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
dev_mode varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
npm longtext CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
\`group\` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
category varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
priority int(11) NULL DEFAULT NULL,
snippets longtext CHARACTER SET utf8 COLLATE utf8_general_ci NULL,
schema_fragment longtext CHARACTER SET utf8 COLLATE utf8_general_ci NULL,
configure longtext CHARACTER SET utf8 COLLATE utf8_general_ci NULL,
createdBy int(11) NULL DEFAULT NULL,
updatedBy int(11) NULL DEFAULT NULL,
created_by int(11) NULL DEFAULT NULL,
updated_by int(11) NULL DEFAULT NULL,
created_at timestamp NULL DEFAULT CURRENT_TIMESTAMP,
updated_at timestamp NULL DEFAULT CURRENT_TIMESTAMP,
public int(11) NULL DEFAULT NULL,
framework varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
isOfficial tinyint(1) NULL DEFAULT NULL,
isDefault tinyint(1) NULL DEFAULT NULL,
tiny_reserved tinyint(1) NULL DEFAULT NULL,
tenant int(11) NULL DEFAULT NULL,
component_metadata longtext CHARACTER SET utf8 COLLATE utf8_general_ci NULL,
library int(11) NULL DEFAULT NULL,
PRIMARY KEY (id) USING BTREE,
UNIQUE INDEX unique_component(createdBy, framework, component, version) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;
`.replace(/\n/g, '')
return new Promise((resolve, reject) => {
this.query(sqlContent)
.then((result) => {
logger.success(`table ${componentsTableName} created.`)
resolve(result)
})
.catch((error) => {
logger.error(`create table ${componentsTableName} failed:${error}.`)
reject(error)
})
})
}
/**
* 初始化数据库的组件表
* @returns promise
*/
initUserComponentsTable() {
return new Promise((resolve, reject) => {
// 查询是否已存在表
this.query(`SHOW TABLES LIKE '${componentsTableName}'`)
.then((result) => {
if (result.length) {
// 已存在
resolve()
} else {
this.createUserComponentsTable()
.then(() => {
resolve()
})
.catch((err) => {
reject(err)
})
}
})
.catch((error) => {
reject(error)
})
})
}
}
export default MysqlConnection