-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathmysql.js
More file actions
87 lines (83 loc) · 2.97 KB
/
mysql.js
File metadata and controls
87 lines (83 loc) · 2.97 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
var dialects = require('./')
var pync = require('pync')
var MysqlClient = require('./mysql-client')
class MySQLDialect {
_quote (str) {
return '`' + str + '`'
}
describeDatabase (options) {
var schema = { dialect: 'mysql', sequences: [] }
var client = new MysqlClient(options)
return client.query('SHOW TABLES')
.then((result) => {
var field = result.fields[0].name
var rows = result.rows
var tables = rows.map((row) => row[field])
return pync.map(tables, (table) => {
var t = {
name: table,
constraints: [],
indexes: []
}
return client.find(`DESCRIBE ${this._quote(table)}`)
.then((columns) => {
t.columns = columns.map((column) => ({
name: column.Field,
nullable: column.Null === 'YES',
default_value: column.Default,
type: column.Type,
extra: column.Extra
}))
return t
})
})
})
.then((tables) => {
schema.tables = tables
return client.find('SELECT * FROM information_schema.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA=?', [client.database])
})
.then((constraints) => {
constraints.forEach((constraint) => {
var name = constraint['CONSTRAINT_NAME']
var table = schema.tables.find((table) => table.name === constraint['TABLE_NAME'])
var info = table.constraints.find((constr) => constr.name === name)
var foreign = !!constraint['REFERENCED_TABLE_NAME']
if (!info) {
info = {
name,
type: foreign ? 'foreign' : (name === 'PRIMARY' ? 'primary' : 'unique'),
columns: []
}
if (foreign) info.referenced_columns = []
table.constraints.push(info)
}
if (foreign) {
info.referenced_table = constraint['REFERENCED_TABLE_NAME']
info.referenced_columns.push(constraint['REFERENCED_COLUMN_NAME'])
}
info.columns.push(constraint['COLUMN_NAME'])
})
return pync.series(schema.tables, (table) => (
client.find(`SHOW INDEXES IN ${this._quote(table.name)}`)
.then((indexes) => {
indexes
.filter((index) => !table.constraints.find((constraint) => constraint.name === index.Key_name))
.forEach((index) => {
var info = table.indexes.find((indx) => index.Key_name === indx.name)
if (!info) {
info = {
name: index.Key_name,
type: index.Index_type,
columns: []
}
table.indexes.push(info)
}
info.columns.push(index.Column_name)
})
})
))
})
.then(() => schema)
}
}
dialects.register('mysql', MySQLDialect)