Imports DevExpress.Xpo.DB
Imports DevExpress.Xpo.DB.Helpers
Imports DevExpress.Data.Filtering
Imports System.Globalization


Public Class PostgreSqlConnectionProviderEx
    Inherits PostgreSqlConnectionProvider
    Public Shadows Const XpoProviderTypeString As String = "PostgresEx"

    Public Shared Shadows Function GetConnectionString(ByVal server As String, ByVal userid As String, ByVal password As String, ByVal database As String) As String
        Return String.Format("{4}={5};Server={0};User Id={1};Password={2};Database={3};Encoding=UNICODE;", server,
        userid, password, database, DataStoreBase.XpoProviderTypeParameterName, XpoProviderTypeString)
    End Function

    Public Shared Shadows Function GetConnectionString(ByVal server As String, ByVal port As Integer, ByVal userid As String, ByVal password As String, ByVal database As String) As String
        Return String.Format("{5}={6};Server={0};User Id={1};Password={2};Database={3};Encoding=UNICODE;Port={4}", _
        server, userid, password, database, port, DataStoreBase.XpoProviderTypeParameterName, _
        XpoProviderTypeString)
    End Function

    Public Shared Shadows Sub Register()
    End Sub

    Shared Sub New()
        RegisterDataStoreProvider(XpoProviderTypeString, New DataStoreCreationFromStringDelegate(AddressOf CreateProviderFromString))
    End Sub

    Public Shared Shadows Function CreateProviderFromString(ByVal connectionString As String, ByVal autoCreateOption As AutoCreateOption, _
                                                            <System.Runtime.InteropServices.Out()> ByRef objectsToDisposeOnDisconnect() As IDisposable) As IDataStore
        Dim connection As IDbConnection = New Npgsql.NpgsqlConnection(connectionString)
        objectsToDisposeOnDisconnect = New IDisposable() {connection}
        Return CreateProviderFromConnection(connection, autoCreateOption)
    End Function

    Public Shared Shadows Function CreateProviderFromConnection(ByVal connection As IDbConnection,
ByVal autoCreateOption As AutoCreateOption) As IDataStore
        Return New PostgreSqlConnectionProviderEx(connection, autoCreateOption)
    End Function

    Public Sub New(ByVal connection As IDbConnection, ByVal autoCreateOption As AutoCreateOption)
        MyBase.New(connection, autoCreateOption)
    End Sub

    Public Overrides Function FormatBinary(ByVal operatorType As BinaryOperatorType, ByVal leftOperand As String, ByVal rightOperand As String) As String
        Select Case operatorType
            Case BinaryOperatorType.Like
                Return String.Format(CultureInfo.InvariantCulture, "{0} ilike {1}", leftOperand, rightOperand)
            Case Else
                Return MyBase.FormatBinary(operatorType, leftOperand, rightOperand)
        End Select
    End Function
End Class