diff --git a/Assets/Output/SQLMaker.cs b/Assets/Output/SQLMaker.cs index cc664f5..4a5bffd 100644 --- a/Assets/Output/SQLMaker.cs +++ b/Assets/Output/SQLMaker.cs @@ -2,122 +2,157 @@ using System.Text; using System.Collections.Generic; - namespace UnityORM { - public class SQLMaker - { - - public readonly static DateTime UnixTime = new DateTime(1970,1,1); - - public SQLMaker () - { - } - - public string GenerateCreateTableSQL(ClassDesc desc){ - - var builder = new StringBuilder(); - builder.Append("CREATE TABLE IF NOT EXISTS " + desc.Name + "("); - foreach(var f in desc.FieldDescs){ - builder.Append(f.NameInTable + " " + ConvertToSQLType(f.FieldType )); - if(f == desc.KeyField){ - builder.Append(" PRIMARY KEY"); - } - if( desc.AutoIncrement){ - builder.Append(" AUTOINCREMENT"); - } - builder.Append(","); - } - builder.Remove(builder.Length - 1,1); - builder.Append(");"); - return builder.ToString(); - } - string ConvertToSQLType(Type t){ - if(t == typeof(int) || - t == typeof(long)){ - return "INTEGER"; - }else if(t == typeof(double)){ - return "FLOAT"; - }else if(t == typeof(byte[])){ - return "BLOB"; - }else if(t == typeof(DateTime)){ - return "INTEGER"; - }else{ - return "TEXT"; - } - } - - public string GenerateSelectAllSQL(ClassDesc desc){ - return "SELECT * FROM " + desc.Name + ";"; - } - - public string GenerateSelectSQL(ClassDesc desc,object key){ - if(desc.KeyField == null) throw new Exception("Class " + desc.Name + " hasn't key field"); - return "SELECT * FROM " + desc.Name + " WHERE " + desc.KeyField.NameInTable + " = " + ValueToBlock(key) + ";"; - } - - public string GenerateDeleteAllSQL(ClassDesc desc){ - return "DELETE FROM " + desc.Name + ";"; - } - public string GenerateDeleteSQL(ClassDesc desc,object key){ - if(desc.KeyField == null) throw new Exception("Class " + desc.Name + " hasn't key field"); - return "DELETE FROM " + desc.Name + " WHERE " + desc.KeyField.NameInTable + " = " + ValueToBlock(key) + ";"; - } - - public string GenerateInsertSQL(ClassDesc desc,T obj){ - var builder = new StringBuilder(); - builder.Append("INSERT INTO " + desc.Name + " ("); - - var fields = desc.FieldDescs; - if(desc.AutoIncrement){ - fields = new List(fields); - fields.Remove(desc.KeyField); - } - - foreach( var f in fields){ - builder.Append(f.NameInTable + ","); - } - builder.Remove(builder.Length - 1,1); - builder.Append(") VALUES ("); - - foreach( var f in fields){ - object v = f.GetForDb(obj); - builder.Append(ValueToBlock(v) + ","); - } - builder.Remove(builder.Length - 1,1); - builder.Append(");"); - - return builder.ToString(); - } - - public string GenerateUpdateSQL(ClassDesc desc,T obj){ - if(desc.KeyField == null) throw new Exception("Class " + desc.Name + " hasn't key field"); - var builder = new StringBuilder(); - builder.Append("UPDATE " + desc.Name + " SET "); - foreach(var f in desc.FieldDescs){ - object v = f.GetForDb(obj); - builder.Append(f.NameInTable + "=" + ValueToBlock(v) + ","); - } - builder.Remove(builder.Length -1 ,1); - builder.Append(" WHERE " + desc.KeyField.NameInTable + " = " + ValueToBlock(desc.KeyField.GetForDb(obj)) + ";"); - - return builder.ToString(); - } - - - string ValueToBlock(object v){ - if(v == null){ - return "NULL"; - }else{ - return "'" + Escape(v.ToString()) + "'"; - } - } - - public string Escape(string str){ - return str.Replace("'","''"); - } - - - } -} + public class SQLMaker + { + public readonly static DateTime UnixTime = new DateTime (1970, 1, 1); + + public SQLMaker () + { + } + + public string GenerateCreateTableSQL (ClassDesc desc) + { + var builder = new StringBuilder (); + builder.Append ("CREATE TABLE IF NOT EXISTS " + desc.Name + "("); + foreach (var f in desc.FieldDescs) + { + builder.Append (f.nameInTable + " " + ConvertToSQLType (f.FieldType)); + if (f == desc.KeyField) + { + builder.Append (" PRIMARY KEY"); + } + if (desc.AutoIncrement) + { + builder.Append (" AUTOINCREMENT"); + } + builder.Append (","); + } + builder.Remove (builder.Length - 1, 1); + builder.Append (");"); + return builder.ToString (); + } + + private string ConvertToSQLType (Type t) + { + if (t == typeof(int) || + t == typeof(long)) + { + return "INTEGER"; + } + else if (t == typeof(double)) + { + return "FLOAT"; + } + else if (t == typeof(byte[])) + { + return "BLOB"; + } + else if (t == typeof(DateTime)) + { + return "INTEGER"; + } + else + { + return "TEXT"; + } + } + + public string GenerateSelectAllSQL (ClassDesc desc) + { + return "SELECT * FROM " + desc.Name + ";"; + } + + public string GenerateSelectSQL (ClassDesc desc, object key) + { + if (desc.KeyField == null) + { + throw new Exception ("Class " + desc.Name + " hasn't key field"); + } + return "SELECT * FROM " + desc.Name + " WHERE " + desc.KeyField.nameInTable + " = " + ValueToBlock (key) + ";"; + } + + public string GenerateDeleteAllSQL (ClassDesc desc) + { + return "DELETE FROM " + desc.Name + ";"; + } + + public string GenerateDeleteSQL (ClassDesc desc, object key) + { + if (desc.KeyField == null) + { + throw new Exception ("Class " + desc.Name + " hasn't key field"); + } + return "DELETE FROM " + desc.Name + " WHERE " + desc.KeyField.nameInTable + " = " + ValueToBlock (key) + ";"; + } + public string GenerateInsertSQL (ClassDesc desc, T obj) + { + var columnsBuilder = new StringBuilder (); + var valuesBuilder = new StringBuilder (); + columnsBuilder.Append ("INSERT INTO " + desc.Name + " ("); + + var fields = desc.FieldDescs; + if (desc.AutoIncrement) + { + fields = new List (fields); + fields.Remove (desc.KeyField); + } + + foreach (var f in fields) + { + // columns + columnsBuilder.Append (f.nameInTable + ","); + // values + object v = f.GetForDb (obj); + valuesBuilder.Append (ValueToBlock (v) + ","); + } + + columnsBuilder.Remove (columnsBuilder.Length - 1, 1); + columnsBuilder.Append (") VALUES ("); + + valuesBuilder.Remove (valuesBuilder.Length - 1, 1); + valuesBuilder.Append (");"); + columnsBuilder.Append (valuesBuilder); + + return columnsBuilder.ToString (); + } + + public string GenerateUpdateSQL (ClassDesc desc, T obj) + { + if (desc.KeyField == null) + { + throw new Exception ("Class " + desc.Name + " hasn't key field"); + } + var builder = new StringBuilder (); + builder.Append ("UPDATE " + desc.Name + " SET "); + foreach (var f in desc.FieldDescs) + { + object v = f.GetForDb (obj); + builder.Append (f.nameInTable + "=" + ValueToBlock (v) + ","); + } + builder.Remove (builder.Length - 1, 1); + builder.Append (" WHERE " + desc.KeyField.nameInTable + " = " + ValueToBlock (desc.KeyField.GetForDb (obj)) + ";"); + + return builder.ToString (); + } + + private string ValueToBlock (object v) + { + if (v == null) + { + return "NULL"; + } + else + { + return "'" + Escape (v.ToString ()) + "'"; + } + } + + private string Escape (string str) + { + return str.Replace ("'", "''"); + } + } +} diff --git a/Assets/Output/SqliteDatabase.cs b/Assets/Output/SqliteDatabase.cs index 4d2dbdc..2c8150f 100755 --- a/Assets/Output/SqliteDatabase.cs +++ b/Assets/Output/SqliteDatabase.cs @@ -1,237 +1,239 @@ using System; using System.Runtime.InteropServices; using UnityEngine; - namespace UnityORM { + public class SqliteException : Exception + { + int errorCode; - public class SqliteException : Exception - { - int errorCode; - public int ErrorCode{get{return errorCode;}} - public SqliteException(int errorCode ,string message) : base(message + "(ErrorCode:" + errorCode + ")") - { - this.errorCode = errorCode; - } - } - - /// - /// Sqlite database. - /// Get from http://gamesforsoul.com/2012/03/sqlite-unity-and-ios-a-rocky-relationship/ - /// and modified. - /// - /// - /// Is thrown when the sqlite exception. - /// - public class SqliteDatabase - { - public static bool IsGoodCode(int resultCode){ - return resultCode == SQLITE_OK || resultCode == SQLITE_DONE; - } - public const int SQLITE_OK = 0; - const int SQLITE_ROW = 100; - public const int SQLITE_DONE = 101; - const int SQLITE_INTEGER = 1; - const int SQLITE_FLOAT = 2; - const int SQLITE_TEXT = 3; - const int SQLITE_BLOB = 4; - const int SQLITE_NULL = 5; - public const int SQLITE_ERROR_ALREADY_OPENED = -2; - public const int SQLITE_ERROR_NOT_OPENED = -1; - - [DllImport("sqlite3.dll", EntryPoint = "sqlite3_open")] - internal static extern int sqlite3_open(string filename, out IntPtr db); - - [DllImport("sqlite3.dll", EntryPoint = "sqlite3_close")] - internal static extern int sqlite3_close(IntPtr db); - - [DllImport("sqlite3.dll", EntryPoint = "sqlite3_prepare_v2")] - internal static extern int sqlite3_prepare_v2(IntPtr db, string zSql, int nByte, out IntPtr ppStmpt, IntPtr pzTail); - - [DllImport("sqlite3.dll", EntryPoint = "sqlite3_step")] - internal static extern int sqlite3_step(IntPtr stmHandle); - - [DllImport("sqlite3.dll", EntryPoint = "sqlite3_errcode")] - internal static extern int sqlite3_errcode(IntPtr db); - - [DllImport("sqlite3.dll", EntryPoint = "sqlite3_extended_errcode")] - internal static extern int sqlite3_extended_errcode(IntPtr db); - - [DllImport("sqlite3.dll", EntryPoint = "sqlite3_changes")] - internal static extern int sqlite3_changes(IntPtr db); - - [DllImport("sqlite3.dll", EntryPoint = "sqlite3_finalize")] - internal static extern int sqlite3_finalize(IntPtr stmHandle); - - [DllImport("sqlite3.dll", EntryPoint = "sqlite3_errmsg")] - internal static extern IntPtr sqlite3_errmsg(IntPtr db); - - [DllImport("sqlite3.dll", EntryPoint = "sqlite3_column_count")] - internal static extern int sqlite3_column_count(IntPtr stmHandle); - - [DllImport("sqlite3.dll", EntryPoint = "sqlite3_column_name")] - internal static extern IntPtr sqlite3_column_name(IntPtr stmHandle, int iCol); - - [DllImport("sqlite3.dll", EntryPoint = "sqlite3_column_type")] - internal static extern int sqlite3_column_type(IntPtr stmHandle, int iCol); - - [DllImport("sqlite3.dll", EntryPoint = "sqlite3_column_int")] - internal static extern int sqlite3_column_int(IntPtr stmHandle, int iCol); - - [DllImport("sqlite3.dll", EntryPoint = "sqlite3_column_int64")] - internal static extern long sqlite3_column_int64(IntPtr stmHandle, int iCol); - - [DllImport("sqlite3.dll", EntryPoint = "sqlite3_column_text")] - internal static extern IntPtr sqlite3_column_text(IntPtr stmHandle, int iCol); - - [DllImport("sqlite3.dll", EntryPoint = "sqlite3_column_double")] - internal static extern double sqlite3_column_double(IntPtr stmHandle, int iCol); - - private IntPtr _connection; - private bool IsConnectionOpen { get; set; } - - - #region Public Methods - - public void Open(string path) - { - if (IsConnectionOpen) - { - throw new SqliteException(SQLITE_ERROR_ALREADY_OPENED,"There is already an open connection"); - } - int openResult = sqlite3_open(path, out _connection); - if (openResult != SQLITE_OK) - { - throw new SqliteException(openResult,"Could not open database file: " + path); - } - IsConnectionOpen = true; - } - - public void Close() - { - if(IsConnectionOpen) - { - sqlite3_close(_connection); - } - - IsConnectionOpen = false; - } - - public int ExecuteNonQuery(string query) - { - if (!IsConnectionOpen) - { - throw new SqliteException(SQLITE_ERROR_NOT_OPENED,"SQLite database is not open."); - } - - IntPtr stmHandle = Prepare(query); - - int result = sqlite3_step(stmHandle); - if (result != SQLITE_DONE) - { - int errorCode = sqlite3_errcode(_connection); - throw new SqliteException(errorCode,"Could not execute SQL statement.ErrorCode:" + errorCode); - } - Finalize(stmHandle); - return sqlite3_changes(_connection); - } - - public DataTable ExecuteQuery(string query) - { - if (!IsConnectionOpen) - { - throw new SqliteException(SQLITE_ERROR_NOT_OPENED,"SQLite database is not open."); - } - - IntPtr stmHandle = Prepare(query); - - int columnCount = sqlite3_column_count(stmHandle); - - var dataTable = new DataTable(); - for (int i = 0; i < columnCount; i++) - { - string columnName = Marshal.PtrToStringAnsi(sqlite3_column_name(stmHandle, i)); - dataTable.Columns.Add(columnName); - } - - //populate datatable - while (sqlite3_step(stmHandle) == SQLITE_ROW) - { - object[] row = new object[columnCount]; - for (int i = 0; i < columnCount; i++) - { - switch (sqlite3_column_type(stmHandle, i)) - { - case SQLITE_INTEGER: - row[i] = sqlite3_column_int64(stmHandle, i); - break; - - case SQLITE_TEXT: - IntPtr text = sqlite3_column_text(stmHandle, i); - row[i] = Marshal.PtrToStringAnsi(text); - break; - - case SQLITE_FLOAT: - row[i] = sqlite3_column_double(stmHandle, i); - break; - - case SQLITE_NULL: - row[i] = null; - break; - } - } - - dataTable.AddRow(row); - } - - Finalize(stmHandle); - - return dataTable; - } - - public void ExecuteScript(string script) - { - string[] statements = script.Split(';'); - - foreach (string statement in statements) - { - if (!string.IsNullOrEmpty(statement.Trim ())) - { - ExecuteNonQuery(statement); - } - } - } - - #endregion - - #region Private Methods - - private IntPtr Prepare(string query) - { - IntPtr stmHandle; - byte[] queryBytes = System.Text.Encoding.UTF8.GetBytes(query); - int trueSize = queryBytes.Length; - int resultCode = sqlite3_prepare_v2(_connection, query, trueSize, out stmHandle, IntPtr.Zero); - if (resultCode != SQLITE_OK) - { - IntPtr errorMsg = sqlite3_errmsg(_connection); - throw new SqliteException(resultCode,Marshal.PtrToStringAnsi(errorMsg) + " FullQuery=|" + query + "|"); - } - - return stmHandle; - } - - private void Finalize(IntPtr stmHandle) - { - int resultCode = sqlite3_finalize(stmHandle); - if (resultCode != SQLITE_OK) - { - throw new SqliteException(resultCode,"Could not finalize SQL statement."); - } - } - - #endregion - } - -} \ No newline at end of file + public int ErrorCode{ get { return errorCode; } } + + public SqliteException (int errorCode, string message) : base(message + "(ErrorCode:" + errorCode + ")") + { + this.errorCode = errorCode; + } + } + + /// + /// Sqlite database. + /// Get from http://gamesforsoul.com/2012/03/sqlite-unity-and-ios-a-rocky-relationship/ + /// and modified. + /// + /// + /// Is thrown when the sqlite exception. + /// + public class SqliteDatabase + { + public static bool IsGoodCode (int resultCode) + { + return resultCode == SQLITE_OK || resultCode == SQLITE_DONE; + } + + public const int SQLITE_OK = 0; + const int SQLITE_ROW = 100; + public const int SQLITE_DONE = 101; + const int SQLITE_INTEGER = 1; + const int SQLITE_FLOAT = 2; + const int SQLITE_TEXT = 3; + const int SQLITE_BLOB = 4; + const int SQLITE_NULL = 5; + public const int SQLITE_ERROR_ALREADY_OPENED = -2; + public const int SQLITE_ERROR_NOT_OPENED = -1; + + [DllImport("sqlite3.dll", EntryPoint = "sqlite3_open")] + internal static extern int sqlite3_open (string filename, out IntPtr db); + + [DllImport("sqlite3.dll", EntryPoint = "sqlite3_close")] + internal static extern int sqlite3_close (IntPtr db); + + [DllImport("sqlite3.dll", EntryPoint = "sqlite3_prepare_v2")] + internal static extern int sqlite3_prepare_v2 (IntPtr db, string zSql, int nByte, out IntPtr ppStmpt, IntPtr pzTail); + + [DllImport("sqlite3.dll", EntryPoint = "sqlite3_step")] + internal static extern int sqlite3_step (IntPtr stmHandle); + + [DllImport("sqlite3.dll", EntryPoint = "sqlite3_errcode")] + internal static extern int sqlite3_errcode (IntPtr db); + + [DllImport("sqlite3.dll", EntryPoint = "sqlite3_extended_errcode")] + internal static extern int sqlite3_extended_errcode (IntPtr db); + + [DllImport("sqlite3.dll", EntryPoint = "sqlite3_changes")] + internal static extern int sqlite3_changes (IntPtr db); + + [DllImport("sqlite3.dll", EntryPoint = "sqlite3_finalize")] + internal static extern int sqlite3_finalize (IntPtr stmHandle); + + [DllImport("sqlite3.dll", EntryPoint = "sqlite3_errmsg")] + internal static extern IntPtr sqlite3_errmsg (IntPtr db); + + [DllImport("sqlite3.dll", EntryPoint = "sqlite3_column_count")] + internal static extern int sqlite3_column_count (IntPtr stmHandle); + + [DllImport("sqlite3.dll", EntryPoint = "sqlite3_column_name")] + internal static extern IntPtr sqlite3_column_name (IntPtr stmHandle, int iCol); + + [DllImport("sqlite3.dll", EntryPoint = "sqlite3_column_type")] + internal static extern int sqlite3_column_type (IntPtr stmHandle, int iCol); + + [DllImport("sqlite3.dll", EntryPoint = "sqlite3_column_int")] + internal static extern int sqlite3_column_int (IntPtr stmHandle, int iCol); + + [DllImport("sqlite3.dll", EntryPoint = "sqlite3_column_int64")] + internal static extern long sqlite3_column_int64 (IntPtr stmHandle, int iCol); + + [DllImport("sqlite3.dll", EntryPoint = "sqlite3_column_text")] + internal static extern IntPtr sqlite3_column_text (IntPtr stmHandle, int iCol); + + [DllImport("sqlite3.dll", EntryPoint = "sqlite3_column_double")] + internal static extern double sqlite3_column_double (IntPtr stmHandle, int iCol); + + private IntPtr _connection; + + private bool IsConnectionOpen { get; set; } + + + #region Public Methods + + public void Open (string path) + { + if (IsConnectionOpen) + { + throw new SqliteException (SQLITE_ERROR_ALREADY_OPENED, "There is already an open connection"); + } + int openResult = sqlite3_open (path, out _connection); + if (openResult != SQLITE_OK) + { + throw new SqliteException (openResult, "Could not open database file: " + path); + } + IsConnectionOpen = true; + } + + public void Close () + { + if (IsConnectionOpen) + { + sqlite3_close (_connection); + } + + IsConnectionOpen = false; + } + + public int ExecuteNonQuery (string query) + { + if (!IsConnectionOpen) + { + throw new SqliteException (SQLITE_ERROR_NOT_OPENED, "SQLite database is not open."); + } + + IntPtr stmHandle = Prepare (query); + + int result = sqlite3_step (stmHandle); + if (result != SQLITE_DONE) + { + int errorCode = sqlite3_errcode (_connection); + throw new SqliteException (errorCode, "Could not execute SQL statement.ErrorCode:" + errorCode); + } + Finalize (stmHandle); + return sqlite3_changes (_connection); + } + + public DataTable ExecuteQuery (string query) + { + if (!IsConnectionOpen) + { + throw new SqliteException (SQLITE_ERROR_NOT_OPENED, "SQLite database is not open."); + } + + IntPtr stmHandle = Prepare (query); + + int columnCount = sqlite3_column_count (stmHandle); + + var dataTable = new DataTable (); + for (int i = 0; i < columnCount; i++) + { + string columnName = Marshal.PtrToStringAnsi (sqlite3_column_name (stmHandle, i)); + dataTable.Columns.Add (columnName); + } + + //populate datatable + while (sqlite3_step(stmHandle) == SQLITE_ROW) + { + object[] row = new object[columnCount]; + for (int i = 0; i < columnCount; i++) + { + switch (sqlite3_column_type (stmHandle, i)) + { + case SQLITE_INTEGER: + row [i] = sqlite3_column_int64 (stmHandle, i); + break; + + case SQLITE_TEXT: + IntPtr text = sqlite3_column_text (stmHandle, i); + row [i] = Marshal.PtrToStringAnsi (text); + break; + + case SQLITE_FLOAT: + row [i] = sqlite3_column_double (stmHandle, i); + break; + + case SQLITE_NULL: + row [i] = null; + break; + } + } + + dataTable.AddRow (row); + } + + Finalize (stmHandle); + + return dataTable; + } + + public void ExecuteScript (string script) + { + string[] statements = script.Split (';'); + + foreach (string statement in statements) + { + if (!string.IsNullOrEmpty (statement.Trim ())) + { + ExecuteNonQuery (statement); + } + } + } + + #endregion + + #region Private Methods + + private IntPtr Prepare (string query) + { + IntPtr stmHandle; + byte[] queryBytes = System.Text.Encoding.UTF8.GetBytes (query); + int trueSize = queryBytes.Length; + int resultCode = sqlite3_prepare_v2 (_connection, query, trueSize, out stmHandle, IntPtr.Zero); + if (resultCode != SQLITE_OK) + { + IntPtr errorMsg = sqlite3_errmsg (_connection); + throw new SqliteException (resultCode, Marshal.PtrToStringAnsi (errorMsg) + " FullQuery=|" + query + "|"); + } + + return stmHandle; + } + + private void Finalize (IntPtr stmHandle) + { + int resultCode = sqlite3_finalize (stmHandle); + if (resultCode != SQLITE_OK) + { + throw new SqliteException (resultCode, "Could not finalize SQL statement."); + } + } + + #endregion + } +} diff --git a/Assets/Sample.cs b/Assets/Sample.cs index 4617bb6..8390f18 100644 --- a/Assets/Sample.cs +++ b/Assets/Sample.cs @@ -4,106 +4,134 @@ using UnityORM; using System; -public class Sample : MonoBehaviour { - - // Use this for initialization - void Start () { - SqliteInit.InitSqlite(); - - - FieldLister lister = new FieldLister(); - - UserData[] data = new UserData[2]; - - data[0] = new UserData(); - data[0].ID = 1; - data[0].Name = "Tarou"; - data[0].Hoge = "fuga"; - data[0].Age = 32; - data[0].LastUpdated = new DateTime(2013,4,1); - data[0].NestedClass.Fuga = "bbbb"; - data[0].NestedClass.Hoge = 23; - - data[1] = new UserData(); - data[1].ID = 2; - data[1].Name = "Jirou"; - data[1].Hoge = "wahoo"; - data[1].Age = 11; - data[1].AddressData = "aaaaa"; - data[1].LastUpdated = new DateTime(2013,5,1); - - Debug.Log(data[0]); - - - var info = lister.ListUp(); - - Debug.Log(info); - - var sqlMaker = new SQLMaker(); - string insert = sqlMaker.GenerateInsertSQL(info,data[0]); - string update = sqlMaker.GenerateUpdateSQL(info,data[0]); - - Debug.Log("Insert = " + insert); - Debug.Log("Update = " + update); - - DBMapper mapper = new DBMapper(SqliteInit.Evolution.Database); - - mapper.UpdateOrInsertAll(data); - - UserData[] fromDb = mapper.Read("SELECT * FROM UserData;"); - Debug.Log(fromDb[0]); - Debug.Log(fromDb[1]); - - - JSONMapper jsonMapper = new JSONMapper(); - - string json = jsonMapper.Write(fromDb); - UserData[] fromJson = jsonMapper.Read(json); - - Debug.Log("Json = " + json); - - Debug.Log(fromJson[0]); - Debug.Log(fromJson[1]); - - - - } - - // Update is called once per frame - void Update () { - - } +public class Sample : MonoBehaviour +{ + // Use this for initialization + void Start () + { + SqliteInit.InitSqlite (); + } + + private UserData[] InsertUserData () + { + UserData[] data = new UserData[2]; + + data [0] = new UserData (); + data [0].ID = 1; + data [0].Name = "Tarou"; + data [0].Hoge = "fuga"; + data [0].Age = 32; + data [0].LastUpdated = new DateTime (2013, 4, 1); + data [0].NestedClass.Fuga = "bbbb"; + data [0].NestedClass.Hoge = 23; + + data [1] = new UserData (); + data [1].ID = 2; + data [1].Name = "Jirou"; + data [1].Hoge = "wahoo"; + data [1].Age = 11; + data [1].AddressData = "aaaaa"; + data [1].LastUpdated = new DateTime (2013, 5, 1); + + Debug.Log (data [0]); + + return data; + } + + private void ShowInsertQuery () + { + UserData[] data = InsertUserData (); + var sqlMaker = new SQLMaker (); + FieldLister lister = new FieldLister (); + var info = lister.ListUp (); + Debug.Log (info); + + string insert = sqlMaker.GenerateInsertSQL (info, data [0]); + Debug.Log ("Insert = " + insert); + } + + private void ShowUpdateQuery () + { + UserData[] data = InsertUserData (); + var sqlMaker = new SQLMaker (); + FieldLister lister = new FieldLister (); + var info = lister.ListUp (); + Debug.Log (info); + + string update = sqlMaker.GenerateUpdateSQL (info, data [0]); + Debug.Log ("Update = " + update); + } + + private void ShowSelectAllJSON () + { + UserData[] data = InsertUserData (); + DBMapper mapper = new DBMapper (SqliteInit.Evolution.Database); + mapper.UpdateOrInsertAll (data); + UserData[] fromDb = mapper.Read ("SELECT * FROM UserData;"); + Debug.Log (fromDb [0]); + Debug.Log (fromDb [1]); + + JSONMapper jsonMapper = new JSONMapper (); + string json = jsonMapper.Write (fromDb); + UserData[] fromJson = jsonMapper.Read (json); + Debug.Log ("Json = " + json); + Debug.Log (fromJson [0]); + Debug.Log (fromJson [1]); + } + + // Update is called once per frame + void Update () + { + } + + void OnGUI () + { + if (GUI.Button (new Rect (10, 10, 150, 50), "Insert Query")) + { + ShowInsertQuery (); + } + + if (GUI.Button (new Rect (10, 70, 150, 50), "Update Query")) + { + ShowUpdateQuery (); + } + + if (GUI.Button (new Rect (10, 130, 150, 50), "Select All JSON")) + { + ShowSelectAllJSON (); + } + } +} + +public class UserData +{ + public long ID; + public string Name; + public int Age; + + [Ignore] + public string Hoge{ get; set; } + + [MetaInfoAttirbute(NameInJSON = "address_data")] + public string AddressData{ get; set; } + + public DateTime LastUpdated; + public Nested NestedClass = new Nested (); + + public override string ToString () + { + return "ID:" + ID + " Name:" + Name + " Hoge:" + Hoge + " Age:" + Age + " Address:" + AddressData + + " LastUpdated:" + LastUpdated + " NestedClass:" + NestedClass; + } } +public class Nested +{ + public int Hoge; + public string Fuga; -public class UserData{ - public long ID; - - public string Name; - - public int Age; - - [Ignore] - public string Hoge{get;set;} - - [MetaInfoAttirbute(NameInJSON = "address_data")] - public string AddressData{get;set;} - - public DateTime LastUpdated; - - public Nested NestedClass = new Nested(); - - public override string ToString () - { - return "ID:" + ID + " Name:" + Name + " Hoge:" + Hoge + " Age:" + Age + " Address:" + AddressData + - " LastUpdated:" + LastUpdated + " NestedClass:" + NestedClass; - } + public override string ToString () + { + return "Hoge : " + Hoge + " Fuga:" + Fuga; + } } -public class Nested{ - public int Hoge; - public string Fuga; - public override string ToString () - { - return "Hoge : " + Hoge + " Fuga:" + Fuga; - } -} \ No newline at end of file diff --git a/Assets/SqliteInit.cs b/Assets/SqliteInit.cs index 83c9a49..8fb3273 100644 --- a/Assets/SqliteInit.cs +++ b/Assets/SqliteInit.cs @@ -1,6 +1,4 @@ using System; - - using UnityEngine; using System.IO; using UnityORM; @@ -8,43 +6,41 @@ public static class SqliteInit { - public static DBEvolution Evolution; - - static bool alreadyInited = false; - - public static void InitSqlite(){ - - if(alreadyInited)return; - alreadyInited = true; - - Evolution = new DBEvolution( - Path.Combine(Application.persistentDataPath,"sample_data.db")); - - Evolution.RecreateTableIfHashDiffers = true;// You shoud set false when you release application to avoid suddon drop table. - - // Init table - Evolution.Evolute("SampleTable",// Traget table - new List(){ // These sql is executed at once. - @"CREATE TABLE SampleTable(id INTEGER,nickname TEXT,lastLogin INTEGER, score FLOAT);", - @"ALTER TABLE SampleTable ADD COLUMN age INTEGER;" - }); - - Evolution.Evolute("OtherTable", - new List(){ - @"CREATE TABLE OtherTable(key TEXT,val TEXT);", - @"INSERT INTO OtherTable VALUES ('a','b')" - }); - - Evolution.Evolute("UserData", - new List(){ - //@"CREATE TABLE UserData(id INTEGER PRIMARY_KEY,name TEXT,hoge TEXT); " - new SQLMaker().GenerateCreateTableSQL(ClassDescRepository.Instance.GetClassDesc()) + " " - }); - - - } - -} + public static DBEvolution Evolution; + static bool alreadyInited = false; + + public static void InitSqlite () + { + if (alreadyInited) + { + return; + } + alreadyInited = true; + string path = Application.dataPath + "/StreamingAssets"; + Evolution = new DBEvolution ( + //Path.Combine(Application.persistentDataPath,"sample_data.db")); + Path.Combine (path, "sample_data.db")); + Evolution.RecreateTableIfHashDiffers = true;// You shoud set false when you release application to avoid suddon drop table. + // Init table + Evolution.Evolute ("SampleTable",// Traget table + new List (){ // These sql is executed at once. + @"CREATE TABLE SampleTable(id INTEGER,nickname TEXT,lastLogin INTEGER, score FLOAT);", + @"ALTER TABLE SampleTable ADD COLUMN age INTEGER;" + }); + + Evolution.Evolute ("OtherTable", + new List (){ + @"CREATE TABLE OtherTable(key TEXT,val TEXT);", + @"INSERT INTO OtherTable VALUES ('a','b')" + }); + + Evolution.Evolute ("UserData", + new List (){ + //@"CREATE TABLE UserData(id INTEGER PRIMARY_KEY,name TEXT,hoge TEXT); " + new SQLMaker().GenerateCreateTableSQL(ClassDescRepository.Instance.GetClassDesc()) + " " + }); + } +}