<commit_before>﻿namespace FSharp.Data.Sql.Providers

open System
open System.Collections.Generic
open System.Data
open System.Reflection
open FSharp.Data.Sql
open FSharp.Data.Sql.Schema
open FSharp.Data.Sql.Common

module PostgreSQL = 
    
    let mutable resolutionPath = String.Empty
    let mutable owner = "public"
    let mutable referencedAssemblies = [||]

    let assemblyNames = [
        "Npgsql.dll"
    ]

    let assembly =
        lazy Reflection.tryLoadAssemblyFrom resolutionPath referencedAssemblies assemblyNames
    
    let findType name = 
        match assembly.Value with
        | Some(assembly) -> assembly.GetTypes() |> Array.find(fun t -> t.Name = name)
        | None -> failwithf "Unable to resolve postgresql assemblies. One of %s must exist in the resolution path" (String.Join(", ", assemblyNames |> List.toArray))

   
    let connectionType = lazy (findType "NpgsqlConnection")
    let commandType = lazy    (findType  "NpgsqlCommand")
    let parameterType = lazy  (findType "NpgsqlParameter")
    let dbType =  lazy (findType "NpgsqlDbType")
    let transactionType = lazy (findType "NpgsqlTransaction")
    let getSchemaMethod = lazy (connectionType.Value.GetMethod("GetSchema",[|typeof<string>|]))

    let getBeginTransactionMethod = lazy (connectionType.Value.GetMethod("BeginTransaction",[||]))

    let getEndTransactionMethod = lazy (transactionType.Value.GetMethod("Commit", [||]))

    let beginTransaction conn = getBeginTransactionMethod.Value.Invoke(conn, [||])

    let endTransaction tran = getEndTransactionMethod.Value.Invoke(tran, [||])

    let createConnection connectionString = 
        Activator.CreateInstance(connectionType.Value,[|box connectionString|]) :?> IDbConnection

    let connect (con:IDbConnection) f =
        if con.State <> ConnectionState.Open then con.Open()
        let result = f con
        con.Close(); result

    let getSchema name (args:string[]) conn = 
        getSchemaMethod.Value.Invoke(conn,[|name|]) :?> DataTable

    let mapTypeToClrType (sqlType:string) =
            match sqlType.ToLower() with
            | "bigint"
            | "int8"       -> Some typeof<Int64>
            | "bit"           // Doesn't seem to correspond to correct type - fixed-length bit string (Npgsql.BitString)
            | "varbit"        // Doesn't seem to correspond to correct type - variable-length bit string (Npgsql.BitString)
            | "boolean"
            | "bool"       -> Some typeof<Boolean>
            | "box"
            | "circle"
            | "line"
            | "lseg"
            | "path"
            | "point"
            | "polygon"    -> Some typeof<Object>
            | "bytea"      -> Some typeof<Byte[]>
            | "double"
            | "float8"     -> Some typeof<Double>
            | "integer"
            | "int"
            | "int4"       -> Some typeof<Int32>
            | "money"
            | "numeric"    -> Some typeof<Decimal>
            | "real"
            | "float4"     -> Some typeof<Single>
            | "smallint"
            | "int2"       -> Some typeof<Int16>
            | "text"       -> Some typeof<String>
            | "date"
            | "time"
            | "timetz"
            | "timestamp"
            | "timestamptz"-> Some typeof<DateTime>
            | "interval"   -> Some typeof<TimeSpan>
            | "character"
            | "varchar"    -> Some typeof<String>
            | "inet"       -> Some typeof<System.Net.IPAddress>
            | "uuid"       -> Some typeof<Guid>
            | "xml"        -> Some typeof<String>
            | _ -> None

    let getDbType(providerType) =
        try
            let parameterType = parameterType.Value
            let p = Activator.CreateInstance(parameterType,[||]) :?> IDbDataParameter
            let npgDbTypeSetter = parameterType.GetProperty("NpgsqlDbType").GetSetMethod()
            let dbTypeGetter = parameterType.GetProperty("DbType").GetGetMethod()
            npgDbTypeSetter.Invoke(p, [|providerType|]) |> ignore
            dbTypeGetter.Invoke(p, [||]) :?> DbType
        with _ -> DbType.Object //Weird cant cast Line to any DbType exception

    let mutable typeMappings = []
    let mutable findClrType : (string -> TypeMapping option)  = fun _ -> failwith "!"
    let mutable findDbType : (string -> TypeMapping option)  = fun _ -> failwith "!"

    let createTypeMappings() = 
        let typ = dbType.Value
        let mappings =
            [
                for v in Enum.GetValues(typ) do
                    let name = Enum.GetName(typ, v).ToLower()
                    match (mapTypeToClrType name) with
                    | Some(t) -> yield { ProviderTypeName = Some name; ClrType = t.ToString(); DbType = (getDbType v); ProviderType = Some (v :?> int);}
                    | None -> ()
                yield { ProviderTypeName = Some "character varying"; ClrType = (typeof<string>).ToString(); DbType = DbType.String; ProviderType = Some 22; }
                yield { ProviderTypeName = Some "refcursor"; ClrType = (typeof<SqlEntity[]>).ToString(); DbType = DbType.Object; ProviderType = None; }
                yield { ProviderTypeName = Some "SETOF refcursor"; ClrType = (typeof<SqlEntity[]>).ToString(); DbType = DbType.Object; ProviderType = None; }
            ]

        let clrMappings =
            mappings
            |> List.map (fun m -> m.ClrType, m)
            |> Map.ofList

        let dbMappings = 
            mappings
            |> List.map (fun m -> m.ProviderTypeName.Value, m)
            |> Map.ofList
            
        typeMappings <- mappings
        findClrType <- clrMappings.TryFind
        findDbType <- dbMappings.TryFind

    let createCommand commandText connection = 
        Activator.CreateInstance(commandType.Value,[|box commandText;box connection|]) :?> IDbCommand
<commit_msg>Adjust PSQL mapping of DateTime so it maps to Date<commit_after>﻿namespace FSharp.Data.Sql.Providers

open System
open System.Collections.Generic
open System.Data
open System.Reflection
open FSharp.Data.Sql
open FSharp.Data.Sql.Schema
open FSharp.Data.Sql.Common

module PostgreSQL = 
    
    let mutable resolutionPath = String.Empty
    let mutable owner = "public"
    let mutable referencedAssemblies = [||]

    let assemblyNames = [
        "Npgsql.dll"
    ]

    let assembly =
        lazy Reflection.tryLoadAssemblyFrom resolutionPath referencedAssemblies assemblyNames
    
    let findType name = 
        match assembly.Value with
        | Some(assembly) -> assembly.GetTypes() |> Array.find(fun t -> t.Name = name)
        | None -> failwithf "Unable to resolve postgresql assemblies. One of %s must exist in the resolution path" (String.Join(", ", assemblyNames |> List.toArray))

   
    let connectionType = lazy (findType "NpgsqlConnection")
    let commandType = lazy    (findType  "NpgsqlCommand")
    let parameterType = lazy  (findType "NpgsqlParameter")
    let dbType =  lazy (findType "NpgsqlDbType")
    let transactionType = lazy (findType "NpgsqlTransaction")
    let getSchemaMethod = lazy (connectionType.Value.GetMethod("GetSchema",[|typeof<string>|]))

    let getBeginTransactionMethod = lazy (connectionType.Value.GetMethod("BeginTransaction",[||]))

    let getEndTransactionMethod = lazy (transactionType.Value.GetMethod("Commit", [||]))

    let beginTransaction conn = getBeginTransactionMethod.Value.Invoke(conn, [||])

    let endTransaction tran = getEndTransactionMethod.Value.Invoke(tran, [||])

    let createConnection connectionString = 
        Activator.CreateInstance(connectionType.Value,[|box connectionString|]) :?> IDbConnection

    let connect (con:IDbConnection) f =
        if con.State <> ConnectionState.Open then con.Open()
        let result = f con
        con.Close(); result

    let getSchema name (args:string[]) conn = 
        getSchemaMethod.Value.Invoke(conn,[|name|]) :?> DataTable

    let mapTypeToClrType (sqlType:string) =
            match sqlType.ToLower() with
            | "bigint"
            | "int8"       -> Some typeof<Int64>
            | "bit"           // Doesn't seem to correspond to correct type - fixed-length bit string (Npgsql.BitString)
            | "varbit"        // Doesn't seem to correspond to correct type - variable-length bit string (Npgsql.BitString)
            | "boolean"
            | "bool"       -> Some typeof<Boolean>
            | "box"
            | "circle"
            | "line"
            | "lseg"
            | "path"
            | "point"
            | "polygon"    -> Some typeof<Object>
            | "bytea"      -> Some typeof<Byte[]>
            | "double"
            | "float8"     -> Some typeof<Double>
            | "integer"
            | "int"
            | "int4"       -> Some typeof<Int32>
            | "money"
            | "numeric"    -> Some typeof<Decimal>
            | "real"
            | "float4"     -> Some typeof<Single>
            | "smallint"
            | "int2"       -> Some typeof<Int16>
            | "text"       -> Some typeof<String>
            | "date"
            | "time"
            | "timetz"
            | "timestamp"
            | "timestamptz"-> Some typeof<DateTime>
            | "interval"   -> Some typeof<TimeSpan>
            | "character"
            | "varchar"    -> Some typeof<String>
            | "inet"       -> Some typeof<System.Net.IPAddress>
            | "uuid"       -> Some typeof<Guid>
            | "xml"        -> Some typeof<String>
            | _ -> None

    let getDbType(providerType) =
        try
            let parameterType = parameterType.Value
            let p = Activator.CreateInstance(parameterType,[||]) :?> IDbDataParameter
            let npgDbTypeSetter = parameterType.GetProperty("NpgsqlDbType").GetSetMethod()
            let dbTypeGetter = parameterType.GetProperty("DbType").GetGetMethod()
            npgDbTypeSetter.Invoke(p, [|providerType|]) |> ignore
            dbTypeGetter.Invoke(p, [||]) :?> DbType
        with _ -> DbType.Object //Weird cant cast Line to any DbType exception

    let mutable typeMappings = []
    let mutable findClrType : (string -> TypeMapping option)  = fun _ -> failwith "!"
    let mutable findDbType : (string -> TypeMapping option)  = fun _ -> failwith "!"

    let createTypeMappings() = 
        let typ = dbType.Value
        let mappings =
            [
                for v in Enum.GetValues(typ) do
                    let name = Enum.GetName(typ, v).ToLower()
                    match (mapTypeToClrType name) with
                    | Some(t) -> yield { ProviderTypeName = Some name; ClrType = t.ToString(); DbType = (getDbType v); ProviderType = Some (v :?> int);}
                    | None -> ()
                yield { ProviderTypeName = Some "character varying"; ClrType = (typeof<string>).ToString(); DbType = DbType.String; ProviderType = Some 22; }
                yield { ProviderTypeName = Some "refcursor"; ClrType = (typeof<SqlEntity[]>).ToString(); DbType = DbType.Object; ProviderType = None; }
                yield { ProviderTypeName = Some "SETOF refcursor"; ClrType = (typeof<SqlEntity[]>).ToString(); DbType = DbType.Object; ProviderType = None; }
            ]

        let adjustments = 
            [(typeof<System.DateTime>.ToString(),System.Data.DbType.Date) ] 
            |> List.map (fun (``type``,dbType) -> ``type``,mappings |> List.find (fun mp -> mp.ClrType = ``type`` && mp.DbType = dbType))

        let clrMappings =
            mappings
            |> List.map (fun m -> m.ClrType, m)
            |> (fun tys -> List.append tys adjustments)
            |> Map.ofList

        let dbMappings = 
            mappings
            |> List.map (fun m -> m.ProviderTypeName.Value, m)
            |> Map.ofList
            
        typeMappings <- mappings
        findClrType <- clrMappings.TryFind
        findDbType <- dbMappings.TryFind

    let createCommand commandText connection = 
        Activator.CreateInstance(commandType.Value,[|box commandText;box connection|]) :?> IDbCommand

{'fraction_non_alphanumeric': 0.1156530408773679, 'fraction_numerical': 0.002160186108341642, 'mean_word_length': 2.113554061045008, 'pattern_counts': {'":': 0, '<': 52, '<?xml version=': 0, '>': 136, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4028074', 'n_tokens_mistral': 3496, 'n_tokens_neox': 3317, 'n_words': 810}