-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataPackageHelper.pqm
456 lines (419 loc) · 27.7 KB
/
DataPackageHelper.pqm
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
/*
MIT License
Copyright (c) 2018-2020 Nimble Learn Ltd (http://www.nimblelearn.com)
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.
*/
// A function that returns a Data Package helper function
let
DataPackage.Helper = (functionName as text) as function =>
let
/*
Resolve a Data Package Identifier and return the Data Package metadata as a record along with some inferred helper properties.
The inferred helper properties are prefixed with a double underscore e.g. '__fullpath'.
*/
DataPackage.Package = (dataPackageIdentifier as text) as record =>
let
// Base path pattern to use when resolving Data Package names against the Core Data Package registry
CoreRegistryBasePathPattern = "https://datahub.io/core/{name}/",
// The data package spec states that the descriptor file MUST be named datapackage.json
Descriptor = "datapackage.json",
// Expand the path if needed. This is a preliminary step for resolving the Data Package identifier.
ExpandedPath = if Text.Contains(dataPackageIdentifier, "\") = false and Text.Contains(dataPackageIdentifier, "/") = false then
// Treat this as an identifier for a Data Package in the Core datasets registry on datahub.io
Text.Replace(CoreRegistryBasePathPattern, "{name}", dataPackageIdentifier)
// Resolve the github.com URL to the corresponding raw.githubusercontent.com URL
else if Text.Contains(dataPackageIdentifier,"github.com") then
Text.Replace(
Text.Replace(
Text.Replace(
dataPackageIdentifier,
"github.com",
"raw.githubusercontent.com"
),
"/blob/master",
"/master"
),
"/tree/master",
"/master"
)
else
dataPackageIdentifier,
// Build the base path for the Data Package
BasePath = Text.Replace(
if Text.StartsWith(ExpandedPath, "http") then
(
if Text.End(ExpandedPath, 1) <> "/" and Text.Contains(ExpandedPath, "datapackage.json") = false then
ExpandedPath & "/"
else
ExpandedPath
)
else
(
if Text.End(ExpandedPath, 1) <> "\" and Text.Contains(ExpandedPath, "datapackage.json") = false then
ExpandedPath & "\"
else
ExpandedPath
),
"datapackage.json",
""
),
// Build the fully qualified path of the descriptor file
DescriptorPath = BasePath & Descriptor,
// Infer the Data Package location type
DescriptorPathType = if Text.StartsWith(DescriptorPath, "http") then
"remote"
else
"local",
// Deserialise the Data Package metadata into a record
DataPackage = Json.Document(DataPackage.ResourceContents(DescriptorPath, DescriptorPathType)),
AddResourcePathType = (path as any) =>
let
Path = if path is list then
// The path type must be of a single type when data is split across multiple files, so we only need to consider the first path in the list
path{0}
else
path,
PathType = if Text.StartsWith(Path, "http") then
// The path is remote
"remote"
else
// Inherit the DataPackage descriptor path type
DescriptorPathType
in
PathType,
AddResourceFullPath = (pathOuter as any, pathTypeOuter as text, descriptorPathTypeOuter as text) =>
let
// Get the fully qualified file path
GetFullPath = (path as text, pathType as text, descriptorPathType as text) =>
let
// Flag whether the path is absolute or relative
IsRelativePath = if Text.StartsWith(path, "http") then
// This is an absolute path i.e. a URL
false
else
// This is a relative path and should inherit the base path of the DataPackage descriptor
true,
AbsolutePath = if pathType = "remote" and IsRelativePath = false then
// No resolution required; the path is already absolute
path
else if pathType = "remote" and IsRelativePath = true then
// Resolve the relative remote path to an absolute URL
BasePath & path
else if pathType = "local" and IsRelativePath = true then
// Resolve the relative local path to an absolute Windows file location
BasePath & Text.Replace(path, "/", "\")
else
try error "Unhandled path type."
in
AbsolutePath,
FullPath = if pathOuter is list then
// The path type must be the same when data is split across files
List.Transform(pathOuter, each GetFullPath(_, pathTypeOuter, descriptorPathTypeOuter))
else
GetFullPath(pathOuter, pathTypeOuter, descriptorPathTypeOuter)
in
FullPath,
// Resolve the schema descriptor. It may be inline or a reference to the location of a schema descriptor.
AddResourceResolveSchema = (schema as any) => if schema is record then
// The schema object is already present; no resolution is required.
schema
// Treat this as a reference to a schema in a remote location
else if schema is text then
// The schema property points to an external schema descriptor; resolution is required.
Json.Document(DataPackage.ResourceContents(schema, "remote"))
else
try error "The schema property is not valid.",
// Resolve the dialect descriptor. It may be inline or a reference to the location of a dialect descriptor
AddResourceResolveDialect = (dialect as any) => if dialect is record or dialect = null then
// The dialect object is already present; no resolution is required
dialect
// The assumption has been made that reference will be to a dialect in a remote location
else if dialect is text then
// The dialect property points to an external dialect descriptor; resolution is required.
Json.Document(DataPackage.ResourceContents(dialect, "remote"))
else
try error "The dialect property is not valid.",
// Extend the Data Package record with the inferred fields (i.e. properties)
ExtendedResources = [
resources = List.Transform(
DataPackage[resources],
each Record.Combine(
{
_,
[
__pathtype = AddResourcePathType([path]),
__fullpath = AddResourceFullPath([path], __pathtype, descriptorpathtype),
__resolvedschema = AddResourceResolveSchema([schema]?),
__resolveddialect = AddResourceResolveDialect([dialect]?)
]
}
)
),
descriptorpathtype = DescriptorPathType
],
// Rename the original 'resources' field to 'replacedresources' so that it can still be accessed in its unaltered state
ExtendedDataPackage = Record.Combine(
{
Record.RenameFields(DataPackage, {"resources", "replacedresources"}),
ExtendedResources
}
)
in
ExtendedDataPackage,
// Returns the data content of a Data Resource. If the file is Gzip compressed, it will be decompressed.
DataPackage.ResourceContents = (path as text, pathType as text, optional compression as text) =>
let
PathType = Text.Lower(pathType),
Compression = if compression = null then
"none"
else
Text.Lower(compression),
WebContents = Web.Contents(path),
FileContents = File.Contents(path),
CompressionErrorMessage = "Unsupported compression type. Allowed values: ""none"", ""gz"".",
PathTypeErrorMessage = "Unsupported path type. Allowed values: ""remote"", ""local"".",
Contents = if PathType = "remote" then
if Compression = "none" then
WebContents
else if Compression = "gz" then
Binary.Decompress(WebContents, Compression.GZip)
else
try error CompressionErrorMessage
else if PathType = "local" then
if Compression = "none" then
FileContents
else if Compression = "gz" then
Binary.Decompress(FileContents, Compression.GZip)
else
try error CompressionErrorMessage
else
try error PathTypeErrorMessage
in
Contents,
// Returns the untyped Data Resource (no Table Schema applied) after using the Data Package metadata to determine how the data should be parsed.
DataPackage.Resource = (dataResource as record) as table =>
let
// Get the fully qualified file path. This property will only exist if the data is not inline
Path = dataResource[__fullpath]?,
// If the data is inline then the tabular data will be represented as JSON in the 'data' property
Data = dataResource[data]?,
// Determine whether special handling of multiple data file paths is required: http://frictionlessdata.io/specs/data-resource/
MultipleDataFilePath = Path is list,
PathType = dataResource[__pathtype],
// Map valid dataResource fields to variables
Header = if (dataResource[__resolveddialect]?)[header]? = null then
if (dataResource[dialect]?)[header]? = null then
true
else
(dataResource[dialect]?)[header]?
else
(dataResource[__resolveddialect]?)[header]?,
// The handling of the compression property isn't defined by the spec so this may need to be reworked in the near-future.
InferredExtension = if MultipleDataFilePath then
Text.Range(Path{0}, Text.PositionOf(Path{0}, ".", Occurrence.Last) + 1)
else
Text.Range(Path, Text.PositionOf(Path, ".", Occurrence.Last) + 1),
InferredCompression = if List.Contains({"csv", "txt"}, InferredExtension) then
"none"
else
InferredExtension,
Compression = if dataResource[compression]? = null then
InferredCompression
else
dataResource[compression]?,
Delimiter = if dataResource[delimiter]? = null then
","
else
dataResource[delimiter]?,
// Mapping common encodings to their corresponding code page identifiers. The mappings were sourced from: https://docs.microsoft.com/en-us/windows/desktop/intl/code-page-identifiers.
CodePageIdentifiers = [
#"gb2312" = 936, // ANSI/OEM Simplified Chinese (PRC, Singapore); Chinese Simplified (GB2312)
#"x-cp20949" = 20949, // Korean Wansung
#"euc-jp" = 20932, // Japanese (JIS 0208-1990 and 0212-1990)
#"iso-8859-1" = 28591, // ISO 8859-1 Latin 1; Western European (ISO)
#"iso-8859-2" = 28592, // ISO 8859-2 Central European; Central European (ISO)
#"iso-8859-3" = 28593, // ISO 8859-3 Latin 3
#"iso-8859-4" = 28594, // ISO 8859-4 Baltic
#"iso-8859-5" = 28595, // ISO 8859-5 Cyrillic
#"iso-8859-6" = 28596, // ISO 8859-6 Arabic
#"iso-8859-7" = 28597, // ISO 8859-7 Greek
#"iso-8859-8" = 28598, // ISO 8859-8 Hebrew; Hebrew (ISO-Visual)
#"iso-8859-9" = 28599, // ISO 8859-9 Turkish
#"iso-8859-13" = 28603, // ISO 8859-13 Estonian
#"iso-8859-15" = 28605, // ISO 8859-15 Latin 9
#"us-ascii" = 20127, // US-ASCII (7-bit)
#"utf-32be" = 12001, // Unicode UTF-32, big endian byte order; available only to managed applications
#"utf-32" = 12000, // Unicode UTF-32, little endian byte order; available only to managed applications
#"utf-16" = 1200, // Unicode UTF-16, little endian byte order (BMP of ISO 10646); available only to managed applications
#"utf-8" = 65001, // Unicode (UTF-8)
#"utf-7" = 65000, // Unicode (UTF-7)
#"windows-1252"= 1252 // ANSI Latin 1; Western European (Windows)
],
Encoding = if dataResource[encoding]? = null then
65001 // UTF-8 encoding is used when this property is missing
else
// Look-up the corresponding code page identifier
(
try Record.Field(
CodePageIdentifiers,
Text.Lower(Text.From(dataResource[encoding]?))
)
otherwise 65001
),
DocumentOptions = [
Delimiter = Delimiter,
Encoding = Encoding
],
LoadCsvFile = (path as text) =>
Csv.Document(
DataPackage.ResourceContents(
path,
PathType,
Compression
),
DocumentOptions
),
LoadInlineJSON = (data as text) =>
let
JsonTabularData = Json.Document(data),
TabularDataRowType = if JsonTabularData is list and JsonTabularData{0}? is list then
"arrays"
else if JsonTabularData is list and JsonTabularData{0}? is record then
"objects"
else
try error "Invalid JSON Tabular Data",
DataTable = if TabularDataRowType = "arrays" then
#table(
JsonTabularData{0},
List.RemoveFirstN(JsonTabularData, 1)
)
else if TabularDataRowType = "objects" then
Table.FromRecords(JsonTabularData)
else
try error "Invalid JSON Tabular Data"
in
DataTable,
// Load the data from a CSV file or inline JSON depending on whether the 'path' or 'data' property has a value
LoadedData = if Path <> null then
if MultipleDataFilePath then
Table.Combine(
List.Transform(
Path,
each LoadCsvFile(_)
)
)
else
LoadCsvFile(Path)
else
// The JSON Tabular Data specifies the header so the 'promote to header' step isn't needed
LoadInlineJSON(Data),
DataTable = if Header = true and Data = null then
Table.PromoteHeaders(LoadedData)
else
LoadedData
in
DataTable,
// Attempt to convert Table Schema field type values into appropriate M type values
DataPackage.ConvertFieldValue = (fieldType as text, fieldValue as any) as any =>
let
FieldTypeAsText = Text.From(fieldValue),
MTypeValue = if fieldType = "string" then
FieldTypeAsText
else if fieldType = "number" then
Number.From(FieldTypeAsText)
else if fieldType = "integer" then
Number.From(FieldTypeAsText)
else if fieldType = "boolean" then
if List.Contains({"yes", "y", "true", "t", "1"}, Text.Lower(FieldTypeAsText)) then
true
else if List.Contains({"no", "n", "false", "f", "0"}, Text.Lower(FieldTypeAsText)) then
false
else
FieldTypeAsText
else if fieldType = "object" or fieldType = "array" then
Json.Document(FieldTypeAsText)
else if fieldType = "date" then
Date.From(FieldTypeAsText)
else if fieldType = "datetime" then
DateTime.From(FieldTypeAsText)
else if fieldType = "time" then
Time.From(FieldTypeAsText)
// Any field types that are not handled yet
else
FieldTypeAsText
in
MTypeValue,
// Map JSON Table Schema field types to equivalent M types
DataPackage.ConvertFieldType = (fieldType as text) as text =>
let
MType = if fieldType = "string" then
"text"
else if List.Contains({"number", "date", "datetime", "time"}, fieldType) then
fieldType
else if fieldType = "integer" then
"number"
else if fieldType = "boolean" then
"logical"
else
"text"
in
MType,
// Map the requested Data Package helper functions to record fields
HelperFunctions = [
DataPackage.Package = DataPackage.Package,
DataPackage.ResourceContents = DataPackage.ResourceContents,
DataPackage.Resource = DataPackage.Resource,
DataPackage.ConvertFieldType = DataPackage.ConvertFieldType,
DataPackage.ConvertFieldValue = DataPackage.ConvertFieldValue
],
// Return the requested helper function
HelperFunction = Record.Field(HelperFunctions, functionName)
in
HelperFunction,
// Add documentation
DataPackage.HelperWithDocumentation = type function (
functionName as (
type text meta [
Documentation.FieldCaption = "Function Name",
Documentation.FieldDescription = "A valid Data Package helper function name",
Documentation.SampleValues = {"DataPackage.Package"}
]
)
) as function meta [
Documentation.Name = "DataPackage.Helper",
Documentation.LongDescription = "Returns a Data Package helper function as a <code>function</code>.
<br><br>Example:
<br>
<br>
<code>let
<br> // Setup the shared function reference
<br> DataPackage.Helper = DataPackageHelper,
<br>
<br> // Get the required helper function by name
<br> DataPackage.Package = DataPackage.Helper(""DataPackage.Package""),
<br>
<br> // Invoke the helper function
<br> Source = DataPackage.Package(""https://datahub.io/core/gdp/datapackage.json"")
<br>in
<br> Source</code>
<br>
<br>
More documentation available at: https://github.com/nimblelearn/datapackage-m",
Documentation.Examples = null
]
in
Value.ReplaceType(DataPackage.Helper, DataPackage.HelperWithDocumentation)