Skip to content

Custom conversions

Jacek edited this page Jan 30, 2019 · 9 revisions

SqlFun allows to intercept parameter creation. That is the moment conversions are applied.
Firstly, the parameter builder function must be defined:

    let myParamBuilder (defaultPB: ParamBuilder) (prefix: string) (name: string) (expr: Expression) (names: string list) = 
        if expr.Type |> meetsSomeCriteria
        then
            [
                prefix + name,
                expr,
                fun value (command: IDbCommand) ->
                    let param = new SqlClient.SqlParameter()
                    param.ParameterName <- "@" + name
                    if value <> null then
                        param.Value <- performTypeConversion (value)
                    command.Parameters.Add(param)
                ,
                getDefaultValue expr.Type 
            ]
        else
            defaultPB prefix name expr names

Then, instead of default paramBuilder, the composition with custom one should be used in configuration code:

    let createConnection () = new SqlConnection(connectionString)

    let generatorConfig = 
        let defaultConfig = GeneratorConfig.Default createConnection
        { defaultConfig with paramBuilder = myParamBuilder <+> defaultConfig.paramBuilder }
    
    let sql commandText = sql generatorConfig commandText

    let proc name = proc generatorConfig name

    let buildQuery ctx = FinalQueryPart(ctx, generatorConfig, string)