sqlDatabase.ts 9.83 KB
Newer Older
liuzhe-lz's avatar
liuzhe-lz committed
1
2
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Deshui Yu's avatar
Deshui Yu committed
3
4
5
6
7

'use strict';

import * as assert from 'assert';
import * as fs from 'fs';
chicm-ms's avatar
chicm-ms committed
8
import * as JSON5 from 'json5';
Deshui Yu's avatar
Deshui Yu committed
9
10
11
12
13
14
15
16
17
18
19
import * as path from 'path';
import * as sqlite3 from 'sqlite3';
import { Deferred } from 'ts-deferred';

import {
    Database,
    MetricDataRecord,
    MetricType,
    TrialJobEvent,
    TrialJobEventRecord
} from '../common/datastore';
chicm-ms's avatar
chicm-ms committed
20
import { getLogger, Logger } from '../common/log';
Deshui Yu's avatar
Deshui Yu committed
21
import { ExperimentProfile } from '../common/manager';
22
import { TrialJobDetail } from '../common/trainingService';
Deshui Yu's avatar
Deshui Yu committed
23
24
25


const createTables: string = `
26
create table TrialJobEvent (timestamp integer, trialJobId text, event text, data text, logPath text, sequenceId integer);
Deshui Yu's avatar
Deshui Yu committed
27
28
29
30
31
32
33
34
35
36
37
38
39
create index TrialJobEvent_trialJobId on TrialJobEvent(trialJobId);
create index TrialJobEvent_event on TrialJobEvent(event);

create table MetricData (timestamp integer, trialJobId text, parameterId text, type text, sequence integer, data text);
create index MetricData_trialJobId on MetricData(trialJobId);
create index MetricData_type on MetricData(type);

create table ExperimentProfile (
    params text,
    id text,
    execDuration integer,
    startTime integer,
    endTime integer,
40
    logDir text,
41
    nextSequenceId integer,
Deshui Yu's avatar
Deshui Yu committed
42
43
44
45
46
47
48
49
50
    revision integer);
create index ExperimentProfile_id on ExperimentProfile(id);
`;

function loadExperimentProfile(row: any): ExperimentProfile {
    return {
        params: JSON.parse(row.params),
        id: row.id,
        execDuration: row.execDuration,
51
52
        startTime: row.startTime === null ? undefined : row.startTime,
        endTime: row.endTime === null ? undefined : row.endTime,
53
        logDir: row.logDir === null ? undefined : row.logDir,
54
        nextSequenceId: row.nextSequenceId,
Deshui Yu's avatar
Deshui Yu committed
55
56
57
58
59
60
        revision: row.revision
    };
}

function loadTrialJobEvent(row: any): TrialJobEventRecord {
    return {
61
        timestamp: row.timestamp,
Deshui Yu's avatar
Deshui Yu committed
62
63
64
        trialJobId: row.trialJobId,
        event: row.event,
        data: row.data === null ? undefined : row.data,
65
66
        logPath: row.logPath === null ? undefined : row.logPath,
        sequenceId: row.sequenceId === null ? undefined : row.sequenceId
Deshui Yu's avatar
Deshui Yu committed
67
68
69
70
71
    };
}

function loadMetricData(row: any): MetricDataRecord {
    return {
72
        timestamp: row.timestamp,
Deshui Yu's avatar
Deshui Yu committed
73
74
75
76
77
78
79
80
81
82
        trialJobId: row.trialJobId,
        parameterId: row.parameterId,
        type: row.type,
        sequence: row.sequence,
        data: row.data
    };
}

class SqlDB implements Database {
    private db!: sqlite3.Database;
chicm-ms's avatar
chicm-ms committed
83
    private log: Logger = getLogger();
Deshui Yu's avatar
Deshui Yu committed
84
85
86
87
88
89
90
    private initTask!: Deferred<void>;

    public init(createNew: boolean, dbDir: string): Promise<void> {
        if (this.initTask !== undefined) {
            return this.initTask.promise;
        }
        this.initTask = new Deferred<void>();
chicm-ms's avatar
chicm-ms committed
91
        this.log.debug(`Database directory: ${dbDir}`);
Deshui Yu's avatar
Deshui Yu committed
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
        assert(fs.existsSync(dbDir));

        const mode: number = createNew ? (sqlite3.OPEN_CREATE | sqlite3.OPEN_READWRITE) : sqlite3.OPEN_READWRITE;
        const dbFileName: string = path.join(dbDir, 'nni.sqlite');

        this.db = new sqlite3.Database(dbFileName, mode, (err: Error | null): void => {
            if (err) {
                this.resolve(this.initTask, err);
            } else {
                if (createNew) {
                    this.db.exec(createTables, (error: Error | null) => {
                        this.resolve(this.initTask, err);
                    });
                } else {
                    this.initTask.resolve();
                }
            }
        });

        return this.initTask.promise;
    }

    public close(): Promise<void> {
        const deferred: Deferred<void> = new Deferred<void>();
        this.db.close((err: Error | null) => { this.resolve(deferred, err); });

        return deferred.promise;
    }

    public storeExperimentProfile(exp: ExperimentProfile): Promise<void> {
122
        const sql: string = 'insert into ExperimentProfile values (?,?,?,?,?,?,?,?)';
Deshui Yu's avatar
Deshui Yu committed
123
124
125
126
        const args: any[] = [
            JSON.stringify(exp.params),
            exp.id,
            exp.execDuration,
127
128
            exp.startTime === undefined ? null : exp.startTime,
            exp.endTime === undefined ? null : exp.endTime,
129
            exp.logDir === undefined ? null : exp.logDir,
130
            exp.nextSequenceId,
Deshui Yu's avatar
Deshui Yu committed
131
132
            exp.revision
        ];
chicm-ms's avatar
chicm-ms committed
133
        this.log.trace(`storeExperimentProfile: SQL: ${sql}, args: ${JSON.stringify(args)}`);
Deshui Yu's avatar
Deshui Yu committed
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
        const deferred: Deferred<void> = new Deferred<void>();
        this.db.run(sql, args, (err: Error | null) => { this.resolve(deferred, err); });

        return deferred.promise;
    }

    public queryExperimentProfile(experimentId: string, revision?: number): Promise<ExperimentProfile[]> {
        let sql: string = '';
        let args: any[] = [];
        if (revision === undefined) {
            sql = 'select * from ExperimentProfile where id=? order by revision DESC';
            args = [experimentId];
        } else {
            sql = 'select * from ExperimentProfile where id=? and revision=?';
            args = [experimentId, revision];
        }
chicm-ms's avatar
chicm-ms committed
150
        this.log.trace(`queryExperimentProfile: SQL: ${sql}, args: ${JSON.stringify(args)}`);
Deshui Yu's avatar
Deshui Yu committed
151
152
153
154
155
156
157
158
159
160
161
162
163
164
        const deferred: Deferred<ExperimentProfile[]> = new Deferred<ExperimentProfile[]>();
        this.db.all(sql, args, (err: Error | null, rows: any[]) => {
            this.resolve(deferred, err, rows, loadExperimentProfile);
        });

        return deferred.promise;
    }

    public async queryLatestExperimentProfile(experimentId: string): Promise<ExperimentProfile> {
        const profiles: ExperimentProfile[] = await this.queryExperimentProfile(experimentId);

        return profiles[0];
    }

165
    public storeTrialJobEvent(
chicm-ms's avatar
chicm-ms committed
166
        event: TrialJobEvent, trialJobId: string, timestamp: number, hyperParameter?: string, jobDetail?: TrialJobDetail): Promise<void> {
167
168
        const sql: string = 'insert into TrialJobEvent values (?,?,?,?,?,?)';
        const logPath: string | undefined = jobDetail === undefined ? undefined : jobDetail.url;
169
        const sequenceId: number | undefined = jobDetail === undefined ? undefined : jobDetail.form.sequenceId;
chicm-ms's avatar
chicm-ms committed
170
        const args: any[] = [timestamp, trialJobId, event, hyperParameter, logPath, sequenceId];
Deshui Yu's avatar
Deshui Yu committed
171

chicm-ms's avatar
chicm-ms committed
172
        this.log.trace(`storeTrialJobEvent: SQL: ${sql}, args: ${JSON.stringify(args)}`);
Deshui Yu's avatar
Deshui Yu committed
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
        const deferred: Deferred<void> = new Deferred<void>();
        this.db.run(sql, args, (err: Error | null) => { this.resolve(deferred, err); });

        return deferred.promise;
    }

    public queryTrialJobEvent(trialJobId?: string, event?: TrialJobEvent): Promise<TrialJobEventRecord[]> {
        let sql: string = '';
        let args: any[] | undefined;
        if (trialJobId === undefined && event === undefined) {
            sql = 'select * from TrialJobEvent';
        } else if (trialJobId === undefined) {
            sql = 'select * from TrialJobEvent where event=?';
            args = [event];
        } else if (event === undefined) {
            sql = 'select * from TrialJobEvent where trialJobId=?';
            args = [trialJobId];
        } else {
            sql = 'select * from TrialJobEvent where trialJobId=? and event=?';
            args = [trialJobId, event];
        }

chicm-ms's avatar
chicm-ms committed
195
        this.log.trace(`queryTrialJobEvent: SQL: ${sql}, args: ${JSON.stringify(args)}`);
Deshui Yu's avatar
Deshui Yu committed
196
197
198
199
200
201
202
203
204
205
        const deferred: Deferred<TrialJobEventRecord[]> = new Deferred<TrialJobEventRecord[]>();
        this.db.all(sql, args, (err: Error | null, rows: any[]) => {
            this.resolve(deferred, err, rows, loadTrialJobEvent);
        });

        return deferred.promise;
    }

    public storeMetricData(trialJobId: string, data: string): Promise<void> {
        const sql: string = 'insert into MetricData values (?,?,?,?,?,?)';
chicm-ms's avatar
chicm-ms committed
206
207
        const json: MetricDataRecord = JSON5.parse(data);
        const args: any[] = [Date.now(), json.trialJobId, json.parameterId, json.type, json.sequence, JSON5.stringify(json.data)];
Deshui Yu's avatar
Deshui Yu committed
208

chicm-ms's avatar
chicm-ms committed
209
        this.log.trace(`storeMetricData: SQL: ${sql}, args: ${JSON5.stringify(args)}`);
Deshui Yu's avatar
Deshui Yu committed
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
        const deferred: Deferred<void> = new Deferred<void>();
        this.db.run(sql, args, (err: Error | null) => { this.resolve(deferred, err); });

        return deferred.promise;
    }

    public queryMetricData(trialJobId?: string, metricType?: MetricType): Promise<MetricDataRecord[]> {
        let sql: string = '';
        let args: any[] | undefined;
        if (metricType === undefined && trialJobId === undefined) {
            sql = 'select * from MetricData';
        } else if (trialJobId === undefined) {
            sql = 'select * from MetricData where type=?';
            args = [metricType];
        } else if (metricType === undefined) {
            sql = 'select * from MetricData where trialJobId=?';
            args = [trialJobId];
        } else {
            sql = 'select * from MetricData where trialJobId=? and type=?';
            args = [trialJobId, metricType];
        }

chicm-ms's avatar
chicm-ms committed
232
        this.log.trace(`queryMetricData: SQL: ${sql}, args: ${JSON.stringify(args)}`);
Deshui Yu's avatar
Deshui Yu committed
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
        const deferred: Deferred<MetricDataRecord[]> = new Deferred<MetricDataRecord[]>();
        this.db.all(sql, args, (err: Error | null, rows: any[]) => {
            this.resolve(deferred, err, rows, loadMetricData);
        });

        return deferred.promise;
    }

    private resolve<T>(
        deferred: Deferred<T[]> | Deferred<void>,
        error: Error | null,
        rows?: any[],
        rowLoader?: (row: any) => T
    ): void {
        if (error !== null) {
            deferred.reject(error);

            return;
        }

        if (rowLoader === undefined) {
            (<Deferred<void>>deferred).resolve();

        } else {
            const data: T[] = [];
            for (const row of (<any[]>rows)) {
                data.push(rowLoader(row));
            }
chicm-ms's avatar
chicm-ms committed
261
            this.log.trace(`sql query result: ${JSON.stringify(data)}`);
Deshui Yu's avatar
Deshui Yu committed
262
263
264
265
266
267
            (<Deferred<T[]>>deferred).resolve(data);
        }
    }
}

export { SqlDB };