src/utils/database.ts   A
last analyzed

Complexity

Total Complexity 4
Complexity/F 0

Size

Lines of Code 69
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 52
mnd 4
bc 4
fnc 0
dl 0
loc 69
rs 10
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
1
import fs from 'fs'
2
import OS from '../client/OS'
3
import Mariadb from '../services/mariadb'
4
import Mysql from '../services/mysql'
5
import Mysql57 from '../services/mysql57'
6
import Mysql80 from '../services/mysql80'
7
8
const supportedDatabases: string[] = [
9
    (new Mysql80).service,
10
    (new Mysql57).service,
11
    (new Mariadb).service
12
]
13
14
/**
15
 * Get the Database object by the name of the service.
16
 * @param databaseType
17
 */
18
const getDatabaseByName = (databaseType: string): Mysql => {
19
    let database: Mysql
20
21
    switch (databaseType) {
22
    case (new Mysql80).service:
23
        database = new Mysql80()
24
        break
25
    case (new Mysql57).service:
26
        database = new Mysql57()
27
        break
28
    case (new Mariadb).service:
29
        database = new Mariadb()
30
        break
31
    default:
32
        throw Error('Invalid database type version: ' + databaseType)
33
    }
34
35
    return database
36
}
37
38
/**
39
 * Get the currently linked Mysql binary.
40
 */
41
const getLinkedDatabase = async (): Promise<Mysql> => {
42
    const mysqlLink = await fs.lstatSync(`${OS.getInstance().usrLocalDir}/bin/mysql`)
43
44
    if (!mysqlLink.isSymbolicLink()) {
45
        throw Error('Mysql executable is not found.')
46
    }
47
48
    const mysqlBinary = await fs.realpathSync(`${OS.getInstance().usrLocalDir}/bin/mysql`)
49
50
    let linkedDatabase: Mysql | undefined
51
52
    supportedDatabases.forEach((versionName) => {
53
        if (mysqlBinary.includes(versionName)) {
54
            linkedDatabase = getDatabaseByName(versionName)
55
        }
56
    })
57
58
    if (linkedDatabase) {
59
        return linkedDatabase
60
    } else {
61
        throw Error('Unable to determine linked database')
62
    }
63
}
64
65
export {
66
    getDatabaseByName,
67
    getLinkedDatabase
68
}
69