-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathNotebookUserData.cs
More file actions
275 lines (255 loc) · 9.9 KB
/
NotebookUserData.cs
File metadata and controls
275 lines (255 loc) · 9.9 KB
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.Json;
using SqlNotebookScript.Core;
using SqlNotebookScript.Interpreter;
using SqlNotebookScript.Utils;
namespace SqlNotebookScript;
public sealed class NotebookUserData : IDisposable
{
private const int ITEM_TYPE_SCRIPT = 1;
private const int ITEM_TYPE_PAGE = 2;
public List<NotebookItemRecord> Items { get; set; } = new();
public List<string> GetScriptParameters(string scriptName)
{
var item = Items.FirstOrDefault(x => x.Name == scriptName);
return ((ScriptNotebookItemRecord)item)?.Parameters;
}
public static NotebookUserData Load(Notebook notebook)
{
NotebookUserData userData = new() { Items = new() };
SqlUtil.WithTransaction(
notebook,
() =>
{
CreateTables(notebook);
using var items = notebook.Query("SELECT * FROM _sqlnotebook_items;");
using var scripts = notebook.Query("SELECT * FROM _sqlnotebook_scripts;");
var scriptsById = scripts.Rows.ToDictionary(x => Convert.ToInt32(x[0]
6880
));
using var scriptParameters = notebook.Query("SELECT * FROM _sqlnotebook_script_parameters;");
var scriptParametersById = scriptParameters.Rows.ToLookup(x => Convert.ToInt32(x[0]));
using var pageTextBlocks = notebook.Query("SELECT * FROM _sqlnotebook_page_text_blocks;");
var pageTextBlocksById = pageTextBlocks.Rows.ToLookup(x => Convert.ToInt32(x[0]));
using var pageQueryBlocks = notebook.Query("SELECT * FROM _sqlnotebook_page_query_blocks;");
var pageQueryBlocksById = pageQueryBlocks.Rows.ToLookup(x => Convert.ToInt32(x[0]));
foreach (var itemRow in items.Rows)
{
var itemId = Convert.ToInt32(itemRow[0]);
var itemName = Convert.ToString(itemRow[1]);
var itemType = Convert.ToInt32(itemRow[2]);
switch (itemType)
{
case ITEM_TYPE_PAGE:
userData.Items.Add(
LoadPage(itemName, pageTextBlocksById[itemId], pageQueryBlocksById[itemId])
);
break;
case ITEM_TYPE_SCRIPT:
userData.Items.Add(LoadScript(itemName, scriptsById[itemId], scriptParametersById[itemId]));
break;
default:
break; // Ignore it.
}
}
}
);
return userData;
}
private static PageNotebookItemRecord LoadPage(
string itemName,
IEnumerable<object[]> textBlockRows,
IEnumerable<object[]> queryBlockRows
)
{
PageNotebookItemRecord page = new() { Name = itemName, Blocks = new() };
var textBlockRowsByIndex = textBlockRows.ToDictionary(x => Convert.ToInt32(x[1]));
var queryBlockRowsByIndex = queryBlockRows.ToDictionary(x => Convert.ToInt32(x[1]));
var sortedIndices = textBlockRowsByIndex.Keys.Concat(queryBlockRowsByIndex.Keys).OrderBy(x => x);
foreach (var index in sortedIndices)
{
if (textBlockRowsByIndex.TryGetValue(index, out var textBlockRow))
{
page.Blocks.Add(new TextPageBlockRecord { Content = Convert.ToString(textBlockRow[2]) });
}
else if (queryBlockRowsByIndex.TryGetValue(index, out var queryBlockRow))
{
var output =
queryBlockRow[3] != null && queryBlockRow[3] is not DBNull
? ScriptOutput.FromBytes((byte[])queryBlockRow[3])
: null;
page.Blocks.Add(
new QueryPageBlockRecord
{
Sql = Convert.ToString(queryBlockRow[2]),
Output = output,
Options = JsonSerializer.Deserialize<QueryPageBlockOptions>(Convert.ToString(queryBlockRow[4])),
}
);
}
}
return page;
}
private static ScriptNotebookItemRecord LoadScript(
string itemName,
object[] scriptRow,
IEnumerable<object[]> scriptParameterRows
)
{
ScriptNotebookItemRecord script = new()
{
Name = itemName,
Sql = Convert.ToString(scriptRow[1]),
Parameters = new(),
};
var scriptParameterRowsByIndex = scriptParameterRows.ToDictionary(x => Convert.ToInt32(x[1]));
var sortedIndices = scriptParameterRowsByIndex.Keys.OrderBy(x => x);
foreach (var index in sortedIndices)
{
var scriptParameterRow = scriptParameterRowsByIndex[index];
script.Parameters.Add(Convert.ToString(scriptParameterRow[2]));
}
return script;
}
public void Save(Notebook notebook)
{
SqlUtil.WithTransaction(
notebook,
() =>
{
CreateTables(notebook);
var itemId = 1;
foreach (var item in Items)
{
switch (item)
{
case ScriptNotebookItemRecord script:
SaveScript(notebook, script, itemId);
break;
case PageNotebookItemRecord page:
SavePage(notebook, page, itemId);
break;
default:
Debug.Fail("Unknown item type.");
break;
}
itemId++;
}
}
);
}
private static void SaveScript(Notebook notebook, ScriptNotebookItemRecord script, int itemId)
{
notebook.Execute(
"INSERT INTO _sqlnotebook_items VALUES (?, ?, ?);",
new object[] { itemId, script.Name, ITEM_TYPE_SCRIPT }
);
notebook.Execute("INSERT INTO _sqlnotebook_scripts VALUES (?, ?);", new object[] { itemId, script.Sql });
var parameterIndex = 0;
foreach (var parameterName in script.Parameters)
{
notebook.Execute(
"INSERT INTO _sqlnotebook_script_parameters VALUES (?, ?, ?);",
new object[] { itemId, parameterIndex, parameterName }
);
parameterIndex++;
}
}
private static void SavePage(Notebook notebook, PageNotebookItemRecord page, int itemId)
{
notebook.Execute(
"INSERT INTO _sqlnotebook_items VALUES (?, ?, ?);",
new object[] { itemId, page.Name, ITEM_TYPE_PAGE }
);
var index = 0;
foreach (var block in page.Blocks)
{
switch (block)
{
case TextPageBlockRecord textBlock:
notebook.Execute(
"INSERT INTO _sqlnotebook_page_text_blocks VALUES (?, ?, ?);",
new object[] { itemId, index, textBlock.Content }
);
break;
case QueryPageBlockRecord queryBlock:
var optionsJson = JsonSerializer.Serialize(queryBlock.Options);
notebook.Execute(
"INSERT INTO _sqlnotebook_page_query_blocks VALUES (?, ?, ?, ?, ?);",
new object[] { itemId, index, queryBlock.Sql, queryBlock.Output?.GetBytes(), optionsJson }
);
break;
default:
Debug.Fail("Unknown block type");
break;
}
index++;
}
}
private static void CreateTables(Notebook notebook)
{
notebook.Execute(
@"CREATE TABLE IF NOT EXISTS _sqlnotebook_items (
id INTEGER NOT NULL,
name TEXT NOT NULL,
type INTEGER NOT NULL,
PRIMARY KEY (id)
);"
);
notebook.Execute(
@"CREATE TABLE IF NOT EXISTS _sqlnotebook_scripts (
item_id INTEGER NOT NULL,
content TEXT NOT NULL,
PRIMARY KEY (item_id),
FOREIGN KEY (item_id) REFERENCES _sqlnotebook_items (id)
);"
);
notebook.Execute(
@"CREATE TABLE IF NOT EXISTS _sqlnotebook_script_parameters (
item_id INTEGER NOT NULL,
parameter_index INTEGER NOT NULL,
name TEXT NOT NULL,
PRIMARY KEY (item_id, parameter_index),
FOREIGN KEY (item_id) REFERENCES _sqlnotebook_scripts (item_id)
);"
);
notebook.Execute(
@"CREATE TABLE IF NOT EXISTS _sqlnotebook_page_text_blocks (
item_id INTEGER NOT NULL,
block_index INTEGER NOT NULL,
content TEXT NOT NULL,
PRIMARY KEY (item_id, block_index),
FOREIGN KEY (item_id) REFERENCES _sqlnotebook_items (id)
);"
);
notebook.Execute(
@"CREATE TABLE IF NOT EXISTS _sqlnotebook_page_query_blocks (
item_id INTEGER NOT NULL,
block_index INTEGER NOT NULL,
content TEXT NOT NULL,
output BLOB NULL,
options_json TEXT NOT NULL,
PRIMARY KEY (item_id, block_index),
FOREIGN KEY (item_id) REFERENCES _sqlnotebook_items (id)
);"
);
}
public static void DropTables(Notebook notebook)
{
notebook.Execute("DROP TABLE IF EXISTS _sqlnotebook_page_query_blocks;");
notebook.Execute("DROP TABLE IF EXISTS _sqlnotebook_page_text_blocks;");
notebook.Execute("DROP TABLE IF EXISTS _sqlnotebook_script_parameters;");
notebook.Execute("DROP TABLE IF EXISTS _sqlnotebook_scripts");
;
notebook.Execute("DROP TABLE IF EXISTS _sqlnotebook_items;");
}
public void Dispose()
{
foreach (var item in Items)
{
if (item is IDisposable disposable)
disposable.Dispose();
}
}
}