-
Notifications
You must be signed in to change notification settings - Fork 0
/
twin.cue
318 lines (284 loc) · 7.92 KB
/
twin.cue
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
package templates
import (
"list"
"strings"
"encoding/json"
"github.com/telefonicasc/digitaltwin-vertical/schema/types"
sql_templates "github.com/telefonicasc/digitaltwin-vertical/schema/templates/sql"
)
#Twin: self={
#entityType: string // Para reutilizar el tipo de entidad
#hasHour: bool | *true // True si la vista identidad tiene horas
#hasMinute: bool | *false // True si la vista identidad tiene minutos
#multiZone: bool | *false // True si la entidad ocupa múltiples zonas
#geometryType: *"Point" | "LineString" | "MultiLineString" | "Polygon" | "MultiPolygon"
#namespace: "dtwin"
description: string
namespace: #namespace
exampleId: string
model: [string]: {
types.#ModelAttribute
// Etiqueta para identificar a los atributos que son métricas.
// Estos atributos se almacenan en la tabla histórica y son objetivo
// de las simulaciones.
#metric: bool | *false
// - 0 si el atributo es un valor absoluto.
// - 1 si es un tanto por 1.
// - 100 si es un tanto por ciento.
#scale: int | *0
// Para atributos calculados, expresión SQL que deriva el valor
// a partir de otras columnas de la tabla.
#calc: string | *""
}
model: {
TimeInstant: {
types.#DateTime
description: "Fecha / Hora del cálculo de vista identidad o simulación"
flows: ["historic", "lastdata"]
}
sourceRef: {
types.#Text
description: """
ID de entidad original.
Reemplaza al entityId en a base de datos, ya que esta entidad
es *singleton* y su ID en base de datos se ve sobrescrito
por una composición de los campos únicos.
"""
flows: ["historic", "lastdata"]
example: "Parking-01"
}
sceneRef: {
types.#Text
description: """
ID del escenario de simulación.
Identifica la simulación realizada. El valor "N/A"
indica que se trata de una vista identidad.
"""
flows: ["historic", "lastdata"]
}
trend: {
types.#Text
description: "Estacionalidad o tendencia para la que se ha calculado el escenario"
flows: ["historic"]
#range: ["Verano", "Fallas", "Otros"]
}
dayType: {
types.#Text
description: "Tipo de día al que corresponde la medida"
flows: ["historic"]
#range: ["L-J", "Viernes", "Sábado", "Domingo"]
}
if #hasHour {
hour: {
types.#Integer
description: "Hora del día a la que corresponde la medida"
flows: ["historic"]
range: "0-23"
example: 15
}
}
if #hasMinute {
minute: {
types.#Integer
description: "Intervalo de 10 minutos al que corresponde la medida"
flows: ["historic"]
range: "0-50"
example: 20
}
}
name: {
types.#Text
description: "Nombre descriptivo de la entidad"
flows: ["lastdata"]
}
location: {
types.#Geometry[#geometryType]
description: "Ubicación de la entidad"
flows: ["lastdata"]
}
if !#multiZone {
zone: {
types.#Text
description: "Identificador de la zona o distrito a la que pertenece la entidad"
example: "Distrito 1"
flows: ["lastdata"]
}
}
if #multiZone {
zoneList: {
types.#Array
description: "Lista de identificadores de la zona o distrito a la que pertenece la entidad"
example: ["Distrito 1", "Distrito 4"]
flows: ["lastdata"]
}
}
}
// Columnas que forman parte de la clave única del objeto.
#unique: [...string]
if !#hasHour && !#hasMinute {
#unique: ["sceneRef", "trend", "dayType"]
}
if #hasHour && !#hasMinute {
#unique: ["sceneRef", "trend", "dayType", "hour"]
}
if #hasMinute {
#unique: ["sceneRef", "trend", "dayType", "hour", "minute"]
}
flows: {
// Flujo histórico customizado. Tanto la primary key
// como la condición de disparo de la notificación están
// personalizadas para el caso de uso.
historic: {
class: "FLOW_HISTORIC"
endpoint: "HISTORIC"
pk: ["entityid", "timeinstant"] + #unique
dbIndexes: {
scene: "(timeinstant, sceneRef)"
}
condition: {
attrs: ["sourceRef", "TimeInstant"] + #unique
expression: q: "sceneRef"
}
replaceId: ["sourceRef"]
}
// Flujo lastdata customizado. Básicamente es la dimensión
// que contiene las coordenadas y nombres descriptivos.
lastdata: {
class: "FLOW_LASTDATA"
endpoint: "LASTDATA"
condition: {
attrs: ["TimeInstant", "sourceRef"]
// No quiero que me borre las filas de la tabla,
// cuando se borren las entidades. Me aseguro de
// excluir el alterationType onDelete.
alterationTypes: [
"entityUpdate",
"entityCreate",
]
expression: q: "sceneRef==N/A"
}
replaceId: ["sourceRef"]
}
// Flujo join de datos unidos
join: {
class: "FLOW_JOIN_VIEW"
#tableName: strings.ToLower(#entityType)
leftModel: {
name: #tableName
entityNamespace: #namespace
attrs: [
"entityid", "entityType", "fiwareservicepath", "recvtime",
] + [for label, m in self.model if list.Contains(m.flows, "historic") {
strings.ToLower(label)
}]
attrJoinOn: ["entityid"]
}
rightModel: [{
name: "\(#tableName)_lastdata"
entityNamespace: #namespace
attrs: [for label, m in self.model if !list.Contains(m.flows, "historic") {
strings.ToLower(label)
}]
attrJoinOn: [
"entityid",
]
}]
}
// Vista de simulación. Permite quedarse con
// las columnas resultado concretas de una simulacion
// particular.
sim: {
class: "FLOW_JOIN_VIEW"
#tableName: strings.ToLower(#entityType)
leftModel: {
name: "simulation_lastdata"
entityNamespace: #namespace
attrs: [
"timeinstant",
]
attrJoinOn: ["entityId", "timeinstant"]
}
rightModel: [{
name: "\(#tableName)_join"
entityNamespace: #namespace
attrs: [
"entityid", "entitytype", "recvtime", "fiwareservicepath",
] + [for label, m in self.model if label != "TimeInstant" {
strings.ToLower(label)
}]
attrJoinOn: ["sceneRef", "timeinstant"]
}]
}
}
// En el atributo "#sql", se enumera la lista de objetos
// templates/sql que se deben crear, y los atributos de input
// que se les deben proporcionar.
#sql: [label = string]: _
#export: sql: {for label, data in #sql {
(label): {
sql_templates[label]
input: {
data
namespace: #namespace
entityType: #entityType
hasHour: #hasHour
hasMinute: #hasMinute
multiZone: #multiZone
}
}
}}
flows: custom_sql: {
class: "FLOW_RAW"
sql: sources: custom_sql: {
documentation: """
Conjunto de vistas utilitarias para la presentación de
datos de escenarios identidad y simulaciones.
"""
path: "./sql"
files: [
"custom_\(#entityType).sql",
]
weight: 10
relations: list.FlattenN([for _, data in #export.sql {
data.relations
}], -1)
}
}
// Todos los objetos de tipo twin tienen un atributo #meta
// que recoge información necesaria para que luego la ETL
// pueda utilizar los datos de cualquier datasource
#export: meta: all: {
input: {
dimensions: ["sourceRef"] + #unique
fixedProps: {for _k, _v in self.model if !_v.#metric && list.Contains(_v.flows, "lastdata") && list.Contains(_v.flows, "historic") && !list.Contains(dimensions, _k) && _k != "TimeInstant" {
(_k): {
ngsiType: _v.ngsiType
scale: _v.#scale
integer: _v.dbType == "integer"
}
}}
metrics: {for _k, _v in self.model if _v.#metric {
(_k): {
ngsiType: _v.ngsiType
scale: _v.#scale
integer: _v.dbType == "integer"
}
}}
non_metrics: {for _k, _v in self.model if !_v.#metric {
(_k): _v.ngsiType
}}
calcs: {for _k, _v in self.model if !_v.#metric && _v.#calc != "" {
(_k): _v.#calc
}}
hasHour: #hasHour
hasMinute: #hasMinute
multiZone: #multiZone
namespace: #namespace
entityType: #entityType
dataTableName: "\(namespace)_\(strings.ToLower(entityType))"
dimsTableName: "\(namespace)_\(strings.ToLower(entityType))_lastdata"
}
// Genera un json con todos los metadatos
template: "\(json.Marshal(input))"
}
}