using System.Data;
using System.Data.SqlClient;
using Stat.DBUtility;
namespace Stat.SQLServerDAL
{
    class Database : IDAL.IDatabase
    {
        #region Idatabase 成员

        public System.Data.DataTable GetList(global::Stat.Model.Database database, ref global::Stat.Model.PageInfo pageInfo)
        {

            string connectionString = GetConnectionString(database.DatabaseId);           

            string sqlWhere = string.Empty;

            sqlWhere += " 1=1";
            if (!database.Keyword.Equals(""))
            {
                sqlWhere += " and " + database.QueryField + " LIKE '%" + database.Keyword + "%'";
            }

            int recordCount = 0;

            DataTable dt = JPageIndex.ProGetList.GetFromDataTable(database.Datatable, database.GetField, sqlWhere, database.SortField, database.SortStype, pageInfo.PageSize, pageInfo.PageIndex, ref recordCount, "Stat_PageIndex", connectionString);

            pageInfo.RecordCount = recordCount;

            return dt;
        }

        /// <summary>
        /// 获取数据库中的所有表名及表名的主键名（待写成存储过程）
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <returns></returns>
        /// <remarks>By juju 2011-09-06</remarks>
        public string[,] GetTables(int databaseServerId)
        {
            string connectionString = GetConnectionString(databaseServerId);

            //查询 主键名 及 表名
            string commandText = "SELECT b.name as keyName,a.Name as Tablename FROM SysObjects a,SysColumns b";
            commandText += " Where a.XType='U' and b.id=Object_Id(a.Name) and b.colid in (select keyno from sysindexkeys where id=Object_Id(a.Name)) order by a.name asc";

            DataTable dt = DBUtility.SqlHelper.ExecuteDataTable(connectionString, CommandType.Text, commandText, null);

            if (dt != null && dt.Rows.Count > 0)
            {
                string[,] arr = new string[dt.Rows.Count, 2];

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    arr[i, 0] = dt.Rows[i][0].ToString();
                    arr[i, 1] = dt.Rows[i][1].ToString();
                }
                return arr;
            }

            return null;
        }

        private static string GetConnectionString(int databaseServerId)
        {
            string connectionString = string.Empty;
            if (databaseServerId > 0)
                connectionString = SqlHelper.ConnectionStringGather(databaseServerId);
            else
                connectionString = SqlHelper.ConnectionStringMaster;
            return connectionString;
        }


        #endregion
    }
}
