1
+ const vscode = require ( `vscode` ) ;
2
+
3
+ const Statement = require ( `../database/statement` ) ;
4
+
5
+ /**
6
+ *
7
+ * @param {vscode.ExtensionContext } context
8
+ */
9
+ exports . initialise = ( context ) => {
10
+ context . subscriptions . push (
11
+ vscode . commands . registerCommand ( `vscode-db2i.pasteGenerator` , async ( ) => {
12
+ try {
13
+ const clipboard_content = await vscode . env . clipboard . readText ( ) ;
14
+ const parsedData = JSON . parse ( clipboard_content ) ;
15
+
16
+ const sql = exports . generateSQL ( parsedData ) ;
17
+ const formatted = Statement . format ( sql ) ;
18
+
19
+ if ( vscode . window . activeTextEditor ) {
20
+ vscode . window . activeTextEditor . edit ( ( edit ) => {
21
+ edit . insert ( vscode . window . activeTextEditor . selection . active , formatted ) ;
22
+ } ) ;
23
+ }
24
+ } catch ( e ) {
25
+ vscode . window . showErrorMessage ( `Error: ${ e . message } ` ) ;
26
+ }
27
+ } ) ,
28
+ )
29
+ }
30
+
31
+ exports . generateSQL = ( jsonIn ) => {
32
+ if ( Array . isArray ( jsonIn ) ) {
33
+ return generateArray ( jsonIn ) ;
34
+ } else {
35
+ return generateObject ( jsonIn ) ;
36
+ }
37
+ }
38
+
39
+ const generateArray = ( elementIn ) => {
40
+ const firstValue = Array . isArray ( elementIn ) ? elementIn [ 0 ] : elementIn ;
41
+ if ( typeof firstValue === `object` ) {
42
+ return `(SELECT json_arrayagg(${ generateObject ( firstValue ) } ) from SYSIBM.SYSDUMMY1)`
43
+ } else {
44
+ return `(SELECT json_arrayagg(${ typeof firstValue === `string` ? `'${ firstValue } '` : firstValue } ) from SYSIBM.SYSDUMMY1)`
45
+ }
46
+ }
47
+
48
+ const generateObject = ( objIn ) => {
49
+ const items = [ ] ;
50
+
51
+ Object . keys ( objIn ) . forEach ( ( key ) => {
52
+ const value = objIn [ key ] ;
53
+ if ( typeof value === `object` ) {
54
+ if ( Array . isArray ( value ) ) {
55
+ items . push ( `'${ key } ': ${ generateArray ( value [ 0 ] ) } format json` ) ;
56
+ } else {
57
+ items . push ( `'${ key } ': ${ generateObject ( value ) } ` ) ;
58
+ }
59
+ } else {
60
+ items . push ( `'${ key } ': ${ typeof value === `string` ? `'${ value } '` : value } ` ) ;
61
+ }
62
+ } ) ;
63
+
64
+ return `json_object(${ items . join ( `, ` ) } )` ;
65
+ }
0 commit comments