⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sqliterecord.cs

📁 一种.net实现ajax方法的类库
💻 CS
字号:
/** Copyright (c) 2006, All-In-One Creations, Ltd.*  All rights reserved.* * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:* *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.*     * Neither the name of All-In-One Creations, Ltd. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLEFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.**//** * Project: emergetk: stateful web framework for the masses * File name: SQLiteRecord.cs * Description: SQLite implentation of AbstractRecord *    * Author: Ben Joldersma *    */using System;using System.Collections;using System.Collections.Specialized;using System.Reflection;using System.ComponentModel;//#if MONO//using Mono.Data.SqliteClient;//#else//using System.Data.SQLite;//#endifusing System.Web;using System.Collections.Generic;using System.Data;namespace EmergeTk.Model{    	/// <summary>	/// Summary description for Model.	/// </summary>	public class SQLiteRecord : AbstractRecord	{        override public DataProvider Provider        {            get            {                return SQLiteProvider.Provider;            }        }        public SQLiteRecord() { DataProvider.RegisterProvider(this.GetType(), SQLiteProvider.Provider); }		const string LongStringDataType = "varchar(8000)";		const string ShortStringDataType = "varchar(20)";		const string StringDataType = "varchar(500)";		const string IntDataType = "int";		const string CreateTableFormat = "CREATE TABLE {0} ( {1} )";		const string UpdateTableFormat = "UPDATE {0} SET {1} WHERE ROWID = {2}";        const string InsertTableFormat = "INSERT INTO {0} VALUES( {1} ); SELECT last_insert_rowid()";		const string DeleteFormat = "DELETE FROM {0} WHERE ROWID = {1}";        const string DropFormat = "DROP TABLE {0}";        override public void Save()		{			Save(true);		}        override public void Save(bool SaveChildren)		{			if( loading )				return;			EnsureTablesCreated();			string sql = "";			ArrayList values = new ArrayList();            if( id == 0 )			{				foreach( ColumnInfo col in Fields )				{                    if (col.DataType == DataType.RecordList)                        continue;                    if (col.Type == typeof(int) || col.Type == typeof(decimal))					{						values.Add( this[col.Name] );					}                    else if (col.Type.IsSubclassOf(typeof(SQLiteRecord)))                    {                        SQLiteRecord r = this[col.Name] as SQLiteRecord;                        //TODO: there shuold be an option to decide if they want to allow adding nulls or not here.                        if (r != null)                            values.Add(r.id);                        else                            values.Add("NULL");                    }                    else//string, enum, etc.                    {                        string val = null;                        if (this[col.Name] != null)                            val = this[col.Name].ToString();                        val = (val != null) ? val.Replace("'", "''") : string.Empty;                        values.Add("'" + val + "'");                    }				}				sql = string.Format( InsertTableFormat, this.ModelName, Util.Join( values, "," ) );                try                {                    //we may get an exception here if the model has changed. if so, resynchronize.                    this.id = Convert.ToInt32(SQLiteProvider.Provider.ExecuteScalar(sql, false));                }                catch                {                    SynchronizeModel();                    //try again, if another exception, let it throw out.                    this.id = Convert.ToInt32(SQLiteProvider.Provider.ExecuteScalar(sql, true));                }                                				if( SaveChildren )				    foreach( ColumnInfo col in Fields )				    {					    if( col.DataType == DataType.RecordList )					    {                            MethodInfo mi = typeof(SQLiteRecord).GetMethod("SaveChildRecordList");                            mi = mi.MakeGenericMethod(this[col.Name].GetType().GetGenericArguments()[0]);                            mi.Invoke(this, new object[] { col.Name, this[col.Name] });					    }				    }                if (newRecordListeners.ContainsKey(this.GetType()))                    newRecordListeners[this.GetType()](this);			}			else			{				foreach( ColumnInfo col in Fields )				{                    if (col.Type == typeof(int) || col.Type == typeof(decimal))					{						values.Add( col.Name + "=" + this[col.Name] );					}                    else if (col.Type.IsSubclassOf(typeof(SQLiteRecord)))                    {                        SQLiteRecord r = this[col.Name] as SQLiteRecord;                        if( r != null )                            values.Add(col.Name + "=" + r.id);                    }                    else if (TypeIsRecordList(col.Type) && SaveChildren)                    {                        object childList = this[col.Name];                        if (childList != null)                        {                            MethodInfo mi = typeof(SQLiteRecord).GetMethod("SaveChildRecordList");                            mi = mi.MakeGenericMethod(childList.GetType().GetGenericArguments()[0]);                            mi.Invoke(this, new object[] { col.Name, this[col.Name] });                        }                    }                    else //string, datetime, enum, record, etc.                    {                        string val = null;                        if (this[col.Name] != null)                            val = this[col.Name].ToString();                        val = (val != null) ? val.Replace("'", "''") : string.Empty;                        values.Add(col.Name + "=" + "'" + val + "'");                    }				}                sql = string.Format(UpdateTableFormat, this.ModelName, Util.Join(values, ","), this.id);                try                {                    //we may get an exception here if the model has changed. if so, resynchronize.                    SQLiteProvider.Provider.ExecuteNonQuery(sql, true);                }                catch                {                    SynchronizeModel();                    SQLiteProvider.Provider.ExecuteNonQuery(sql, true);                }                FireChangeEvents();			}		}        public void SaveChildRecordList<T>(string PropertyName, IRecordList<T> list) where T : SQLiteRecord		{            string tableName = this.ModelName;			string childTableName = tableName + "_" + PropertyName;			SQLiteProvider.Provider.ExecuteNonQuery( string.Format( "DELETE FROM {0} WHERE Parent_Id = {1}", childTableName, this.id ), true );			foreach( T r in list )			{				r.Save(false);                SQLiteProvider.Provider.ExecuteNonQuery(string.Format("INSERT INTO {0} VALUES( {1}, {2} )", childTableName, this.id, r.id),true);			}		}        override public void Delete()        {            SQLiteProvider.Provider.ExecuteNonQuery(string.Format(DeleteFormat, this.ModelName, this.id), true);            base.Delete();        }        private void SynchronizeModel()        {            typeof(SQLiteRecord).GetMethod("SynchronizeModelType", BindingFlags.NonPublic | BindingFlags.Instance).MakeGenericMethod(                         this.GetType()).Invoke(this, null);        }        private void SynchronizeModelType<T>() where T : SQLiteRecord, new()        {            EnsureTablesCreated();            IRecordList<T> oldRecords = SQLiteProvider.Provider.Load<T>();            SQLiteProvider.Provider.ExecuteNonQuery(string.Format(DropFormat, ModelName), true);            existingTables[ModelName] = false;            if (oldRecords != null && oldRecords.Count > 0)            {                //TODO: this will break FK relationships!                foreach (T r in oldRecords)                    r.id = 0;                oldRecords.Save();            }            EnsureTablesCreated();        }		private void EnsureTablesCreated()		{			string tableName = this.ModelName;            if (TableExists(tableName))                return;            CreateTable(tableName);            existingTables[tableName] = true;		}        private void CreateTable(string tableName)        {            ArrayList pairs = new ArrayList();            foreach (ColumnInfo col in Fields )            {                string dataType = null; //"int";                if (col.Type == typeof(string))                {                    dataType = StringDataType;                }                else if (col.Type == typeof(int))                {                    dataType = "int";                }                else if (col.Type == typeof(decimal))                {                    dataType = "float";                }                else if (col.Type == typeof(DateTime))                {                    dataType = "string";                }                else if (col.Type.IsSubclassOf(typeof(Enum)))                {                    dataType = "string";                }                else if (col.Type.IsSubclassOf(typeof(SQLiteRecord)))                {                    dataType = "int";                }                else if (TypeIsRecordList(col.Type))                {                    createChildTable(tableName + "_" + col.Name, col);                }                else if (col.Type == typeof(bool))                {                    dataType = "bit";                }                if (dataType != null)                {                    pairs.Add(col.Name + " " + dataType);                }            }            string propString = Util.Join(pairs, ", ");            SQLiteProvider.Provider.ExecuteNonQuery(string.Format(CreateTableFormat, tableName, propString), true);        }        private static void createChildTable(string tableName, ColumnInfo col)        {            if (!TableExists(tableName))            {                SQLiteProvider.Provider.ExecuteNonQuery(string.Format(CreateTableFormat, tableName, "Parent_Id int, Child_Id int"), true);                existingTables[tableName] = true;            }        }        static Dictionary<string, bool> existingTables;		static public bool TableExists( string name )		{            if (existingTables == null) existingTables = new Dictionary<string, bool>();            else if (existingTables.ContainsKey(name) ) return existingTables[name];            int c = Convert.ToInt32(SQLiteProvider.Provider.ExecuteScalar("SELECT COUNT(*) FROM sqlite_master WHERE name = '" + name + "'", false));            return existingTables[name] = c > 0;		}		private static Dictionary<string,SQLiteRecord> recordCache = new Dictionary<string,SQLiteRecord>();        public static T Load<T>(params FilterInfo[] filters) where T : AbstractRecord, new()        {            string WhereClause = Util.Join(filters);            string name = typeof(T).Name;            string key = name + "_" + WhereClause;            if (recordCache.ContainsKey(key))                return recordCache[key] as T;            if (!TableExists(name))            {                T dummy = new T();                (dummy as SQLiteRecord).EnsureTablesCreated();                return null;            }            DataTable result = SQLiteProvider.Provider.ExecuteDataTable(string.Format("SELECT ROWID, * FROM {0} WHERE {1} ", name, WhereClause), false);            if (result == null || result.Rows.Count == 0)                return null;            T r = LoadFromDataRow<T>(result.Rows[0]);            recordCache[key] = r as SQLiteRecord;            return r;        }        protected RecordList<C> LoadChildren<C>(ColumnInfo fi) where C : AbstractRecord, new()         {            string childTableName = ModelName + "_" + fi.Name;            if (!TableExists(childTableName))                createChildTable(childTableName, fi);            RecordList<C> childRecords = new RecordList<C>();            DataTable children = SQLiteProvider.Provider.ExecuteDataTable(string.Format("SELECT * FROM {0} WHERE Parent_Id = {1}", childTableName, id), false);            foreach (DataRow row in children.Rows)            {                C r2 = SQLiteRecord.Load<C>(Convert.ToInt32(row["Child_Id"]));                if( r2 != null )                    childRecords.Add(r2);            }            return childRecords;        }        public static T Load<T>(int id) where T : AbstractRecord, new()		{            return Load<T>(new FilterInfo("ROWID",id,FilterOperation.Equals));		}    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -