Ejemplo n.º 1
0
 internal static void CheckAndCreateOracleSequence(string seqName, string conn, string primaryKey, string tableName)
 {
     seqName = seqName.ToUpper();
     using (DbBase db = DalCreate.CreateDal(conn))
     {
         object o = db.ExeScalar(string.Format(TableSchema.ExistOracleSequence, seqName), false);
         if (o == null || Convert.ToString(o) == "0")
         {
             int startWith = 1;
             if (!string.IsNullOrEmpty(primaryKey))
             {
                 o = db.ExeScalar(string.Format(TableSchema.GetOracleMaxID, primaryKey, tableName), false);
                 if (!int.TryParse(Convert.ToString(o), out startWith) || startWith < 1)
                 {
                     startWith = 1;
                 }
                 else
                 {
                     startWith++;
                 }
             }
             db.ExeNonQuery(string.Format(TableSchema.CreateOracleSequence, seqName, startWith), false);
         }
     }
 }
Ejemplo n.º 2
0
 internal static void CreateSelectBaseProc(DalType dal, string conn)
 {
     try
     {
         switch (dal)
         {
         //case DalType.Oracle:
         //    if (!flag.Contains("oracle"))
         //    {
         //        flag.Add("oracle");
         //        using (DbBase db = DalCreate.CreateDal(conn))
         //        {
         //            db.AllowRecordSql = false;
         //            object o = db.ExeScalar(string.Format(ExistOracle.Replace("TABLE", "PROCEDURE"), "MyPackage.SelectBase"), false);
         //            if (o != null && Convert.ToInt32(o) < 1)
         //            {
         //                db.ExeNonQuery(SqlPager.GetPackageHeadForOracle(), false);
         //                db.ExeNonQuery(SqlPager.GetPackageBodyForOracle(), false);
         //            }
         //        }
         //    }
         //    break;
         case DalType.MsSql:
             if (!flag.Contains("sql"))
             {
                 flag.Add("sql");    //考虑到一个应用不太可能同时使用mssql的不同版本,只使用一个标识。
                 using (DbBase db = DalCreate.CreateDal(conn))
                 {
                     db.IsAllowRecordSql = false;
                     object o = null;
                     if (!db.Version.StartsWith("08"))
                     {
                         //    o = db.ExeScalar(string.Format(Exist2000.Replace("U", "P"), "SelectBase"), false);
                         //    if (o != null && Convert.ToInt32(o) < 1)
                         //    {
                         //        db.ExeNonQuery(SqlPager.GetSelectBaseForSql2000(), false);
                         //    }
                         //}
                         //else
                         //{
                         o = db.ExeScalar(string.Format(TableSchema.Exist2005, "SelectBase", "P"), false);
                         if (o != null && Convert.ToInt32(o) < 1)
                         {
                             db.ExeNonQuery(SqlCreateForPager.GetSelectBaseForSql2005(), false);
                         }
                     }
                 }
             }
             break;
         }
     }
     catch (Exception err)
     {
         Log.WriteLogToTxt(err);
     }
 }
Ejemplo n.º 3
0
        public static MDataColumn GetColumns(string tableName, ref DbBase dbHelper)
        {
            tableName = Convert.ToString(SqlCreate.SqlToViewSql(tableName));
            DalType dalType = dbHelper.dalType;

            tableName = SqlFormat.Keyword(tableName, dbHelper.dalType);

            string key = GetSchemaKey(tableName, dbHelper.DataBase, dbHelper.dalType);

            if (CacheManage.LocalInstance.Contains(key))//缓存里获取
            {
                return(CacheManage.LocalInstance.Get <MDataColumn>(key).Clone());
            }
            switch (dalType)
            {
            case DalType.SQLite:
            case DalType.MySql:
                tableName = SqlFormat.NotKeyword(tableName);
                break;

            case DalType.Txt:
            case DalType.Xml:
                tableName = Path.GetFileNameWithoutExtension(tableName);    //视图表,带“.“的,会出问题
                string      fileName = dbHelper.Con.DataSource + tableName + (dalType == DalType.Txt ? ".txt" : ".xml");
                MDataColumn mdc      = MDataColumn.CreateFrom(fileName);
                mdc.dalType = dalType;
                return(mdc);
            }

            MDataColumn mdcs = new MDataColumn();

            mdcs.dalType = dbHelper.dalType;
            //如果table和helper不在同一个库
            DbBase helper = dbHelper.ResetDbBase(tableName);

            helper.IsAllowRecordSql = false;//内部系统,不记录SQL表结构语句。
            try
            {
                bool isView = tableName.Contains(" ");//是否视图。
                if (!isView)
                {
                    isView = Exists("V", tableName, ref helper);
                }
                MCellStruct mStruct = null;
                SqlDbType   sqlType = SqlDbType.NVarChar;
                if (isView)
                {
                    string sqlText = SqlFormat.BuildSqlWithWhereOneEqualsTow(tableName);// string.Format("select * from {0} where 1=2", tableName);
                    mdcs = GetViewColumns(sqlText, ref helper);
                }
                else
                {
                    mdcs.AddRelateionTableName(SqlFormat.NotKeyword(tableName));
                    switch (dalType)
                    {
                    case DalType.MsSql:
                    case DalType.Oracle:
                    case DalType.MySql:
                    case DalType.Sybase:
                        #region Sql
                        string sql = string.Empty;
                        if (dalType == DalType.MsSql)
                        {
                            string dbName = null;
                            if (!helper.Version.StartsWith("08"))
                            {
                                //先获取同义词,检测是否跨库
                                string realTableName = Convert.ToString(helper.ExeScalar(string.Format(SynonymsName, SqlFormat.NotKeyword(tableName)), false));
                                if (!string.IsNullOrEmpty(realTableName))
                                {
                                    string[] items = realTableName.Split('.');
                                    tableName = realTableName;
                                    if (items.Length > 0)    //跨库了
                                    {
                                        dbName = realTableName.Split('.')[0];
                                    }
                                }
                            }

                            sql = GetMSSQLColumns(helper.Version.StartsWith("08"), dbName ?? helper.DataBase);
                        }
                        else if (dalType == DalType.MySql)
                        {
                            sql = GetMySqlColumns(helper.DataBase);
                        }
                        else if (dalType == DalType.Oracle)
                        {
                            sql = GetOracleColumns();
                        }
                        else if (dalType == DalType.Sybase)
                        {
                            tableName = SqlFormat.NotKeyword(tableName);
                            sql       = GetSybaseColumns();
                        }
                        helper.AddParameters("TableName", tableName, DbType.String, 150, ParameterDirection.Input);
                        DbDataReader sdr = helper.ExeDataReader(sql, false);
                        if (sdr != null)
                        {
                            long   maxLength;
                            bool   isAutoIncrement = false;
                            short  scale           = 0;
                            string sqlTypeName     = string.Empty;
                            while (sdr.Read())
                            {
                                short.TryParse(Convert.ToString(sdr["Scale"]), out scale);
                                if (!long.TryParse(Convert.ToString(sdr["MaxSize"]), out maxLength))    //mysql的长度可能大于int.MaxValue
                                {
                                    maxLength = -1;
                                }
                                else if (maxLength > int.MaxValue)
                                {
                                    maxLength = int.MaxValue;
                                }
                                sqlTypeName             = Convert.ToString(sdr["SqlType"]);
                                sqlType                 = DataType.GetSqlType(sqlTypeName);
                                isAutoIncrement         = Convert.ToBoolean(sdr["IsAutoIncrement"]);
                                mStruct                 = new MCellStruct(mdcs.dalType);
                                mStruct.ColumnName      = Convert.ToString(sdr["ColumnName"]).Trim();
                                mStruct.OldName         = mStruct.ColumnName;
                                mStruct.SqlType         = sqlType;
                                mStruct.IsAutoIncrement = isAutoIncrement;
                                mStruct.IsCanNull       = Convert.ToBoolean(sdr["IsNullable"]);
                                mStruct.MaxSize         = (int)maxLength;
                                mStruct.Scale           = scale;
                                mStruct.Description     = Convert.ToString(sdr["Description"]);
                                mStruct.DefaultValue    = SqlFormat.FormatDefaultValue(dalType, sdr["DefaultValue"], 0, sqlType);
                                mStruct.IsPrimaryKey    = Convert.ToString(sdr["IsPrimaryKey"]) == "1";
                                switch (dalType)
                                {
                                case DalType.MsSql:
                                case DalType.MySql:
                                case DalType.Oracle:
                                    mStruct.IsUniqueKey  = Convert.ToString(sdr["IsUniqueKey"]) == "1";
                                    mStruct.IsForeignKey = Convert.ToString(sdr["IsForeignKey"]) == "1";
                                    mStruct.FKTableName  = Convert.ToString(sdr["FKTableName"]);
                                    break;
                                }

                                mStruct.SqlTypeName = sqlTypeName;
                                mStruct.TableName   = SqlFormat.NotKeyword(tableName);
                                mdcs.Add(mStruct);
                            }
                            sdr.Close();
                            if (dalType == DalType.Oracle && mdcs.Count > 0)    //默认没有自增概念,只能根据情况判断。
                            {
                                MCellStruct firstColumn = mdcs[0];
                                if (firstColumn.IsPrimaryKey && firstColumn.ColumnName.ToLower().Contains("id") && firstColumn.Scale == 0 && DataType.GetGroup(firstColumn.SqlType) == 1 && mdcs.JointPrimary.Count == 1)
                                {
                                    firstColumn.IsAutoIncrement = true;
                                }
                            }
                        }
                        #endregion
                        break;

                    case DalType.SQLite:
                        #region SQlite
                        if (helper.Con.State != ConnectionState.Open)
                        {
                            helper.Con.Open();
                        }
                        DataTable sqliteDt = helper.Con.GetSchema("Columns", new string[] { null, null, tableName });
                        if (!helper.isOpenTrans)
                        {
                            helper.Con.Close();
                        }
                        int    size;
                        short  sizeScale;
                        string dataTypeName = string.Empty;

                        foreach (DataRow row in sqliteDt.Rows)
                        {
                            object len = row["NUMERIC_PRECISION"];
                            if (len == null)
                            {
                                len = row["CHARACTER_MAXIMUM_LENGTH"];
                            }
                            short.TryParse(Convert.ToString(row["NUMERIC_SCALE"]), out sizeScale);
                            if (!int.TryParse(Convert.ToString(len), out size))    //mysql的长度可能大于int.MaxValue
                            {
                                size = -1;
                            }
                            dataTypeName = Convert.ToString(row["DATA_TYPE"]);
                            if (dataTypeName == "text" && size > 0)
                            {
                                sqlType = DataType.GetSqlType("varchar");
                            }
                            else
                            {
                                sqlType = DataType.GetSqlType(dataTypeName);
                            }
                            //COLUMN_NAME,DATA_TYPE,PRIMARY_KEY,IS_NULLABLE,CHARACTER_MAXIMUM_LENGTH AUTOINCREMENT

                            mStruct              = new MCellStruct(row["COLUMN_NAME"].ToString(), sqlType, Convert.ToBoolean(row["AUTOINCREMENT"]), Convert.ToBoolean(row["IS_NULLABLE"]), size);
                            mStruct.Scale        = sizeScale;
                            mStruct.Description  = Convert.ToString(row["DESCRIPTION"]);
                            mStruct.DefaultValue = SqlFormat.FormatDefaultValue(dalType, row["COLUMN_DEFAULT"], 0, sqlType);    //"COLUMN_DEFAULT"
                            mStruct.IsPrimaryKey = Convert.ToBoolean(row["PRIMARY_KEY"]);
                            mStruct.SqlTypeName  = dataTypeName;
                            mStruct.TableName    = SqlFormat.NotKeyword(tableName);
                            mdcs.Add(mStruct);
                        }
                        #endregion
                        break;

                    case DalType.Access:
                        #region Access
                        DataTable       keyDt, valueDt;
                        string          sqlText = SqlFormat.BuildSqlWithWhereOneEqualsTow(tableName);// string.Format("select * from {0} where 1=2", tableName);
                        OleDbConnection con     = new OleDbConnection(helper.Con.ConnectionString);
                        OleDbCommand    com     = new OleDbCommand(sqlText, con);
                        con.Open();
                        keyDt   = com.ExecuteReader(CommandBehavior.KeyInfo).GetSchemaTable();
                        valueDt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, SqlFormat.NotKeyword(tableName) });
                        con.Close();
                        con.Dispose();

                        if (keyDt != null && valueDt != null)
                        {
                            string    columnName = string.Empty, sqlTypeName = string.Empty;
                            bool      isKey = false, isCanNull = true, isAutoIncrement = false;
                            int       maxSize      = -1;
                            short     maxSizeScale = 0;
                            SqlDbType sqlDbType;
                            foreach (DataRow row in keyDt.Rows)
                            {
                                columnName      = row["ColumnName"].ToString();
                                isKey           = Convert.ToBoolean(row["IsKey"]);       //IsKey
                                isCanNull       = Convert.ToBoolean(row["AllowDBNull"]); //AllowDBNull
                                isAutoIncrement = Convert.ToBoolean(row["IsAutoIncrement"]);
                                sqlTypeName     = Convert.ToString(row["DataType"]);
                                sqlDbType       = DataType.GetSqlType(sqlTypeName);
                                short.TryParse(Convert.ToString(row["NumericScale"]), out maxSizeScale);
                                if (Convert.ToInt32(row["NumericPrecision"]) > 0)    //NumericPrecision
                                {
                                    maxSize = Convert.ToInt32(row["NumericPrecision"]);
                                }
                                else
                                {
                                    long len = Convert.ToInt64(row["ColumnSize"]);
                                    if (len > int.MaxValue)
                                    {
                                        maxSize = int.MaxValue;
                                    }
                                    else
                                    {
                                        maxSize = (int)len;
                                    }
                                }
                                mStruct              = new MCellStruct(columnName, sqlDbType, isAutoIncrement, isCanNull, maxSize);
                                mStruct.Scale        = maxSizeScale;
                                mStruct.IsPrimaryKey = isKey;
                                mStruct.SqlTypeName  = sqlTypeName;
                                mStruct.TableName    = SqlFormat.NotKeyword(tableName);
                                foreach (DataRow item in valueDt.Rows)
                                {
                                    if (columnName == item[3].ToString())    //COLUMN_NAME
                                    {
                                        if (item[8].ToString() != "")
                                        {
                                            mStruct.DefaultValue = SqlFormat.FormatDefaultValue(dalType, item[8], 0, sqlDbType);    //"COLUMN_DEFAULT"
                                        }
                                        break;
                                    }
                                }
                                mdcs.Add(mStruct);
                            }
                        }

                        #endregion
                        break;
                    }
                }
                helper.ClearParameters();
            }
            catch (Exception err)
            {
                helper.debugInfo.Append(err.Message);
            }
            finally
            {
                helper.IsAllowRecordSql = true;//恢复记录SQL表结构语句。
                if (helper != dbHelper)
                {
                    helper.Dispose();
                }
            }
            if (mdcs.Count > 0)
            {
                //移除被标志的列:
                string[] fields = AppConfig.DB.HiddenFields.Split(',');
                foreach (string item in fields)
                {
                    string field = item.Trim();
                    if (!string.IsNullOrEmpty(field) & mdcs.Contains(field))
                    {
                        mdcs.Remove(field);
                    }
                }
            }
            if (!CacheManage.LocalInstance.Contains(key))
            {
                CacheManage.LocalInstance.Add(key, mdcs.Clone());
            }
            return(mdcs);
        }
Ejemplo n.º 4
0
 /// <summary>
 /// �Ƿ���ڱ����ͼ
 /// </summary>
 /// <param name="type">"U"��"V"</param>
 /// <param name="name">��������ͼ��</param>
 public static bool Exists(string type, string name, ref DbBase helper)
 {
     if (type == "U" && tableCache.Count > 0)
     {
         string key = "TableCache:" + helper.dalType + "." + helper.DataBase;
         if (tableCache.ContainsKey(key))
         {
             return tableCache[key].ContainsKey(name);
         }
     }
     int result = 0;
     string exist = string.Empty;
     helper.IsAllowRecordSql = false;
     DalType dalType = helper.dalType;
     name = SqlFormat.Keyword(name, helper.dalType);
     switch (dalType)
     {
         case DalType.Access:
             try
             {
                 System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection(helper.Con.ConnectionString);
                 con.Open();
                 result = con.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, SqlFormat.NotKeyword(name), "Table" }).Rows.Count;
                 con.Close();
             }
             catch (Exception err)
             {
                 Log.WriteLogToTxt(err);
             }
             break;
         case DalType.MySql:
             if (type != "V" || (type == "V" && name.ToLower().StartsWith("v_")))//��ͼ����v_��ͷ
             {
                 exist = string.Format(ExistMySql, SqlFormat.NotKeyword(name), helper.DataBase);
             }
             break;
         case DalType.Oracle:
             exist = string.Format(ExistOracle, (type == "U" ? "TABLE" : "VIEW"), name);
             break;
         case DalType.MsSql:
             exist = string.Format(helper.Version.StartsWith("08") ? Exist2000 : Exist2005, name, type);
             break;
         case DalType.SQLite:
             exist = string.Format(ExistSqlite, (type == "U" ? "table" : "view"), SqlFormat.NotKeyword(name));
             break;
         case DalType.Sybase:
             exist = string.Format(ExistSybase, SqlFormat.NotKeyword(name), type);
             break;
         case DalType.Txt:
         case DalType.Xml:
             string folder = helper.Con.DataSource + Path.GetFileNameWithoutExtension(name);
             FileInfo info = new FileInfo(folder + ".ts");
             result = (info.Exists && info.Length > 10) ? 1 : 0;
             if (result == 0)
             {
                 info = new FileInfo(folder + (dalType == DalType.Txt ? ".txt" : ".xml"));
                 result = (info.Exists && info.Length > 10) ? 1 : 0;
             }
             break;
     }
     if (exist != string.Empty)
     {
         helper.IsAllowRecordSql = false;
         result = Convert.ToInt32(helper.ExeScalar(exist, false));
     }
     return result > 0;
 }
Ejemplo n.º 5
0
        /// <summary>
        /// 是否存在表或视图
        /// </summary>
        /// <param name="type">"U"或"V"</param>
        /// <param name="name">表名或视图名</param>
        public static bool Exists(string type, string name, ref DbBase helper)
        {
            if (type == "U" && tableCache.Count > 0)
            {
                string key = "TableCache:" + helper.dalType + "." + helper.DataBase;
                if (tableCache.ContainsKey(key))
                {
                    return(tableCache[key].ContainsKey(name));
                }
            }
            int    result = 0;
            string exist  = string.Empty;

            helper.IsAllowRecordSql = false;
            DalType dalType = helper.dalType;

            name = SqlFormat.Keyword(name, helper.dalType);
            switch (dalType)
            {
            case DalType.Access:
                try
                {
                    System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection(helper.Con.ConnectionString);
                    con.Open();
                    result = con.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, SqlFormat.NotKeyword(name), "Table" }).Rows.Count;
                    con.Close();
                }
                catch (Exception err)
                {
                    Log.WriteLogToTxt(err);
                }
                break;

            case DalType.MySql:
                if (type != "V" || (type == "V" && name.ToLower().StartsWith("v_")))    //视图必须v_开头
                {
                    exist = string.Format(ExistMySql, SqlFormat.NotKeyword(name), helper.DataBase);
                }
                break;

            case DalType.Oracle:
                exist = string.Format(ExistOracle, (type == "U" ? "TABLE" : "VIEW"), name);
                break;

            case DalType.MsSql:
                exist = string.Format(helper.Version.StartsWith("08") ? Exist2000 : Exist2005, name, type);
                break;

            case DalType.SQLite:
                exist = string.Format(ExistSqlite, (type == "U" ? "table" : "view"), SqlFormat.NotKeyword(name));
                break;

            case DalType.Sybase:
                exist = string.Format(ExistSybase, SqlFormat.NotKeyword(name), type);
                break;

            case DalType.Txt:
            case DalType.Xml:
                string   folder = helper.Con.DataSource + Path.GetFileNameWithoutExtension(name);
                FileInfo info   = new FileInfo(folder + ".ts");
                result = (info.Exists && info.Length > 10) ? 1 : 0;
                if (result == 0)
                {
                    info   = new FileInfo(folder + (dalType == DalType.Txt ? ".txt" : ".xml"));
                    result = (info.Exists && info.Length > 10) ? 1 : 0;
                }
                break;
            }
            if (exist != string.Empty)
            {
                helper.IsAllowRecordSql = false;
                result = Convert.ToInt32(helper.ExeScalar(exist, false));
            }
            return(result > 0);
        }