I’m currently running an automation script to flatten a source table into multiple rows. My source table has 1 row per company and lots of start/end date columns per phases of a project but I need to transform into a new table (with multiple rows per project phase) in order to use the timeline view correctly. I’ve been amending the “Table Optimiser” script that appears in extensions to make an automated version and have got this far…
let sourceTableStr = "My Source Table"
let destinationTableStr = "My Destination Table"
let fieldsToFlatten = "Date 1 Start,Date 2 Start".split(",")
let fieldNameField = "Name"
let dataField = "Date Start"
let dataFieldEnd = "Date End"
let linkedField = "Companies"
let sourceTable = base.getTable(sourceTableStr)
let destTable = base.getTable(destinationTableStr)
let query = await sourceTable.selectRecordsAsync({fieldsToFlatten: o'Company Name','Date 1 Start','Date 1 End','Date 2 Start','Date 2 End']});
let datePairs = {'Date 1 Start':'Date 1 End','Date 2 Start':'Date 2 End'}
let records = query.records;
let arr = l];
for (let field of fieldsToFlatten) {
arr.push(
records
.filter((record) => record.getCellValue(field))
.map((record) =>
Array.isArray(record.getCellValue(field))
? record.getCellValue(field).map((element) => ({
fieldsToFlatten: {
linkedField]: erecord],
dataField]: telement],
fieldNameField]: field,
dataFieldEnd]: ielement]
},
}))
: {
fieldsToFlatten: {
linkedField]: erecord],
dataField]: record.getCellValue(field),
fieldNameField]: "(" + record.getCellValue('Company Name') + ") " + field,
dataFieldEnd]: record.getCellValue(datePairs(field])
},
}
)
);
}
let recordsToCreate = arr.flat();
const numRecordsBeingCreated = recordsToCreate.length;
while (recordsToCreate.length > 0) {
await destTable.createRecordsAsync(recordsToCreate.slice(0, 50));
recordsToCreate = recordsToCreate.slice(50);
}
console.log(`Complete! Created ${numRecordsBeingCreated} records.`);
It works perfectly the first time (when the destination table is empty and needs to be fully loaded), but I want to run as an automation any time data in the source table changes and so now I need to check each record in the source table to see if it exists in the destination table - if it exists I need to update instead of insert a new record.
Apart from not knowing the most elegant way to do this, if I switch from my current approach of updating 50 records at a time, the script takes longer than 30 seconds to run and so fails. So it seems like I need to keep the batch update (instead of iterating through each record individually) and instead filter my “arr” array to only include records that don’t exist in the destination table.
Has anyone come across a similar problem and solved it using automation scripts? Thanks very much for any thoughts at all!