-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.ts
473 lines (438 loc) · 13.5 KB
/
index.ts
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
88
89
90
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
import { Parser } from '@json2csv/plainjs';
import {
ILabShell,
ILayoutRestorer,
JupyterFrontEnd,
JupyterFrontEndPlugin
} from '@jupyterlab/application';
import {
ICommandPalette,
ISessionContext,
IToolbarWidgetRegistry
} from '@jupyterlab/apputils';
import { IEditorServices } from '@jupyterlab/codeeditor';
import { IDefaultFileBrowser } from '@jupyterlab/filebrowser';
import { IMetadataFormProvider } from '@jupyterlab/metadataform';
import {
INotebookTracker,
NotebookActions,
NotebookPanel
} from '@jupyterlab/notebook';
import {
Contents,
ContentsManager,
Kernel,
KernelMessage,
Session
} from '@jupyterlab/services';
import { ISettingRegistry } from '@jupyterlab/settingregistry';
import { ITranslator, nullTranslator } from '@jupyterlab/translation';
import {
IFormRenderer,
IFormRendererRegistry,
runIcon
} from '@jupyterlab/ui-components';
import { PartialJSONObject } from '@lumino/coreutils';
import { FieldProps } from '@rjsf/utils';
import { CustomContentFactory } from './cellfactory';
import { requestAPI } from './handler';
import { CommandIDs, SQL_MIMETYPE, SqlCell, objectEnum } from './common';
import * as injectCode from './injectedCode';
import { ISqlCellInjection, SqlCellInjection } from './kernelInjection';
import { Databases } from './sidepanel';
import { DatabaseSelect, SqlWidget, SqlSwitchWidget } from './widget';
/**
* The sql-cell namespace token.
*/
const namespace = 'sql-cell';
/**
* Load the commands and the cell toolbar buttons (from settings).
*/
const plugin: JupyterFrontEndPlugin<void> = {
id: '@jupyter/sql-cell:plugin',
description: 'Add the commands to the registry.',
autoStart: true,
requires: [INotebookTracker, ISqlCellInjection],
optional: [ICommandPalette, IDefaultFileBrowser],
activate: (
app: JupyterFrontEnd,
tracker: INotebookTracker,
injection: ISqlCellInjection,
commandPalette: ICommandPalette,
fileBrowser: IDefaultFileBrowser | null
) => {
const { commands } = app;
commands.addCommand(CommandIDs.run, {
label: 'Run SQL',
caption: 'Run SQL',
icon: runIcon,
execute: async args => {
const path = (args?.path || '_sql_output') as string;
const activeCell = tracker.activeCell;
if (!(activeCell?.model.type === 'raw')) {
return;
}
const database_id = SqlCell.getMetadata(activeCell.model, 'database')[
'id'
];
if (database_id === undefined) {
console.error('The database has not been set.');
}
const date = new Date();
const kernel = tracker.currentWidget?.sessionContext.session?.kernel;
const source = activeCell?.model.sharedModel.getSource();
requestAPI<any>('execute', {
method: 'POST',
body: JSON.stringify({ query: source, id: database_id })
})
.then(data => {
const variable = SqlCell.getMetadata(activeCell.model, 'variable');
if (kernel && injection.status && variable) {
const future = Private.transferDataToKernel(
kernel,
data.data,
variable
);
future.done.then(reply => {
console.log('REPLY', reply);
});
} else {
Private.saveData(path, data.data, date, fileBrowser)
.then(dataPath => console.log(`Data saved ${dataPath}`))
.catch(undefined);
}
})
.catch(reason => {
console.error(reason);
});
},
isEnabled: () => SqlCell.isSqlCell(tracker.activeCell?.model),
isVisible: () => SqlCell.isRaw(tracker.activeCell?.model)
});
commands.addCommand(CommandIDs.switchSQL, {
label: 'SQL',
caption: () => {
const model = tracker.activeCell?.model;
return SqlCell.isSqlCell(model) ? 'Switch to Raw' : 'Switch to SQL';
},
execute: async () => {
const notebook = tracker.currentWidget?.content;
let model = tracker.activeCell?.model;
if (!notebook || !model) {
return;
}
if (model.type !== 'raw') {
NotebookActions.changeCellType(notebook, 'raw');
// Reassign the model since the cell has been deleted and created again.
model = tracker.activeCell?.model;
}
if (model?.getMetadata('format') !== SQL_MIMETYPE) {
model?.setMetadata('format', SQL_MIMETYPE);
} else if (model?.getMetadata('format') === SQL_MIMETYPE) {
model?.deleteMetadata('format');
}
app.commands.notifyCommandChanged(CommandIDs.switchSQL);
app.commands.notifyCommandChanged(CommandIDs.run);
},
isVisible: () => SqlCell.isRaw(tracker.activeCell?.model),
isToggled: () => SqlCell.isSqlCell(tracker.activeCell?.model)
});
if (commandPalette) {
commandPalette.addItem({
command: CommandIDs.run,
category: 'SQL'
});
}
}
};
/**
* The notebook cell factory provider, to handle SQL cells.
*/
const cellFactory: JupyterFrontEndPlugin<NotebookPanel.IContentFactory> = {
id: '@jupyter/sql-cell:content-factory',
description: 'Provides the notebook cell factory.',
provides: NotebookPanel.IContentFactory,
requires: [IEditorServices],
autoStart: true,
activate: (app: JupyterFrontEnd, editorServices: IEditorServices) => {
const editorFactory = editorServices.factoryService.newInlineEditor;
return new CustomContentFactory({ editorFactory });
}
};
/**
* The side panel to handle the list of databases.
*/
const databasesList: JupyterFrontEndPlugin<void> = {
id: '@jupyter/sql-cell:databases-list',
description: 'The side panel which handle databases list.',
autoStart: true,
optional: [
ILabShell,
ILayoutRestorer,
IMetadataFormProvider,
INotebookTracker,
ITranslator
],
activate: (
app: JupyterFrontEnd,
labShell: ILabShell,
restorer: ILayoutRestorer | null,
metadataForms: IMetadataFormProvider | null,
tracker: INotebookTracker | null,
translator: ITranslator | null
) => {
const { shell } = app;
if (!translator) {
translator = nullTranslator;
}
const panel = new Databases({ tracker, translator });
if (metadataForms) {
// Update the databases list in the metadata form.
panel.databaseUpdated.connect((_, databases) => {
const properties: PartialJSONObject = { oneOf: [] };
(properties!.oneOf as objectEnum[])!.push({
const: null,
title: '-'
});
databases.forEach(db => {
const dbJson = JSON.parse(JSON.stringify(db));
(properties!.oneOf as objectEnum[])!.push({
const: dbJson,
title: db.alias
});
});
metadataForms
.get('sqlCellSection')!
.setProperties('/sql-cell/database', properties);
});
}
// Restore the widget state
if (restorer) {
restorer.add(panel, namespace);
}
if (labShell) {
labShell.currentChanged.connect(
(_: ILabShell, args: ILabShell.IChangedArgs) => {
panel.mainAreaWidgetChanged(args.newValue);
}
);
}
shell.add(panel, 'left');
}
};
/**
* The plugin to add a form interacting with cell metadata, in the notebook tools.
*/
const metadataForm: JupyterFrontEndPlugin<void> = {
id: '@jupyter/sql-cell:metadata-form',
description:
'A JupyterLab extension to add a form in the Notebook tools panel.',
autoStart: true,
requires: [IFormRendererRegistry, INotebookTracker],
activate: (
app: JupyterFrontEnd,
formRegistry: IFormRendererRegistry,
tracker: INotebookTracker
) => {
const { commands } = app;
// The widget to toggle to SQL cell.
const switcher: IFormRenderer = {
fieldRenderer: () => {
return SqlSwitchWidget({
commands,
tracker
});
}
};
formRegistry.addRenderer('@jupyter/sql-cell:switch.renderer', switcher);
// A widget to associate a database to the cell.
const databaseSelect: IFormRenderer = {
fieldRenderer: (props: FieldProps) => {
return DatabaseSelect({ ...props, tracker });
}
};
formRegistry.addRenderer(
'@jupyter/sql-cell:database-select.renderer',
databaseSelect
);
}
};
/*
* A plugin to inject a function in the notebook kernel.
*/
const kernelFunctionInjector: JupyterFrontEndPlugin<ISqlCellInjection> = {
id: '@jupyter/sql-cell:kernel-injection',
description: 'A JupyterLab extension to inject a function in notebook kernel',
autoStart: true,
provides: ISqlCellInjection,
requires: [INotebookTracker],
activate: (app: JupyterFrontEnd, tracker: INotebookTracker) => {
let sessionContext: ISessionContext | undefined = undefined;
const injection = new SqlCellInjection();
/**
* Triggered when the current notebook or current kernel changes.
*/
const onKernelChanged = async (
_sessionContext: ISessionContext,
kernelChange: Session.ISessionConnection.IKernelChangedArgs
) => {
injection.status = false;
const kernel = kernelChange.newValue;
if (kernel) {
kernel.info.then(info => {
let code = '';
if (info.language_info.name === 'python') {
code = injectCode.PYTHON_CODE;
}
if (!code) {
return;
}
const content: KernelMessage.IExecuteRequestMsg['content'] = {
code: code
};
const future = kernel.requestExecute(content);
future.done.then(reply => {
injection.status = reply.content.status === 'ok';
});
});
}
};
tracker.currentChanged.connect((_, panel) => {
sessionContext?.kernelChanged.disconnect(onKernelChanged);
sessionContext = panel?.sessionContext;
const kernel = sessionContext?.session?.kernel;
if (sessionContext && kernel) {
onKernelChanged(sessionContext, {
name: 'kernel',
oldValue: null,
newValue: kernel
});
}
sessionContext?.kernelChanged.connect(onKernelChanged);
});
return injection;
}
};
/**
* The notebook toolbar widget.
*/
const notebookToolbarWidget: JupyterFrontEndPlugin<void> = {
id: '@jupyter/sql-cell:notebook-toolbar',
description: 'A JupyterLab extension to add a widget in the Notebook toolbar',
autoStart: true,
requires: [INotebookTracker, IToolbarWidgetRegistry],
optional: [ISettingRegistry],
activate: (
app: JupyterFrontEnd,
tracker: INotebookTracker,
toolbarRegistry: IToolbarWidgetRegistry,
settingRegistry: ISettingRegistry | null
) => {
const { commands } = app;
const toolbarFactory = (panel: NotebookPanel) => {
return new SqlWidget({ commands, tracker });
};
toolbarRegistry.addFactory<NotebookPanel>(
'Notebook',
'SqlWidget',
toolbarFactory
);
if (settingRegistry) {
settingRegistry
.load(notebookToolbarWidget.id)
.then(settings => {
console.log('@jupyter/sql-cell settings loaded:', settings.composite);
})
.catch(reason => {
console.error(
'Failed to load settings for @jupyter/sql-cell.',
reason
);
});
}
}
};
export default [
cellFactory,
databasesList,
metadataForm,
kernelFunctionInjector,
notebookToolbarWidget,
plugin
];
namespace Private {
/**
* Call the function to transfer the data on the kernel.
*
* @param kernel - kernel on which to transfer the data.
* @param data - data to transfer to the kernel (mst be serializable).
* @returns the code execution future.
*/
export function transferDataToKernel(
kernel: Kernel.IKernelConnection,
data: any,
variable?: string
): Kernel.IShellFuture<
KernelMessage.IExecuteRequestMsg,
KernelMessage.IExecuteReplyMsg
> {
data = JSON.stringify(data).replace(/"/gi, '\\"');
const variableStr = variable ? `, "${variable}"` : '';
const code = `_sql_transfer_data("${data}"${variableStr})`;
const content: KernelMessage.IExecuteRequestMsg['content'] = {
code: code,
stop_on_error: true
};
return kernel.requestExecute(content, false);
}
/**
* Save data in a CSV file.
*
* @param path - the path to the directory where to save data.
* @param data - the data to parse as CSV.
* @param date - the query date.
*/
export async function saveData(
path: string,
data: any,
date: Date,
fileBrowser: IDefaultFileBrowser | null
): Promise<string | undefined> {
const contentsManager = new ContentsManager();
const parser = new Parser();
const csv = parser.parse(data);
const dateText = date
.toLocaleString()
.replace(/[/:]/g, '-')
.replace(/\s/g, '')
.replace(',', '_');
let currentPath = '';
if (!path.startsWith('/')) {
currentPath = `${fileBrowser?.model.path}/` || '';
}
for (const directory of path.split('/')) {
currentPath = `${currentPath}${directory}/`;
await contentsManager
.get(currentPath, { content: false })
.catch(error =>
contentsManager.save(currentPath, { type: 'directory' })
);
}
const filename = `${dateText}.csv`;
const fileModel = {
name: filename,
path: `${currentPath}/${filename}`,
format: 'text' as Contents.FileFormat,
content: csv
};
return contentsManager
.save(fileModel.path, fileModel)
.then(() => {
return fileModel.path;
})
.catch(e => {
console.error(e);
return undefined;
});
}
}