Skip to content

DSL style builders #2

@vshekar

Description

@vshekar

Once input data is validated, we need to convert the into sqlalchemy models, this can be done using the builder pattern.
For example:

class ExperimentTypeBuilder:
    def __init__(self, name: str, short_name: str):
        self.exp = ExperimentType(name=name, short_name=short_name)
        self.current_action = None

    def add_action(self, name: str, short_name: str):
        action = ActionType(
            name=name,
            short_name=short_name,
            order=len(self.exp.actions)
        )
        self.current_action = action
        return self

    def add_parameter(self, name: str, short_name: str, value_type: str, default_value: str = ""):
        param = ParameterType(
            name=name,
            short_name=short_name,
            value_type=value_type,
            default_value=default_value
        )
        self.current_action.parameters.append(param)
        return self

    def end_action(self):
        self.exp.actions.append(self.current_action)
        self.current_action = None
        return self

    def build(self):
        return self.exp

We can use the builder to map pydantic models to sqlalchemy models like so:

def map_schema_to_experiment_type(schema: ExperimentTypeSchema) -> ExperimentType:
    builder = ExperimentTypeBuilder(schema.name, schema.short_name)
    for action in schema.actions:
        builder.add_action(action.name, action.short_name)
        for param in action.parameters:
            builder.add_parameter(
                param.name,
                param.short_name,
                param.value_type,
                param.default_value
            )
        builder.end_action()
    return builder.build()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions