📄 mysqlrecord.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: MySqlRecord.cs * Description: MySql implentation of AbstractRecord * * Author: Ben Joldersma * */using System;using System.Collections;using System.Collections.Specialized;using System.Reflection;using System.ComponentModel;using MySql.Data.MySqlClient;using System.Web;using System.Collections.Generic;using System.Data;namespace EmergeTk.Model{ /// <summary> /// Summary description for Model. /// </summary> public class MySqlRecord : AbstractRecord { override public DataProvider Provider { get { return MySqlProvider.Provider; } } public MySqlRecord() { DataProvider.RegisterProvider(this.GetType(), MySqlProvider.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} ( `ROWID` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, {1},PRIMARY KEY(`ROWID`) )"; const string UpdateTableFormat = "UPDATE {0} SET {1} WHERE ROWID = {2}"; const string InsertTableFormat = "INSERT INTO {0}({2}) VALUES( {1} ); SELECT LAST_INSERT_ID();"; 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(); List<String> fieldNames = new List<string>(); if( id == 0 ) { foreach( ColumnInfo col in Fields ) { if (col.Type == typeof(int) || col.Type == typeof(decimal)) { values.Add( this[col.Name] ); } else if (col.Type.IsSubclassOf(typeof(MySqlRecord))) { MySqlRecord r = this[col.Name] as MySqlRecord; //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 + "'"); } fieldNames.Add(col.Name); } sql = string.Format(InsertTableFormat, this.ModelName, Util.Join(values, ","), Util.Join(fieldNames) ); try { //we may get an exception here if the model has changed. if so, resynchronize. this.id = Convert.ToInt32(MySqlProvider.Provider.ExecuteScalar(sql, false)); } catch { SynchronizeModel(); //try again, if another exception, let it throw out. this.id = Convert.ToInt32(MySqlProvider.Provider.ExecuteScalar(sql, true)); } if( SaveChildren ) foreach( ColumnInfo col in Fields ) { if( TypeIsRecordList(col.Type) ) { MethodInfo mi = typeof(MySqlRecord).GetMethod("SaveChildRecordList"); mi = mi.MakeGenericMethod(this.GetType()); 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(MySqlRecord))) { MySqlRecord r = this[col.Name] as MySqlRecord; 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(MySqlRecord).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. MySqlProvider.Provider.ExecuteNonQuery(sql, true); } catch { SynchronizeModel(); MySqlProvider.Provider.ExecuteNonQuery(sql, true); } FireChangeEvents(); } } public void SaveChildRecordList<T>(string PropertyName, IRecordList<T> list) where T : MySqlRecord { string tableName = this.ModelName; string childTableName = tableName + "_" + PropertyName; MySqlProvider.Provider.ExecuteNonQuery( string.Format( "DELETE FROM {0} WHERE Parent_Id = {1}", childTableName, this.id ), true ); foreach( T r in list ) { if( r.id == 0 ) r.Save(false); MySqlProvider.Provider.ExecuteNonQuery(string.Format("INSERT INTO {0} VALUES( {1}, {2} )", childTableName, this.id, r.id),true); } } override public void Delete() { MySqlProvider.Provider.ExecuteNonQuery(string.Format(DeleteFormat, this.ModelName, this.id), true); base.Delete(); } private void SynchronizeModel() { typeof(MySqlRecord).GetMethod("SynchronizeModelType", BindingFlags.NonPublic | BindingFlags.Instance).MakeGenericMethod( this.GetType()).Invoke(this, null); } private void SynchronizeModelType<T>() where T : MySqlRecord, new() { EnsureTablesCreated(); IRecordList<T> oldRecords = MySqlProvider.Provider.Load<T>(); MySqlProvider.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)) { if (col.DataType == DataType.LargeText || col.DataType == DataType.Xml) dataType = LongStringDataType; else if (col.DataType == DataType.SmallText) dataType = ShortStringDataType; else 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 = "DATETIME"; } else if (col.Type.IsSubclassOf(typeof(Enum))) { dataType = "varchar(50)"; } else if (col.Type.IsSubclassOf(typeof(MySqlRecord))) { dataType = "int"; } else if (TypeIsRecordList(col.Type)) { createChildTable(tableName + "_" + col.Name, col); } if (dataType != null) { pairs.Add(col.Name + " " + dataType); } } string propString = Util.Join(pairs, ", "); MySqlProvider.Provider.ExecuteNonQuery(string.Format(CreateTableFormat, tableName, propString), true); } private static void createChildTable(string tableName, ColumnInfo col) { if (!TableExists(tableName)) { MySqlProvider.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 ) { MySqlConnection conn = MySqlProvider.CreateConnection(); if (existingTables == null) existingTables = new Dictionary<string, bool>(); else if (existingTables.ContainsKey(name) ) return existingTables[name]; int c = Convert.ToInt32(MySqlProvider.Provider.ExecuteScalar("SELECT COUNT(*) FROM information_schema.TABLES WHERE Table_Schema = '" + conn.Database + "' and Table_Name = '" + name + "'", false)); return existingTables[name] = c > 0; } public static object[] emptyObjectArray = new object[]{}; private static Dictionary<string,MySqlRecord> recordCache = new Dictionary<string,MySqlRecord>(); 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 MySqlRecord).EnsureTablesCreated(); return null; } DataTable result = MySqlProvider.Provider.ExecuteDataTable(string.Format("SELECT * FROM {0} WHERE {1} ", name, WhereClause), false); if(result.Rows.Count == 0 ) return null; T r = LoadFromDataRow<T>(result.Rows[0]); recordCache[key] = r as MySqlRecord; 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 = MySqlProvider.Provider.ExecuteDataTable(string.Format("SELECT * FROM {0} WHERE Parent_Id = {1}", childTableName, id), false); foreach (DataRow row in children.Rows) { C r2 = MySqlRecord.Load<C>(Convert.ToInt32(row["Child_Id"])); childRecords.Add(r2); } return childRecords; } static bool propertyIsRecordList(PropertyInfo prop ) { return (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition().Name == "RecordList`"); } 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 + -