-
Notifications
You must be signed in to change notification settings - Fork 14
/
index.js
1508 lines (1439 loc) · 67.1 KB
/
index.js
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const helpers = require("dataform-ga4-helpers");
const sessionHelpers = require("./includes/helpers");
const { processingSteps } = require("./includes/processing_steps");
const { recommendedEvents } = require("./includes/recommended_events");
for (const funcName in sessionHelpers) {
if (typeof sessionHelpers[funcName] === "function") {
helpers[funcName] = sessionHelpers[funcName];
}
}
const {
defaultSessionNames,
sessionPresets,
defaultSourceMediumRules,
defaultPostProcessing,
} = require("./includes/constants");
const { defaultAssertions } = require("./includes/assertions");
const bigQueryOptions = [
"clusterBy",
"updatePartitionFilter",
"additionalOptions",
"partitionExpirationDays",
"requirePartitionFilter",
];
/**
* dataform-ga4-sessions module
* @module dataform-ga4-sessions
* @typicalname ga4
* @example
* ```js
* const ga4 = require('dataform-ga4-sessions')
* ```
*/
/**
* Creates Dataform Action to build GA4 Event tables based on BigQuery exported data.
* @class
* @package
*/
class DataformAction {
/**
* @param {Object} sourceConfig - GA4 BigQuery Source configuration
* @param {string} sourceConfig.database - The GA4 export database name. For example `<YOUR-GCP-PROJECT-ID>`
* @param {string} sourceConfig.dataset - The GA4 export database name. For example `<YOUR-GCP-PROJECT-ID>`
* @param {string} sourceConfig.incrementalTableName - Source incremental table name. For example `events_20240101`
* @param {string} sourceConfig.nonIncrementalTableName - Source non-incremental table name. For example `events_*`
* @param {string} sourceConfig.incrementalTableEventStepWhere - This property set where condition for the incremental queries. The important note this condition is added to the first step, not the final step. So if you filter for example events with source / medium values you could miss this data in the final result. Default is false
* @param {string} sourceConfig.nonIncrementalTableEventStepWhere - This property set where condition for the non-incremental queries. The important note this condition is added to the first step, not the final step. So if you filter for example events with source / medium values you could miss this data in the final result. Default is false
* @param {Object} targetConfig - Optional. Target configuration
* @param {string} targetConfig.schema - Optional. Target schema name
* @param {string} targetConfig.tableName - Optional. Target table name
*/
constructor(sourceConfig, targetConfig) {
/**
* @property {Object} source - GA4 BigQuery Source configuration
* @property {string} source.database - The GA4 export database name. For example `<YOUR-GCP-PROJECT-ID>`
* @property {string} source.dataset - The GA4 export database name. For example `<YOUR-GCP-PROJECT-ID>`
* @property {string} source.incrementalTableName - Source incremental table name. For example `events_20240101`
* @property {string} source.nonIncrementalTableName - Source non-incremental table name. For example `events_*`
* @property {string} source.incrementalTableEventStepWhere - This property set where condition for the incremental queries. The important note this condition is added to the first step, not the final step. So if you filter for example events with source / medium values you could miss this data in the final result. Default is false
* @property {string} source.nonIncrementalTableEventStepWhere - This property set where condition for the non-incremental queries. The important note this condition is added to the first step, not the final step. So if you filter for example events with source / medium values you could miss this data in the final result. Default is false
*/
this._source = {
database: sourceConfig.database || dataform.projectConfig.defaultDatabase,
dataset: sourceConfig.dataset,
incrementalTableName: sourceConfig.incrementalTableName,
incrementalTableEventStepWhere:
sourceConfig.incrementalTableEventStepWhere || false,
nonIncrementalTableName:
sourceConfig.nonIncrementalTableName || "events_*",
nonIncrementalTableEventStepWhere:
sourceConfig.nonIncrementalTableEventStepWhere || false,
};
/**
* Use getter / setter methods to set values for the following properties.
* @property {Object} target - Destination table config.
* @property {string} target.schema - The target schema. Destination dataset name. Default is dataform_staging
* @property {string} target.tableName - The target table name. Destination table name.
* @example
* ```js
* session.target = {schema: "dataform_testing", tableName: "test_sessions"}}
* ```
*/
this._target = {
schema:
targetConfig && targetConfig.schema
? targetConfig.schema
: "dataform_staging",
tableName:
targetConfig && targetConfig.tableName ? targetConfig.tableName : null,
};
/**
* @property {string} timezone - The timezone. Default is `Europe/London`
* @example
* ```js
* session.timezone = "Europe/Berlin"
* ```
*/
this._timezone = "Europe/London";
/**
* @property {string[]} tags - Dataform [execution tags](https://cloud.google.com/dataform/docs/tags) needed to run a chose a set of actions to run. By default `[source.dataset]` tag is added.
* @example
* ```js
* session.tags = ["daily","hourly"]
* ```
*/
this._tags = [this._source.dataset];
/**
* @property {Array.<{name: String, config: {description: String}, query: function(String):String}>} assertions - List of default [Dataform assertions](https://cloud.google.com/dataform/docs/assertions) for the class, but in most cases if you need extra assertions you could define them outside the class in separate files.
*
*/
this._assertions = [];
/**
* @property {string} partitionBy - The [partition by])(https://cloud.google.com/dataform/docs/partitions-clusters#create_a_table_partition). Dataform use this keys to generate partitioned tables. By default partitionBy is set to `date`. If you want to use another partitionBy value you need to set it manually.
* @example
* ```js
* session._partitionBy = "DATE(timestamp)"
* ```
*/
this._partitionBy = "date";
/**
* @property {string} uniqueKey - The [unique key](https://cloud.google.com/dataform/docs/incremental-tables#merge_rows_in_an_incremental_table) for incremental tables. Dataform use this keys to generate merge queries.
* @example
* ```js
* session.uniqueKey = ["session_id","date"]
* ```
*/
this._uniqueKey = [];
/**
* @property {string[]} clusterBy - The [cluster by](https://cloud.google.com/dataform/docs/partitions-clusters#create_a_table_cluster). Dataform use this keys to generate clustered tables. By default clusterBy is not set. If you want to use clusterBy you need to set it manually.
* @example
* ```js
* session.clusterBy = ["name", "revenue"]
* ```
*/
this._clusterBy = undefined;
/**
* @property {string} updatePartitionFilter - The [update partition filter](https://cloud.google.com/dataform/docs/incremental-tables#filter_rows_in_an_incremental_table). Dataform use this keys to to avoid scanning the whole table to find matching rows, set updatePartitionFilter to only consider a subset of records. By default updatePartitionFilter is not set. If you want to use updatePartitionFilter you need to set it manually.
* @example
* ```js
* session.updatePartitionFilter = "timestamp >= timestamp_sub(current_timestamp(), interval 24 hour)"
* ```
*/
this._updatePartitionFilter = undefined;
/**
* @property {Object} additionalOptions - [IBigQueryOptions additionalOptions](https://cloud.google.com/dataform/docs/reference/dataform-core-reference#bigquery). Key-value pairs for the table, view, and materialized view options.
* @example
* ```js
* session.additionalOptions = {numeric_option: "5", string_option: '"string-value"'}
* ```
*/
this._additionalOptions = undefined;
/**
* @property {number} partitionExpirationDays - [IBigQueryOptions partitionExpirationDays](https://cloud.google.com/dataform/docs/reference/dataform-core-reference#bigquery). The number of days for which BigQuery stores data in each partition. The setting applies to all partitions in a table, but is calculated independently for each partition based on the partition time.
* @example
* ```js
* session.partitionExpirationDays = 90
* ```
*/
this._partitionExpirationDays = undefined;
/**
* @property {boolean} requirePartitionFilter - [IBigQueryOptions partitionExpirationDays](https://cloud.google.com/dataform/docs/reference/dataform-core-reference#bigquery). Declares whether the partitioned table requires a WHERE clause predicate filter that filters the partitioning column.
* @example
* ```js
* session.requirePartitionFilter = true
* ```
*/
this._requirePartitionFilter = undefined;
bigQueryOptions.forEach((prop) => {
this[`_${prop}`] = undefined; // Initialize private properties with default values
Object.defineProperty(this, prop, {
get: function () {
return this[`_${prop}`];
},
set: function (value) {
this[`_${prop}`] = value;
},
});
});
/**
* @property {Object[]} columns - List of columns from GA4 raw table to be added to the final table. You could check the list of all available columns [here](https://support.google.com/analytics/answer/7029846?hl=en). By default columns are added based on the preset. Or you could add them manually using `addColumns` method.
* @property {String} columns[].name - Name of the column in GA4 raw table.
* @property {String} [columns[].columnName] - Optional. The name of the column in the result table. If not provided the name will be the same as in GA4 raw table.
*/
this._columns = [];
/**
* @property {Object[]} eventParams - List of event params unnested from GA4 raw table event_params column. By default `eventParams` are added based on the preset. You could add your custom event_params using `addEventParams` method.
* @property {String} eventParams[].name - The value of `key` in the event_params record.
* @property {String} [eventParams[].columnName] - Optional. The name of the column in the result table. If not provided the name will be the same as `eventParams[].name`.
* @property {'string' | 'int' | 'double' | 'float' | 'coalesce' | 'coalesce_float'} [eventParams[].type] - Optional. The name of the value in the event_params column. By default `string`.
*/
this._eventParams = [];
/**
* @property {Object[]} userProperties - List of user properties unnested from GA4 raw table user_properties column. By default `userProperties` are not added. You could add your custom user_properties using `addUserProperties` method.
* @property {String} userProperties[].name - The value of `key` in the user_properties record.
* @property {String} [userProperties[].columnName] - Optional. The name of the column in the result table. If not provided the name will be the same as `userProperties[].name`.
* @property {'string' | 'int' | 'double' | 'float' | 'coalesce' | 'coalesce_float'} [userProperties[].type] - Optional. The name of the value in the event_params column. By default `string`.
*/
this._userProperties = [];
/**
* @property {Object[]} queryParameters - List of query parameters from the unnested `event_params` column with the key `page_location`. You could add your custom query_parameters using `addQueryParameters` method.
* @property {String} queryParameters[].name - The query parameter name.
* @property {String} [queryParameters[].columnName] - Optional. The name of the column in the result table. If not provided the name will be the same as `queryParameters[].name`.
*/
this._queryParameters = [];
/**
* @property {Object[]} itemColumns - List of child columns to keep in the final table from `items` column. By default `itemColumns` are not added, and if items added as a column all child columns wil be added. You could add itemColumns manually using `addItemColumns` method.
* @property {String} itemColumns[].name - Name of child column the column in GA4 raw table.
* @property {String} [itemColumns[].columnName] - Optional. The name of the column in the result table. If not provided the name will be the same as `itemColumns[].name`.
*/
this._itemColumns = [];
/**
* @property {Object[]} itemParams - List of event params of item scope unnested from GA4 raw table items.item_params column. By default `itemParams` are not added. You could add your custom item_params using `addItemParams` method.
* @property {String} itemParams[].name - The value of `key` in the items.item_params record.
* @property {String} [itemParams[].columnName] - Optional. The name of the column in the result table. If not provided the name will be the same as `itemParams[].name`.
* @property {'string' | 'int' | 'double' | 'float' | 'coalesce' | 'coalesce_float'} [userProperties[].type] - Optional. The name of the value in the event_params column. By default `string`.
*/
this._itemParams = [];
const properties = [
"columns",
"eventParams",
"userProperties",
"queryParameters",
"itemColumns",
"itemParams",
];
properties.forEach((prop) => {
Object.defineProperty(this, prop, {
get: function () {
return this[`_${prop}`];
},
set: function (value) {
this.validateEventParams(value);
items.forEach((item) => {
if (
defaultSessionNames.includes(
item.columnName ? item.columnName : item.name
)
) {
return;
}
this[`_${prop}`].push(item);
});
},
});
});
}
#addItemsToProperty(items, propertyName) {
this.validateEventParams(items);
const currentItemNames = this[`_${propertyName}`].map((item) => item.name);
items.forEach((item) => {
if (
defaultSessionNames.includes(
item.columnName ? item.columnName : item.name
)
) {
return;
}
if (currentItemNames.includes(item.name)) {
// change item to a new item
const index = currentItemNames.indexOf(item.name);
this[`_${propertyName}`][index] = item;
} else {
this[`_${propertyName}`].push(item);
}
currentItemNames;
});
}
/**
*
* @param {Object[]} columns - List of columns from GA4 raw table to be added to the final table.
* @param {String} columns[].name - Name of the column in GA4 raw table.
* @param {String} [columns[].columnName] - Optional. The name of the column in the result table. If not provided the name will be the same as in GA4 raw table.
* @example
* ```js
* session.addColumns([
* { name: "geo.city", columnName: "city" },
* { name: "geo.metro", columnName: "metro" },
* { name: "stream_id" },
* { name: "platform" },
* ])
* ```
* @description
* :::warning
* If you add columns with `RECORD` type, like: `device.*`, `geo.*` you should specify the `columnName`. Because the result column name couldn't have a dot (.) symbol in the name.
* :::
*/
addColumns(columns) {
this.#addItemsToProperty(columns, "columns");
}
/**
* @param {Object[]} eventParams - List of event params unnested from GA4 raw table event_params column.
* @param {String} eventParams[].name - The value of `key` in the event_params record.
* @param {String} [eventParams[].columnName] - Optional. The name of the column in the result table. If not provided the name will be the same as `eventParams[].name`.
* @param {'string' | 'int' | 'double' | 'float' | 'coalesce' | 'coalesce_float'} [eventParams[].type] - Optional. The name of the value in the event_params column. By default `string`.
* @example
* ```js
* session.addEventParams([
* { name: "page_title", type: "string" }
* ])
* ```
*/
addEventParams(eventParams) {
this.#addItemsToProperty(eventParams, "eventParams");
}
/**
* @param {Object[]} userProperties - List of user properties unnested from GA4 raw table user_properties column.
* @param {String} userProperties[].name - The value of `key` in the user_properties record.
* @param {String} [userProperties[].columnName] - Optional. The name of the column in the result table. If not provided the name will be the same as `userProperties[].name`.
* @param {'string' | 'int' | 'double' | 'float' | 'coalesce' | 'coalesce_float'} [userProperties[].type] - Optional. The name of the value in the event_params column. By default `string`.
* @example
* ```js
* session.addUserProperties([
* { name: "user_status", type: "string" }
* ])
* ```
*/
addUserProperties(userProperties) {
this.#addItemsToProperty(userProperties, "userProperties");
}
/**
* @param {Object[]} queryParameters - List of query parameters from the unnested `event_params` column with the key `page_location`.
* @param {String} queryParameters[].name - The query parameter name.
* @param {String} [queryParameters[].columnName] - Optional. The name of the column in the result table. If not provided the name will be the same as `queryParameters[].name`.
* @example
* ```js
* session.addQueryParameters([
* { name: "fbclid" },
* { name: "ttclid" },
* { name: "gclid", columnName: "gclid_url" },
* ])
* ```
*/
addQueryParameters(queryParameters) {
this.#addItemsToProperty(queryParameters, "queryParameters");
}
/**
*
* @property {Object[]} itemColumns - List of child columns to keep in the final table from `items` column. By default `itemColumns` are not added, and if items added as a column all child columns wil be added. You could add itemColumns manually using `addItemColumns` method.
* @property {String} itemColumns[].name - Name of child column the column in GA4 raw table.
* @property {String} [itemColumns[].columnName] - Optional. The name of the column in the result table. If not provided the name will be the same as `itemColumns[].name`.
* @example
* ```js
* purchase.addItemColumns([
* { name: "item_id" },
* { name: "item_name" },
* { name: "price" },
* { name: "quantity" },
* ])
* ```
* @description
* :::note
* Supported only in Event class
* :::
* In the example below from items columns only `item_id`, `item_name`, `price`, `quantity` will be added to the final table in the `items.item_id`, `items.item_name`, `items.price`, `items.quantity` accordingly.
*/
addItemColumns(itemColumns) {
this.#addItemsToProperty(itemColumns, "itemColumns");
}
/**
*
* @property {Object[]} itemParams - List of names of item-scoped custom dimensions to extract from `items.item_params` by key. By default `itemParams` are not added. You could add itemParams manually using `addItemParams` method.
* @property {String} itemParams[].name - Name of item-scoped custom dimensions.
* @property {String} [itemParams[].columnName] - Optional. The name of the column in the result table. If not provided the name will be the same as `itemParams[].name`.
* @param {'string' | 'int' | 'double' | 'float' | 'coalesce' | 'coalesce_float'} [userProperties[].type] - Optional. The type of the value in the `items.item_params` column. By default `string`.
* @example
* ```js
* purchase.addItemParams([
* { name: "color" , columnName: "item_color"},
* ])
* ```
* @description
* :::note
* Supported only in Event class
* :::
* In the example below the items.item_params column will be expanded and filtered for the key color. The resulting string values will be stored in items.item_color.
*/
addItemParams(itemParams) {
this.#addItemsToProperty(itemParams, "itemParams");
}
/**
* Helper method to generate SQL code to get unique id for each row in a final table, used inside publish method. Should be overwritten in the child class.
*/
getSqlUniqueId() {}
get timezone() {
return this._timezone;
}
set timezone(timezone) {
this._timezone = timezone || "Europe/London";
}
get tags() {
return this._tags;
}
set tags(value) {
if (Array.isArray(value)) {
this._tags.push(...value);
} else if (typeof value === "string") {
this._tags.push(value);
} else {
throw new TypeError("Tags should be an array or a string");
}
}
get target() {
return this._target;
}
set target(config) {
this._target = {
schema: config.schema || "dataform_staging",
tableName: config.tableName,
};
}
getConfig() {
const config = {
type: "incremental",
uniqueKey: this._uniqueKey,
schema: this._target.schema,
tags: this._tags,
bigquery: {
partitionBy: this._partitionBy,
},
};
bigQueryOptions.forEach((prop) => {
if (this[`_${prop}`]) {
config.bigquery[prop] = this[`_${prop}`];
}
});
return config;
}
get assertions() {
return this._assertions;
}
set assertions(config) {
if (Array.isArray(value)) {
this._tags.push(...value);
} else {
throw new TypeError("Tags should be an array of assertions");
}
this._assertions = config;
}
validateEventParams(value) {
if (!Array.isArray(value)) {
throw new TypeError("Columns should be an array");
}
value.forEach((column) => {
if (typeof column !== "object" || column === null) {
throw new TypeError("Each column should be an object");
}
// Check if the 'name' property exists and is not an empty string
if (
!column.hasOwnProperty("name") ||
typeof column.name !== "string" ||
column.name.trim() === ""
) {
throw new TypeError(
"Each column should have a required 'name' property of string type and it should not be empty"
);
}
if (
column.hasOwnProperty("columnName") &&
typeof column.columnName !== "string"
) {
throw new TypeError(
"Each column should have a 'columnName' property of string type"
);
}
const validTypes = [
"string",
"int",
"double",
"float",
"coalesce",
"coalesce_float",
];
if (
column.hasOwnProperty("type") &&
!validTypes.includes(column.type.toLowerCase())
) {
throw new TypeError(
`Each column should have a 'type' property with one of the following values: ${validTypes.join(
", "
)}`
);
}
});
}
/**
* Main method to publish Dataform Action. This method generates SQL and then uses Dataform core [publish](https://cloud.google.com/dataform/docs/reference/dataform-core-reference#publish) method to generate incremental and non-incremental session table. This method should be overwritten in the child class.
*/
publish() {}
/**
* The method to publish default [Dataform assertions](https://cloud.google.com/dataform/docs/assertions). This method should be overwritten in the child class.
*/
publishAssertions() {}
}
/**
* Creates Dataform Action to build GA4 event tables based on BigQuery exported data, for example table for `purchase` events. But instead of using this class directly, it is recommended to use `EventFactory` to create events. The factory could simplify the creation of auto or recommended events. But after the creation of the event, you could use any of `DataformAction` methods and properties.
* @class
* @augments DataformAction
*/
class Event extends DataformAction {
/**
* Constructor for the Event class inherited from DataformAction class. Before creating the object of this class you need to declare GA4 source tables using `declareSources` method.
* @param {Object} sourceConfig - GA4 BigQuery Source configuration
* @param {string} sourceConfig.database - The GA4 export database name. For example `<YOUR-GCP-PROJECT-ID>`
* @param {string} sourceConfig.dataset - The GA4 export database name. For example `<YOUR-GCP-PROJECT-ID>`
* @param {string} sourceConfig.incrementalTableName - Source incremental table name. For example `events_20240101`
* @param {string} sourceConfig.nonIncrementalTableName - Source non-incremental table name. For example `events_*`
* @param {string} sourceConfig.incrementalTableEventStepWhere - This property set where condition for the incremental queries. The important note this condition is added to the first step, not the final step. So if you filter for example events with source / medium values you could miss this data in the final result. Default is false
* @param {string} sourceConfig.nonIncrementalTableEventStepWhere - This property set where condition for the non-incremental queries. The important note this condition is added to the first step, not the final step. So if you filter for example events with source / medium values you could miss this data in the final result. Default is false
* @param {Object} targetConfig - Optional. Target configuration
* @param {string} targetConfig.schema - Optional. Target schema name. Default is `dataform_staging`
* @param {string} targetConfig.tableName - Optional. Target table name.
* @example
* ```js
* // Define your config
* const eventConfig = {
* dataset: "analytics_XXXXXX",
* incrementalTableName: "events_XXXXXX",
* };
*
* // Declare GA4 source tables
* ga4.declareSources(eventConfig);
*
* // Create event
* let purchase = new ga4.Event(eventConfig);
*
* // Set destination table name and add where conditions for the event
* purchase.setEventName("purchase");
*```
*/
constructor(sourceConfig, targetConfig) {
super(sourceConfig, targetConfig);
/**
* @property {string} uniqueKey - The [unique key](https://cloud.google.com/dataform/docs/incremental-tables#merge_rows_in_an_incremental_table) for incremental tables. Dataform use this keys to generate merge queries. Default value for Event is `["date", "event_id"]`
* @example
* ```js
* event.uniqueKey = ["event_id","date"]
* ```
*/
this._uniqueKey = ["date", "event_id"];
/**
* @property {string} timestampEventParamName - This property will be used to generate unique event_id. The value will be from unnested `event_params` column with the key equals the value of this property. But at first you should add this event parameter in your GTM setup.
* ```js
* event.timestampEventParamName = "gtm_event_timestamp"
* ```
*/
this._timestampEventParamName = undefined;
this._skipUniqueEventsStep = false;
}
get timestampEventParamName() {
return this._timestampEventParamName;
}
set timestampEventParamName(timestampEventParamName) {
this._timestampEventParamName = timestampEventParamName;
}
/**
*
* @property {Object[]} itemColumns - List of child columns to keep in the final table from `items` column. By default `itemColumns` are not added, and if items added as a column all child columns wil be added. You could add itemColumns manually using `addItemColumns` method.
* @property {String} itemColumns[].name - Name of child column the column in GA4 raw table.
* @property {String} [itemColumns[].columnName] - Optional. The name of the column in the result table. If not provided the name will be the same as `itemColumns[].name`.
* @example
* ```js
* purchase.addItemColumns([
* { name: "item_id" },
* { name: "item_name" },
* { name: "price" },
* { name: "quantity" },
* ])
* ```
* @description
* :::warning
* If you provide doesn't existing column name in the `itemColumns` list, you will get a SQL error and can't build the table.
* :::
* In the example below from items columns only `item_id`, `item_name`, `price`, `quantity` will be added to the final table in the `items.item_id`, `items.item_name`, `items.price`, `items.quantity` accordingly.
*/
addItemColumns(itemColumns) {
super.addItemColumns(itemColumns);
}
/**
*
* @property {Object[]} itemParams - List of names of item-scoped custom dimensions to extract from `items.item_params` by key. By default `itemParams` are not added. You could add itemParams manually using `addItemParams` method.
* @property {String} itemParams[].name - Name of item-scoped custom dimensions.
* @property {String} [itemParams[].columnName] - Optional. The name of the column in the result table. If not provided the name will be the same as `itemParams[].name`.
* @param {'string' | 'int' | 'double' | 'float' | 'coalesce' | 'coalesce_float'} [userProperties[].type] - Optional. The type of the value in the `items.item_params` column. By default `string`.
* @example
* ```js
* purchase.addItemParams([
* { name: "color" , columnName: "item_color"},
* ])
* ```
* @description
* :::warning
* item_params were added to the BigQuery export late October 2023. And you can't use addItemParams for events before that date.
* :::
* In the example below the items.item_params column will be expanded and filtered for the key color. The resulting string values will be stored in items.item_color. */
addItemParams(itemParams) {
super.addItemParams(itemParams);
}
/**
* Helper method to skip unique events step. By default `where` condition is added to filter all events with `event_id` equals to null. Also `QUALIFY` statement is added to get only one event per `event_id`. But if you want to skip this step you could use this method.
* @example
* ```js
* event.skipUniqueEventsStep();
* ```
*/
skipUniqueEventsStep() {
this._skipUniqueEventsStep = true;
}
/**
* Helper method to generate SQL code to get unique id for each row in a final table, used inside publish method. By default it use getSqlEventId from dataform-ga4-helpers package
*/
getSqlUniqueId() {
return helpers.getSqlEventId(this._timestampEventParamName);
}
/**
* This helper method will use event name to define target table and add where conditions for the final query. It's recommended to use `EventFactory` to create events. But if you want to create event manually you could use this method.
* @param {string} eventName - The event name. For example `purchase`
* @example
* ```js
* event.setEventName("purchase")
* ```
*/
setEventName(eventName) {
if (!this._target.tableName) this._target.tableName = eventName;
if (!this._source.incrementalTableEventStepWhere)
this._source.incrementalTableEventStepWhere = `event_name = '${eventName}'`;
if (!this._source.nonIncrementalTableEventStepWhere)
this._source.nonIncrementalTableEventStepWhere = `event_name = '${eventName}'`;
}
#getSqlItemParam = (paramName, paramType = "string", columnName = false) =>
`${helpers.getSqlUnnestParam(
paramName,
paramType,
null,
"i.item_params"
)} as ${columnName ? columnName : paramName}`;
#getSqlItemParams = (itemParams) => {
const sql = itemParams.map((itemParam) =>
this.#getSqlItemParam(
itemParam.name,
itemParam.type,
itemParam.columnName
)
);
return itemParams.length > 0 ? sql.join(", ") : "";
};
#deleteItemsIfItemsColumnExists(_columns) {
let columns = [..._columns];
if (
(columns.map((item) => item.name).indexOf("items") > -1) &
(this._itemColumns.length > 0)
) {
columns = columns.filter((item) => item.name !== "items");
}
return columns;
}
#sqlItemsColumns(itemColumns) {
return `ARRAY(
SELECT AS STRUCT ${itemColumns
.map(
(item) =>
`${item.name} as ${item.columnName ? item.columnName : item.name}`
)
.join(", ")}
${
this._itemParams.length > 0
? `, ${this.#getSqlItemParams(this._itemParams)}`
: ""
}
FROM UNNEST(items) i order by 1 asc
) AS items
`;
}
/**
* Main method to publish Dataform Action. This method generates SQL and then uses Dataform core [publish](https://cloud.google.com/dataform/docs/reference/dataform-core-reference#publish) method to generate incremental and non-incremental session table. This method should be overwritten in the child class.
* @example
* ```js
* purchase.publish()
* ```
*/
publish() {
if (!this._target.tableName) {
throw new Error("Table name is required, please set target.tableName");
}
const events = publish(this._target.tableName, {
schema: this._target.schema,
})
.config(this.getConfig())
.query(
(ctx) => `
-- prepare events table
with events_tbl as (
select
${helpers.getSqlSessionId()},
${this.getSqlUniqueId(this._timestampEventParamName)},
${helpers.getSqlDate(this._timezone)},
${helpers.getSqlEventParam("page_location")},
TIMESTAMP_MICROS(event_timestamp) as event_timestamp,
user_id,
user_pseudo_id,
${ctx.when(
this._columns.length > 0,
`${helpers.getSqlColumns(
this.#deleteItemsIfItemsColumnExists(this._columns)
)}, `
)}
${ctx.when(
this._eventParams.length > 0,
`${helpers.getSqlEventParams(this._eventParams)}, `
)}
${ctx.when(
this._userProperties.length > 0,
`${helpers.getSqlUserProperties(this._userProperties)}, `
)}
${ctx.when(
this._queryParameters.length > 0,
`${helpers.getSqlQueryParameters(
helpers.getSqlEventParam("page_location", "string", null),
this._queryParameters
)}, `
)}
${ctx.when(
this._itemColumns.length > 0,
`${this.#sqlItemsColumns(this._itemColumns)}, `
)}
from
${ctx.when(
ctx.incremental(),
`${ctx.ref(
this._source.database,
this._source.dataset,
this._source.incrementalTableName
)}
${
this._source.incrementalTableEventStepWhere
? "WHERE " + this._source.incrementalTableEventStepWhere
: ""
}
`
)}
${ctx.when(
!ctx.incremental(),
`${ctx.ref(
this._source.database,
this._source.dataset,
this._source.nonIncrementalTableName
)}
${
this._source.nonIncrementalTableEventStepWhere
? "WHERE " + this._source.nonIncrementalTableEventStepWhere
: ""
}
`
)}
)
${
this._skipUniqueEventsStep
? ""
: `, unique_events_tbl as (
select
*
from events_tbl
where event_id is not null
QUALIFY ROW_NUMBER() OVER (
PARTITION BY event_id
) = 1
)`
}
-- select final result from the last processing step and apply post processing
select
* ${
this._postProcessing &&
this._postProcessing.delete &&
this._postProcessing.delete.length > 0
? `except (${this._postProcessing.delete.join(", ")})`
: ""
}
from ${this._skipUniqueEventsStep ? "events_tbl" : "unique_events_tbl"}
`
);
return events;
}
}
/**
* Helper class to create GA4 events. It's recommended to use this class to create events. But if you want to create event manually you could use `Event` class.
* @class
*/
class EventFactory {
/**
* Create any recommended or auto event using EventFactory method like `createEventName`.
* @param {Object} sourceConfig - GA4 BigQuery Source configuration
* @param {string} sourceConfig.database - The GA4 export database name. For example `<YOUR-GCP-PROJECT-ID>`
* @param {string} sourceConfig.dataset - The GA4 export database name. For example `<YOUR-GCP-PROJECT-ID>`
* @param {string} sourceConfig.incrementalTableName - Source incremental table name. For example `events_20240101`
* @param {string} sourceConfig.nonIncrementalTableName - Source non-incremental table name. For example `events_*`
* @param {string} sourceConfig.incrementalTableEventStepWhere - This property set where condition for the incremental queries. The important note this condition is added to the first step, not the final step. So if you filter for example events with source / medium values you could miss this data in the final result. Default is false
* @param {string} sourceConfig.nonIncrementalTableEventStepWhere - This property set where condition for the non-incremental queries. The important note this condition is added to the first step, not the final step. So if you filter for example events with source / medium values you could miss this data in the final result. Default is false
* @example
* ```js
* // Define your config
* const eventConfig = {
* dataset: "analytics_XXXXXX",
* incrementalTableName: "events_XXXXXX",
* };
*
* // Define EventFactory
* const ef = new ga4.EventFactory(eventConfig);
*
* // Create purchase event:
* const purchase = ef.createPurchase();
*
* //Publish event
* purchase.publish()
* ```
*/
constructor(sourceConfig) {
this._source = sourceConfig;
/**
* @property {string} timestampEventParamName - This property will be used to generate unique event_id. The value will be from unnested `event_params` column with the key equals the value of this property. But at first you should add this event parameter in your GTM setup.
* @example
* ```js
* // Define EventFactory
* const ef = new ga4.EventFactory(eventConfig);
* // Set timestampEventParamName
* ef.timestampEventParamName = "gtm_event_timestamp"
* ```
*/
this._timestampEventParamName = undefined;
/**
* @property {string} targetSchema - This property will be used to set target schema for all events generated by factory.
* @example
* ```js
* // Define EventFactory
* const ef = new ga4.EventFactory(eventConfig);
* // Set target schema for all events created by factory
* ef.targetSchema = 'my_schema'
* let events = ef.createEcommerceEvents();
* events.forEach((event) => {
* // But you could overwrite target schema for particular event
* if (event.target.tableName === "purchase") {
* event.target.schema = " my_schema_2";
* }
* event.publish()
* });
* ```
*/
this._targetSchema = undefined;
recommendedEvents.forEach((eventConfig) => {
this[`create${this.#snakeToCamel(eventConfig.eventName)}`] = () => {
return this.createEvent(eventConfig);
};
});
}
get timestampEventParamName() {
return this._timestampEventParamName;
}
set timestampEventParamName(timestampEventParamName) {
this._timestampEventParamName = timestampEventParamName;
}
get targetSchema() {
return this._targetSchema;
}
set targetSchema(targetSchema) {
this._targetSchema = targetSchema;
}
#snakeToCamel(str) {
let result = str.replace(/(_\w)/g, function (m) {
return m[1].toUpperCase();
});
return result.charAt(0).toUpperCase() + result.slice(1);
}
/**
* @param {Object} eventConfig - Event configuration
* @param {String} eventConfig.eventName - Event name. For example `purchase`
* @param {Object} [eventConfig.columns] - List of columns from GA4 raw table to be added to the final table. You could check the list of all available columns [here](https://support.google.com/analytics/answer/7029846?hl=en). By default columns are added based on the preset. Or you could add them manually using `addColumns` method.
* @param {String} [eventConfig.columns.name] - Name of the column in GA4 raw table.
* @param {String} [eventConfig.columns.columnName] - Optional. The name of the column in the result table. If not provided the name will be the same as in GA4 raw table.
* @param {Object} [eventConfig.eventParams] - List of event params unnested from GA4 raw table event_params column. By default `eventParams` are added based on the preset. You could add your custom event_params using `addEventParams` method.
* @param {String} [eventConfig.eventParams.name] - The value of `key` in the event_params record.
* @param {String} [eventParams.columnName] - Optional. The name of the column in the result table. If not provided the name will be the same as `eventParams.name`.
* @param {'string' | 'int' | 'double' | 'float' | 'coalesce' | 'coalesce_float'} [eventConfig.eventParams.type] - Optional. The name of the value in the event_params column. By default `string`.
* @param {Object} [eventConfig.userProperties] - List of user properties unnested from GA4 raw table user_properties column. By default `userProperties` are not added. You could add your custom user_properties using `addUserProperties` method.
* @param {String} [eventConfig.userProperties.name] - The value of `key` in the user_properties record.
* @param {String} [eventConfig.userProperties.columnName] - Optional. The name of the column in the result table. If not provided the name will be the same as `userProperties.name`.
* @param {'string' | 'int' | 'double' | 'float' | 'coalesce' | 'coalesce_float'} [eventConfig.userProperties.type] - Optional. The name of the value in the event_params column. By default `string`.
* @param {Object} [eventConfig.queryParameters] - List of query parameters from the unnested `event_params` column with the key `page_location`. You could add your custom query_parameters using `addQueryParameters` method.
* @param {String} [eventConfig.queryParameters.name] - The query parameter name.
* @param {String} [eventConfig.queryParameters.columnName] - Optional. The name of the column in the result table. If not provided the name will be the same as `queryParameters[].name`.
* @returns {Event} Event object
* @example
* ```js
* const purchase = ef.createEvent({
* eventName: "session_start",
* columns:[{name:"privacy_info.analytics_storage", columnName:"analytics_storage"}],
* eventParams:[ { name: "page_referrer", type: "string" }]
* })
* ```
*/
createEvent(eventConfig) {
let sourceConfig = { ...this._source };
const whereCondition = `event_name = '${eventConfig.eventName}'`;
sourceConfig.incrementalTableEventStepWhere =
sourceConfig.incrementalTableEventStepWhere
? sourceConfig.incrementalTableEventStepWhere + ` AND ${whereCondition}`
: whereCondition;
sourceConfig.nonIncrementalTableEventStepWhere =
sourceConfig.nonIncrementalTableEventStepWhere
? sourceConfig.nonIncrementalTableEventStepWhere +
` AND ${whereCondition}`
: whereCondition;
const targetConfig = { tableName: eventConfig.eventName };
if (this._targetSchema) targetConfig.schema = this._targetSchema;
const event = new Event(sourceConfig, targetConfig);
if (eventConfig.eventParams) event.addEventParams(eventConfig.eventParams);
if (eventConfig.columns) event.addColumns(eventConfig.columns);
if (eventConfig.userProperties)
event.userProperties(eventConfig.userProperties);
if (eventConfig.queryParameters)
event.addQueryParameters(eventConfig.queryParameters);
if (this._timestampEventParamName) {
event.timestampEventParamName = this._timestampEventParamName;
}
return event;
}
/**
* Tne method to create multiple events using list of events configurations. This method is useful if you want to reuse the same event configurations between projects. In this case you could define event configurations in separate file and import the configs and create events using this helper method.
* @param {Object[]} eventConfig - List of event configurations
* @param {String} eventConfig[].eventName - Event name. For example `purchase`
* @param {Object} [eventConfig[].columns] - List of columns from GA4 raw table to be added to the final table. You could check the list of all available columns [here](https://support.google.com/analytics/answer/7029846?hl=en). By default columns are added based on the preset. Or you could add them manually using `addColumns` method.
* @param {String} [eventConfig[].columns.name] - Name of the column in GA4 raw table.
* @param {String} [eventConfig[].columns.columnName] - Optional. The name of the column in the result table. If not provided the name will be the same as in GA4 raw table.
* @param {Object} [eventConfig[].eventParams] - List of event params unnested from GA4 raw table event_params column. By default `eventParams` are added based on the preset. You could add your custom event_params using `addEventParams` method.
* @param {String} [eventConfig[].eventParams.name] - The value of `key` in the event_params record.
* @param {String} [eventParams[].columnName] - Optional. The name of the column in the result table. If not provided the name will be the same as `eventParams.name`.
* @param {'string' | 'int' | 'double' | 'float' | 'coalesce' | 'coalesce_float'} [eventConfig[].eventParams.type] - Optional. The name of the value in the event_params column. By default `string`.
* @param {Object} [eventConfig[].userProperties] - List of user properties unnested from GA4 raw table user_properties column. By default `userProperties` are not added. You could add your custom user_properties using `addUserProperties` method.
* @param {String} [eventConfig[].userProperties.name] - The value of `key` in the user_properties record.
* @param {String} [eventConfig[].userProperties.columnName] - Optional. The name of the column in the result table. If not provided the name will be the same as `userProperties.name`.
* @param {'string' | 'int' | 'double' | 'float' | 'coalesce' | 'coalesce_float'} [eventConfig[].userProperties.type] - Optional. The name of the value in the event_params column. By default `string`.
* @param {Object} [eventConfig[].queryParameters] - List of query parameters from the unnested `event_params` column with the key `page_location`. You could add your custom query_parameters using `addQueryParameters` method.
* @param {String} [eventConfig[].queryParameters.name] - The query parameter name.
* @param {String} [eventConfig[].queryParameters.columnName] - Optional. The name of the column in the result table. If not provided the name will be the same as `queryParameters[].name`.
* @returns {Event[]} List of events
* @example
* ```js
* // Create events
* let events = ef.createEvents(configs);
* // Publish events
* events.forEach(event => event.publish());
* ```
*/
createEvents(eventConfigs) {