コード例 #1
0
        internal static IntPtr SetupPGConn(PqsqlConnectionStringBuilder connStringBuilder, out ConnStatusType connStatus, out PGTransactionStatusType tranStatus)
        {
#if CODECONTRACTS
            Contract.Requires <ArgumentNullException>(connStringBuilder != null);
#else
            if (connStringBuilder == null)
            {
                throw new ArgumentNullException(nameof(connStringBuilder));
            }
#endif

            // setup null-terminated key-value arrays for the connection
            string[] keys = new string[connStringBuilder.Keys.Count + 1];
            string[] vals = new string[connStringBuilder.Values.Count + 1];

            // get keys and values from PqsqlConnectionStringBuilder
            connStringBuilder.Keys.CopyTo(keys, 0);
            connStringBuilder.Values.CopyTo(vals, 0);

            // now create connection
            IntPtr conn = PqsqlWrapper.PQconnectdbParams(keys, vals, 0);

            if (conn == IntPtr.Zero)
            {
                connStatus = ConnStatusType.CONNECTION_BAD;
                tranStatus = PGTransactionStatusType.PQTRANS_UNKNOWN;
                return(conn);
            }

            // always force client_encoding to utf8
            int client_encoding = PqsqlWrapper.PQclientEncoding(conn);

            if (client_encoding == (int)PgEnc.PG_UTF8)              // done
            {
                connStatus = PqsqlWrapper.PQstatus(conn);
                tranStatus = PqsqlWrapper.PQtransactionStatus(conn);
            }
            else if (client_encoding == -1)             // bail out, but keep connection object
            {
                connStatus = ConnStatusType.CONNECTION_BAD;
                tranStatus = PGTransactionStatusType.PQTRANS_UNKNOWN;
            }
            else                                                                    // try to set client_encoding to utf8
            {
                if (PqsqlWrapper.PQsetClientEncoding(conn, PgEncName.PG_UTF8) == 0) // success
                {
                    connStatus = PqsqlWrapper.PQstatus(conn);
                    tranStatus = PqsqlWrapper.PQtransactionStatus(conn);
                }
                else                 // bail out, but keep connection object
                {
                    connStatus = ConnStatusType.CONNECTION_BAD;
                    tranStatus = PGTransactionStatusType.PQTRANS_UNKNOWN;
                }
            }

            return(conn);
        }