[COMPASS-5685] Add Variable Declarations to BSON Transpiler Created: 04/Apr/22  Updated: 29/Oct/23  Resolved: 17/May/22

Status: Closed
Project: Compass
Component/s: Export to Language
Affects Version/s: None
Fix Version/s: 1.31.3

Type: Task Priority: Major - P3
Reporter: Preston Vasquez Assignee: Unassigned
Resolution: Fixed Votes: 1
Labels: go-driver
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Related
Documentation Changes: Not Needed

 Description   

Request

Explore adding a variable declarations template to the BSON Transpiler templates. 

ObjectIdSymbolDeclarationsTemplate: &ObjectIdSymbolDeclarationsTemplate null 

Motivation

Go handles some functionality by returning both a value as well as any error encountered while parsing the value.  For example, when trying to parse an objectID from hex, you would handle errors inline

objectID, err := primitive.ObjectIDFromHex("5ab901c29ee65f5c8550c5b9")
if err != nil {
	log.Fatal(err)
}
 
// use objectID for something

While this follows the "go way" of error-handling, the `ObjectIdSymbolArgsTemplate`, for example, expects only functionality that will return an object id alone.  This requires the go templates to use closures to handle errors that might occur at runtime

// This would be embedded in some CRUD Operation
// and is what would be transpiled from 
// { _id: ObjectID("5ab901c29ee65f5c8550c5b9") }
bson.D{{"_id", func(hex string) primitive.ObjectID {
	objectID, err := primitive.ObjectIDFromHex(hex)
	if err != nil {
		log.Fatal(err)
	}
	return objectID
}("5ab901c29ee65f5c8550c5b9")}}

This does not look very natural and could be a source of confusion for go developers trying to export code.

Proposal

The closure method may possibly be avoided by adding the new template `ObjectIdSymbolDeclarationsTemplate` where variables are declared to be used within the args template 

ObjectIdSymbolDeclarationsTemplate: &ObjectIdSymbolDeclarationsTemplate !!js/function >
    (arg, count) => {
        return `objectID${count}, err := primitive.ObjectIDFromHex(${arg})
        if err != nil {
            log.Fatal(err)
        }`
    }
ObjectIdSymbolArgsTemplate: &ObjectIdSymbolArgsTemplate !!js/function >
    (_, count) => {
        return `objectID${count}`
    }

This would be transpiled into the following 

objectID1, err := primitive.ObjectIDFromHex("5ab901c29ee65f5c8550c5b9")
if err != nil {
	log.Fatal(err)
}
 
// this would be embedded in some CRUD Operation
bson.D{{"_id", objectID1}} 


Generated at Wed Feb 07 22:40:27 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.