1+ import ProgressBar from 'progress' ;
2+ import config from '../config' ;
3+ import { PoolClient } from 'pg' ;
4+
5+ const batchSize = 10000 ;
6+
7+ async function run ( ) : Promise < void > {
8+ const pool = await config . pg ( ) ;
9+
10+ const client = await pool . connect ( ) ;
11+ try {
12+ // Fetch all product hashes
13+ config . logger . info ( 'Fetching all product hashes' ) ;
14+ const productHashes = await getProductHashes ( client ) ;
15+
16+ const progressBar = new ProgressBar (
17+ '-> loading [:bar] :percent (:etas remaining)' ,
18+ {
19+ width : 40 ,
20+ complete : '=' ,
21+ incomplete : ' ' ,
22+ renderThrottle : 500 ,
23+ total : productHashes . length ,
24+ }
25+ ) ;
26+
27+ // For each product hash, insert by batch the emissions data into the product table
28+ config . logger . info ( 'Updating product emissions' ) ;
29+ for ( let i = 0 ; i < productHashes . length ; i += batchSize ) {
30+ const batch = productHashes . slice ( i , i + batchSize ) ;
31+
32+ await client . query ( 'BEGIN' ) ;
33+
34+ await Promise . all ( batch . map ( ( productHash ) => {
35+ updateProductEmissions ( client , productHash ) ;
36+ progressBar . tick ( ) ;
37+ } ) ) ;
38+
39+ await client . query ( 'COMMIT' ) ;
40+ }
41+
42+ // await setEmissionsUpdateSuccessful(client);
43+ } catch ( e ) {
44+ await client . query ( 'ROLLBACK' ) ;
45+
46+ // await setEmissionsUpdateFailed(client);
47+
48+ throw e ;
49+ }
50+
51+ }
52+
53+ async function getProductHashes ( client : PoolClient ) : Promise < string [ ] > {
54+ const result = await client . query (
55+ `
56+ SELECT "productHash"
57+ FROM "products"
58+ `
59+ ) ;
60+
61+ return result . rows . map ( ( row ) => row . productHash ) ;
62+ }
63+
64+ async function updateProductEmissions ( client : PoolClient , productHash : string ) : Promise < void > {
65+ const emissionsData = generateEmissionsData ( ) ;
66+ await client . query (
67+ `
68+ UPDATE "products"
69+ SET "emissions" = $1
70+ WHERE "productHash" = $2
71+ ` ,
72+ [ emissionsData , productHash ]
73+ ) ;
74+ }
75+
76+ const generateEmissionsData = ( ) => {
77+ return JSON . stringify ( [ {
78+ emissionHash : 'SampleEmissionHash' ,
79+ unit : 'kgeqCO2' ,
80+ CO2e : Math . random ( ) * 100 ,
81+ effectiveDateStart : '2020-01-01' ,
82+ effectiveDateEnd : '2024-12-31' ,
83+ startUsageAmount : 0 ,
84+ endUsageAmount : 100 ,
85+ description : 'Sample Description' ,
86+ } ] ) ;
87+ } ;
88+
89+ config . logger . info ( 'Starting: loading data into DB' ) ;
90+ run ( )
91+ . then ( ( ) => {
92+ config . logger . info ( 'Completed: loading data into DB' ) ;
93+ process . exit ( 0 ) ;
94+ } )
95+ . catch ( ( err ) => {
96+ config . logger . error ( err ) ;
97+ process . exit ( 1 ) ;
98+ } ) ;
0 commit comments