sqlDatabase.ts 9.8 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
8
9
10
11
12
13
14
15
16
17
18

'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
19
import { getLogger, Logger } from '../common/log';
Deshui Yu's avatar
Deshui Yu committed
20
import { ExperimentProfile } from '../common/manager';
21
import { TrialJobDetail } from '../common/trainingService';
Deshui Yu's avatar
Deshui Yu committed
22
23
24


const createTables: string = `
25
create table TrialJobEvent (timestamp integer, trialJobId text, event text, data text, logPath text, sequenceId integer);
Deshui Yu's avatar
Deshui Yu committed
26
27
28
29
30
31
32
33
34
35
36
37
38
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,
39
    logDir text,
40
    nextSequenceId integer,
Deshui Yu's avatar
Deshui Yu committed
41
42
43
44
45
46
47
48
49
    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,
50
51
        startTime: row.startTime === null ? undefined : row.startTime,
        endTime: row.endTime === null ? undefined : row.endTime,
52
        logDir: row.logDir === null ? undefined : row.logDir,
53
        nextSequenceId: row.nextSequenceId,
Deshui Yu's avatar
Deshui Yu committed
54
55
56
57
58
59
        revision: row.revision
    };
}

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

function loadMetricData(row: any): MetricDataRecord {
    return {
71
        timestamp: row.timestamp,
Deshui Yu's avatar
Deshui Yu committed
72
73
74
75
76
77
78
79
80
81
        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
82
    private log: Logger = getLogger();
Deshui Yu's avatar
Deshui Yu committed
83
84
85
86
87
88
89
    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
90
        this.log.debug(`Database directory: ${dbDir}`);
Deshui Yu's avatar
Deshui Yu committed
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
        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> {
121
        const sql: string = 'insert into ExperimentProfile values (?,?,?,?,?,?,?,?)';
Deshui Yu's avatar
Deshui Yu committed
122
123
124
125
        const args: any[] = [
            JSON.stringify(exp.params),
            exp.id,
            exp.execDuration,
126
127
            exp.startTime === undefined ? null : exp.startTime,
            exp.endTime === undefined ? null : exp.endTime,
128
            exp.logDir === undefined ? null : exp.logDir,
129
            exp.nextSequenceId,
Deshui Yu's avatar
Deshui Yu committed
130
131
            exp.revision
        ];
chicm-ms's avatar
chicm-ms committed
132
        this.log.trace(`storeExperimentProfile: SQL: ${sql}, args: ${JSON.stringify(args)}`);
Deshui Yu's avatar
Deshui Yu committed
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
        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
149
        this.log.trace(`queryExperimentProfile: SQL: ${sql}, args: ${JSON.stringify(args)}`);
Deshui Yu's avatar
Deshui Yu committed
150
151
152
153
154
155
156
157
158
159
160
161
162
163
        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];
    }

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

chicm-ms's avatar
chicm-ms committed
171
        this.log.trace(`storeTrialJobEvent: SQL: ${sql}, args: ${JSON.stringify(args)}`);
Deshui Yu's avatar
Deshui Yu committed
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
        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
194
        this.log.trace(`queryTrialJobEvent: SQL: ${sql}, args: ${JSON.stringify(args)}`);
Deshui Yu's avatar
Deshui Yu committed
195
196
197
198
199
200
201
202
203
204
        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
205
206
        const json: MetricDataRecord = JSON.parse(data);
        const args: any[] = [Date.now(), json.trialJobId, json.parameterId, json.type, json.sequence, JSON.stringify(json.data)];
Deshui Yu's avatar
Deshui Yu committed
207

chicm-ms's avatar
chicm-ms committed
208
        this.log.trace(`storeMetricData: SQL: ${sql}, args: ${JSON.stringify(args)}`);
Deshui Yu's avatar
Deshui Yu committed
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
        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
231
        this.log.trace(`queryMetricData: SQL: ${sql}, args: ${JSON.stringify(args)}`);
Deshui Yu's avatar
Deshui Yu committed
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
        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
260
            this.log.trace(`sql query result: ${JSON.stringify(data)}`);
Deshui Yu's avatar
Deshui Yu committed
261
262
263
264
265
266
            (<Deferred<T[]>>deferred).resolve(data);
        }
    }
}

export { SqlDB };