CYQ.Data 支持 PostgreSQL 數據庫

前言:

好久以前,就有同窗問我CYQ.Data能不能支持下PostgreSQL,以後小作了下調查,發現這個數據庫用的人少,加上各類因素,就一直沒動手。node

前兩天,不當心看了一下Github上的消息:mysql

看到這個問題又被從新提了出來了,因而,鬧吧!git

下面分享一下支持該數據庫要處理的過程,讓大夥明白CYQ.Data要支持一種新的數據庫,須要花多少功夫。github

一、找到數據庫的驅動程序:Npgsql.dll

網上查找了點相關知識,發現.NET 裏操做PostgreSQL有兩種提供的dll,一種是正規的收費的,另外一種是開源的Npgsql.dll,所以這裏選擇了開源的。sql

在Nuget上能夠搜索Npgsql,不過上面的版本要求依賴的版本很高,因而我找了最先的版本開始支持,畢竟CYQ.Data 是從支持最低2.0及以上的。數據庫

這裏是找到的下載低版本支持的網址:http://pgfoundry.org/frs/?group_id=1000140&release_id=1889oracle

同時,下載的兩個2.0和4.0兩個版本,也一併上傳到:https://github.com/cyq1162/cyqdata/tree/master/文檔框架

二、建立PostgreDal.cs,實現動態加載DLL

添加動態加載的代碼:ide

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Data.Common;
using CYQ.Data.Cache;
using System.IO;

namespace CYQ.Data
{
    internal class PostgreDal : DbBase
    {
        public PostgreDal(ConnObject co)
            : base(co)
        {

        }
        internal static Assembly GetAssembly()
        {
            object ass = CacheManage.LocalInstance.Get("Postgre_Assembly");
            if (ass == null)
            {
                try
                {
                    string name = string.Empty;
                    if (File.Exists(AppConst.RunFolderPath + "Npgsql.dll"))
                    {
                        name = "Npgsql";
                    }
                    else
                    {
                        name = "Can't find the Npgsql.dll";
                        Error.Throw(name);
                    }
                    ass = Assembly.Load(name);
                    CacheManage.LocalInstance.Set("Postgre_Assembly", ass, 10080);
                }
                catch (Exception err)
                {
                    string errMsg = err.Message;
                    Error.Throw(errMsg);
                }
            }
            return ass as Assembly;
        }
        protected override DbProviderFactory GetFactory(string providerName)
        {
            object factory = CacheManage.LocalInstance.Get("Postgre_Factory");
            if (factory == null)
            {
                Assembly ass = GetAssembly();
                factory = ass.GetType("Npgsql.NpgsqlFactory").GetField("Instance").GetValue(null);
               // factory = ass.CreateInstance("Npgsql.NpgsqlFactory.Instance");
                if (factory == null)
                {
                    throw new System.Exception("Can't Create  NpgsqlFactory in Npgsql.dll");
                }
                else
                {
                    CacheManage.LocalInstance.Set("Postgre_Factory", factory, 10080);
                }

            }
            return factory as DbProviderFactory;

        }

        protected override bool IsExistsDbName(string dbName)
        {
            try
            {
                IsAllowRecordSql = false;
                bool result = ExeScalar("select 1 from pg_catalog.pg_database where datname='" + dbName + "'", false) != null;
                IsAllowRecordSql = true;
                return result;
            }
            catch
            {
                return true;
            }
        }
        public override char Pre
        {
            get
            {
                return ':';
            }
        }
        public override void AddReturnPara()
        {

        }
    }
}

幾點說明:post

1、GetFactory方法,其它dll框架提供的都是直接實例化,而Npgsql.dll提供倒是單例屬性,因此代碼有點變化。
2、Npgsql操做參數化的符號是「:」號。

三、DalCreate.cs追加PostgreSql類型及數據庫連接解析

 

這裏重點發現postgresql和mssql二者的數據庫連接格式都一致:

server=...;uid=xxx;pwd=xxx;database=xxx;

所以從單純的語句上,根本沒法判斷從屬於哪一種數據庫。

通過小小的思考,解決方案出來了:

else
            {
                //postgre和mssql的連接語句同樣,這裏用database=和uid=順序來決定;database寫在後面的,爲postgre
                int dbIndex = connString.IndexOf("database=", StringComparison.OrdinalIgnoreCase);
                int uid = connString.IndexOf("uid=", StringComparison.OrdinalIgnoreCase);
                if (uid > 0 && uid < dbIndex && File.Exists(AppConfig.RunPath + "Npgsql.dll"))
                {
                    return PostgreClient;
                }
                return SqlClient;
            }

簡的說:只有知足引用了npgsql.dll以及database寫在uid以後兩種條件下,判斷爲postgresql,其它的都回歸到mssql。

四、處理表結構語句:獲取數據庫表以及表的結構語句:

這一塊花的時間比較多,網上也費了點時間查了很多資料,最後本身寫了語句:

獲取數據庫全部表:

internal static string GetPostgreTables(string dbName)
        {
            return string.Format("select table_name as TableName,cast(obj_description(relfilenode,'pg_class') as varchar) as Description from information_schema.tables t left join  pg_class p on t.table_name=p.relname  where table_schema='public' and table_catalog='{0}'", dbName);
        }

獲取某表的結構:

internal static string GetPostgreColumns()
        {
            return @"select
a.attname AS ColumnName,
case t.typname when 'int4' then 'int' when 'int8' then 'bigint' else t.typname end AS SqlType,
coalesce(character_maximum_length,numeric_precision,-1) as MaxSize,numeric_scale as Scale,
case a.attnotnull when 'true' then 0 else 1 end AS IsNullable,
case  when position('nextval' in column_default)>0 then 1 else 0 end as IsAutoIncrement, 
case when o.conname is null then 0 else 1 end as IsPrimaryKey,
d.description AS Description,
i.column_default as DefaultValue
from pg_class c 
left join pg_attribute a on c.oid=a.attrelid
left join pg_description d on a.attrelid=d.objoid AND a.attnum = d.objsubid
left join pg_type t on a.atttypid = t.oid
left join information_schema.columns i on i.table_schema='public' and i.table_name=c.relname and i.column_name=a.attname
left join pg_constraint o on a.attnum = o.conkey[1] and o.contype='p'
where c.relname =:TableName
and a.attnum > 0 and a.atttypid>0
ORDER BY a.attnum";
        }

五、處理關鍵字符號

因爲PostgreSQL的大小寫敏感,並且關鍵字加須要用雙引號包含(這點和SQLite一致):

這裏在原有的基礎上加上case便可。

六、處理差別化的SQL語句:SqlCreate.cs

A、獲取插入後的自增值,這裏能夠借用一下自增列產生的默認值:

這裏用默認值,替換一下nextval序列爲currval序列便可。

 else if (_action.dalHelper.dalType == DalType.PostgreSQL)
                        {
                            string key = Convert.ToString(primaryCell.Struct.DefaultValue);
                            if (!string.IsNullOrEmpty(key))
                            {
                                key = key.Replace("nextval", "currval");
                                sql = sql + "; select " + key + " as OutPutValue";
                            }
                        }

 B、須要引用關鍵字的地方:

略。。。。

七、處理分頁語句:SqlCreateForPager.cs

這裏PostgreSQL和分頁和sqlite及mysql是一致的,所以只要在相關的地方補上case便可:

public static string GetSql(DalType dalType, string version, int pageIndex, int pageSize, object objWhere, string tableName, int rowCount, string columns, string primaryKey, bool primaryKeyIsIdentity)
        {
            if (string.IsNullOrEmpty(columns))
            {
                columns = "*";
            }
            pageIndex = pageIndex == 0 ? 1 : pageIndex;
            string where = SqlFormat.GetIFieldSql(objWhere);
            if (string.IsNullOrEmpty(where))
            {
                where = "1=1";
            }
            if (pageSize == 0)
            {
                return string.Format(top1Pager, columns, tableName, where);
            }
            if (rowCount > 0)//分頁查詢。
            {
                where = SqlCreate.AddOrderBy(where, primaryKey);
            }
            int topN = pageIndex * pageSize;//Top N 最大數
            int max = (pageIndex - 1) * pageSize;
            int rowStart = (pageIndex - 1) * pageSize + 1;
            int rowEnd = rowStart + pageSize - 1;
            string orderBy = string.Empty;
            if (pageIndex == 1 && dalType != DalType.Oracle)//第一頁(oracle時 rownum 在排序條件爲非數字時,和row_number()的不同,會致使結果差別,因此分頁統一用row_number()。)
            {
                switch (dalType)
                {
                    case DalType.Access:
                    case DalType.MsSql:
                    case DalType.Sybase:
                        return string.Format(top1Pager, "top " + pageSize + " " + columns, tableName, where);
                    //case DalType.Oracle:
                    //    return string.Format(top1Pager, columns, tableName, "rownum<=" + pageSize + " and " + where);
                    case DalType.SQLite:
                    case DalType.MySql:
                    case DalType.PostgreSQL:
                        return string.Format(top1Pager, columns, tableName, where + " limit " + pageSize);
                }
            }
            else
            {

                switch (dalType)
                {
                    case DalType.Access:
                    case DalType.MsSql:
                    case DalType.Sybase:
                        int leftNum = rowCount % pageSize;
                        int pageCount = leftNum == 0 ? rowCount / pageSize : rowCount / pageSize + 1;//頁數
                        if (pageIndex == pageCount && dalType != DalType.Sybase) // 最後一頁Sybase 不支持雙Top order by
                        {
                            return string.Format(top2Pager, pageSize+" "+columns, "top " + (leftNum == 0 ? pageSize : leftNum) + " * ", tableName, ReverseOrderBy(where, primaryKey), GetOrderBy(where, false, primaryKey));//反序
                        }
                        if ((pageCount > 1000 || rowCount > 100000) && pageIndex > pageCount / 2) // 頁數事後半段,反轉查詢
                        {
                            orderBy = GetOrderBy(where, false, primaryKey);
                            where = ReverseOrderBy(where, primaryKey);//事先反轉一次。
                            topN = rowCount - max;//取後面的
                            int rowStartTemp = rowCount - rowEnd;
                            rowEnd = rowCount - rowStart;
                            rowStart = rowStartTemp;
                        }
                        break;

                }
            }


            switch (dalType)
            {
                case DalType.MsSql:
                case DalType.Oracle:
                    if (version.StartsWith("08"))
                    {
                        goto temtable;
                        // goto top3;//sql 2000
                    }
                    int index = tableName.LastIndexOf(')');
                    if (index > 0)
                    {
                        tableName = tableName.Substring(0, index + 1);
                    }
                    string v = dalType == DalType.Oracle ? "" : " v";
                    string onlyWhere = "where " + SqlCreate.RemoveOrderBy(where);
                    onlyWhere = SqlFormat.RemoveWhereOneEqualsOne(onlyWhere);
                    return string.Format(rowNumberPager, GetOrderBy(where, false, primaryKey), (columns == "*" ? "t.*" : columns), tableName, onlyWhere, v, rowStart, rowEnd);
                case DalType.Sybase:
                temtable:
                    if (primaryKeyIsIdentity)
                    {
                        bool isOk = columns == "*";
                        if (!isOk)
                        {
                            string kv = SqlFormat.NotKeyword(primaryKey);
                            string[] items = columns.Split(',');
                            foreach (string item in items)
                            {
                                if (string.Compare(SqlFormat.NotKeyword(item), kv, StringComparison.OrdinalIgnoreCase) == 0)
                                {
                                    isOk = true;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            columns = "t.*";
                            index = tableName.LastIndexOf(')');
                            if (index > 0)
                            {
                                tableName = tableName.Substring(0, index + 1);
                            }
                            tableName += " t ";
                        }
                        if (isOk)
                        {

                            return string.Format(tempTablePagerWithIdentity, DateTime.Now.Millisecond, topN, primaryKey, tableName, where, pageSize, columns, rowStart, rowEnd, orderBy);
                        }
                    }
                    return string.Format(tempTablePager, DateTime.Now.Millisecond, pageIndex * pageSize + " " + columns, tableName, where, pageSize, rowStart, rowEnd, orderBy);
                case DalType.Access:
                top3:
                    if (!string.IsNullOrEmpty(orderBy)) // 反轉查詢
                    {
                        return string.Format(top4Pager,columns, (rowCount - max > pageSize ? pageSize : rowCount - max), topN, tableName, where, GetOrderBy(where, true, primaryKey), GetOrderBy(where, false, primaryKey), orderBy);
                    }
                    return string.Format(top3Pager, (rowCount - max > pageSize ? pageSize : rowCount - max),columns, topN, tableName, where, GetOrderBy(where, true, primaryKey), GetOrderBy(where, false, primaryKey));
                case DalType.SQLite:
                case DalType.MySql:
                case DalType.PostgreSQL:
                    if (max > 500000 && primaryKeyIsIdentity && Convert.ToString(objWhere) == "" && !tableName.Contains(" "))//單表大數量時的優化成主鍵訪問。
                    {
                        where = string.Format("{0}>=(select {0} from {1} limit {2}, 1) limit {3}", primaryKey, tableName, max, pageSize);
                        return string.Format(top1Pager, columns, tableName, where);
                    }
                    return string.Format(top1Pager, columns, tableName, where + " limit " + pageSize + " offset " + max);
            }
            return (string)Error.Throw("Pager::No Be Support:" + dalType.ToString());
        }

總結:

一個數據庫的基本支持、寫到這裏就完成了增刪改查及分頁。

固然,對於CYQ.Data而言,還差一些未處理:

一、多種數據庫轉換互通處理:DataType.cs。

二、對錶的建立修改操做:SqlCreateForSchema.cs。

三、支持多數據庫兼容性寫法:SqlCompatible.cs。

四、其它細節。

相關文章
相關標籤/搜索