sqlDatabase.ts 10.9 KB
Newer Older
Deshui Yu's avatar
Deshui Yu committed
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
/**
 * Copyright (c) Microsoft Corporation
 * All rights reserved.
 *
 * MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
 * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

'use strict';

import * as assert from 'assert';
import * as fs from 'fs';
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
35
import { getLogger, Logger } from '../common/log';
Deshui Yu's avatar
Deshui Yu committed
36
import { ExperimentProfile } from '../common/manager';
37
import { TrialJobDetail } from '../common/trainingService';
Deshui Yu's avatar
Deshui Yu committed
38
39
40
41

/* tslint:disable:no-any */

const createTables: string = `
42
create table TrialJobEvent (timestamp integer, trialJobId text, event text, data text, logPath text, sequenceId integer);
Deshui Yu's avatar
Deshui Yu committed
43
44
45
46
47
48
49
50
51
52
53
54
55
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,
56
    logDir text,
57
    maxSequenceId integer,
Deshui Yu's avatar
Deshui Yu committed
58
59
60
61
62
63
64
65
66
    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,
67
68
        startTime: row.startTime === null ? undefined : row.startTime,
        endTime: row.endTime === null ? undefined : row.endTime,
69
        logDir: row.logDir === null ? undefined : row.logDir,
70
        maxSequenceId: row.maxSequenceId,
Deshui Yu's avatar
Deshui Yu committed
71
72
73
74
75
76
        revision: row.revision
    };
}

function loadTrialJobEvent(row: any): TrialJobEventRecord {
    return {
77
        timestamp: row.timestamp,
Deshui Yu's avatar
Deshui Yu committed
78
79
80
        trialJobId: row.trialJobId,
        event: row.event,
        data: row.data === null ? undefined : row.data,
81
82
        logPath: row.logPath === null ? undefined : row.logPath,
        sequenceId: row.sequenceId === null ? undefined : row.sequenceId
Deshui Yu's avatar
Deshui Yu committed
83
84
85
86
87
    };
}

function loadMetricData(row: any): MetricDataRecord {
    return {
88
        timestamp: row.timestamp,
Deshui Yu's avatar
Deshui Yu committed
89
90
91
92
93
94
95
96
97
98
        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
99
    private log: Logger = getLogger();
Deshui Yu's avatar
Deshui Yu committed
100
101
102
103
104
105
106
    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
107
        this.log.debug(`Database directory: ${dbDir}`);
Deshui Yu's avatar
Deshui Yu committed
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
        assert(fs.existsSync(dbDir));

        // tslint:disable-next-line:no-bitwise
        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> {
139
        const sql: string = 'insert into ExperimentProfile values (?,?,?,?,?,?,?,?)';
Deshui Yu's avatar
Deshui Yu committed
140
141
142
143
        const args: any[] = [
            JSON.stringify(exp.params),
            exp.id,
            exp.execDuration,
144
145
            exp.startTime === undefined ? null : exp.startTime,
            exp.endTime === undefined ? null : exp.endTime,
146
            exp.logDir === undefined ? null : exp.logDir,
147
            exp.maxSequenceId,
Deshui Yu's avatar
Deshui Yu committed
148
149
            exp.revision
        ];
chicm-ms's avatar
chicm-ms committed
150
        this.log.trace(`storeExperimentProfile: 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
165
166
        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
167
        this.log.trace(`queryExperimentProfile: SQL: ${sql}, args: ${JSON.stringify(args)}`);
Deshui Yu's avatar
Deshui Yu committed
168
169
170
171
172
173
174
175
176
177
178
179
180
181
        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];
    }

182
    public storeTrialJobEvent(
chicm-ms's avatar
chicm-ms committed
183
        event: TrialJobEvent, trialJobId: string, timestamp: number, hyperParameter?: string, jobDetail?: TrialJobDetail): Promise<void> {
184
185
186
        const sql: string = 'insert into TrialJobEvent values (?,?,?,?,?,?)';
        const logPath: string | undefined = jobDetail === undefined ? undefined : jobDetail.url;
        const sequenceId: number | undefined = jobDetail === undefined ? undefined : jobDetail.sequenceId;
chicm-ms's avatar
chicm-ms committed
187
        const args: any[] = [timestamp, trialJobId, event, hyperParameter, logPath, sequenceId];
Deshui Yu's avatar
Deshui Yu committed
188

chicm-ms's avatar
chicm-ms committed
189
        this.log.trace(`storeTrialJobEvent: SQL: ${sql}, args: ${JSON.stringify(args)}`);
Deshui Yu's avatar
Deshui Yu committed
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
        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
212
        this.log.trace(`queryTrialJobEvent: SQL: ${sql}, args: ${JSON.stringify(args)}`);
Deshui Yu's avatar
Deshui Yu committed
213
214
215
216
217
218
219
220
221
222
223
224
225
        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 (?,?,?,?,?,?)';
        const json: MetricDataRecord = JSON.parse(data);
        const args: any[] = [Date.now(), json.trialJobId, json.parameterId, json.type, json.sequence, JSON.stringify(json.data)];

chicm-ms's avatar
chicm-ms committed
226
        this.log.trace(`storeMetricData: SQL: ${sql}, args: ${JSON.stringify(args)}`);
Deshui Yu's avatar
Deshui Yu committed
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
        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
249
        this.log.trace(`queryMetricData: SQL: ${sql}, args: ${JSON.stringify(args)}`);
Deshui Yu's avatar
Deshui Yu committed
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
        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
278
            this.log.trace(`sql query result: ${JSON.stringify(data)}`);
Deshui Yu's avatar
Deshui Yu committed
279
280
281
282
283
284
            (<Deferred<T[]>>deferred).resolve(data);
        }
    }
}

export { SqlDB };