namespace Guru { using SQLite4Unity3d; using UnityEngine; using System.Collections; using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using UnityEngine.Networking; public class DBService { internal const string DefaultDBName = "data"; internal const string DefaultDBExtension = ".db"; internal static string DebugDBPath = "mocks_dir/db"; private SQLiteConnection _connection; private string _dbName; private string _dbPath; private bool _isDebug = false; /// /// 获取数据库的路径 /// public string DatabasePath => _dbPath; /// /// 启动服务 /// /// /// public DBService(string name, bool isDebug = false) { _isDebug = isDebug; if (string.IsNullOrEmpty(name)) name = DefaultDBName; _dbName = name; _dbPath = Path.GetFullPath($"{Application.persistentDataPath}/{_dbName}{DefaultDBExtension}"); if (isDebug) { _dbPath = Path.GetFullPath($"{Application.persistentDataPath}/{_dbName}_debug{DefaultDBExtension}"); } } public static DBService Open(string name, bool isDebug = false) { var ds = new DBService(name, isDebug); ds.Connect(); return ds; } /// /// 关闭连接 /// public void Close() => _connection?.Close(); /// /// 建立连接, 若不存在则创建数据库 /// public void Connect(string dbPath = "") { if(!string.IsNullOrEmpty(dbPath)) _dbPath = dbPath; _connection = new SQLiteConnection(_dbPath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create); } public bool Exists => File.Exists(_dbPath); /// /// 部署默认的 Database /// 将内置在 StreamingAssets 中的数据库文件部署到 PersistentDataPath 中 /// /// public void DeployEmbeddedDB(string embeddedPath, Action onComplete) { string from = Path.Combine(Application.streamingAssetsPath, embeddedPath); var uwr = new UnityWebRequest(from); uwr.SendWebRequest().completed += ao => { var success = false; try { if ( uwr.result == UnityWebRequest.Result.Success) { File.WriteAllBytes(_dbPath, uwr.downloadHandler.data); success = true; } } catch (Exception e) { Debug.LogError(e); } onComplete?.Invoke(success); }; } /// /// 获取表格 /// /// /// public IEnumerable CreatOrLoadTable() where T: new() { _connection.CreateTable(); return _connection.Table(); } public List GetTableList() where T: new() { var tb = CreatOrLoadTable(); return tb?.ToList() ?? new List(); } public int Insert(T value) { return _connection.Insert(value); } public int InsertAll(IEnumerable data) { return _connection.InsertAll(data); } public int Remove(object primaryKey) { return _connection.Delete(primaryKey); } public int Remove(object primaryKey) { return _connection.Delete(primaryKey); } public int UpdateAll(IEnumerable data) { return _connection.UpdateAll(data); } public T Get(object primaryKey) where T : new() { return _connection.Get(primaryKey); } public T Find(Expression> predicate) where T : new() { return _connection.Find(predicate); } private bool _onCmdExecution = false; /// /// 执行 SQL 语句 /// /// /// /// /// public int Execute(string query, Action onExecutionComplete = null, params object[] args) { if (_onCmdExecution) return -1; SQLiteConnection.TimeExecutionHandler del = null; del = (t1, t2) => { _onCmdExecution = false; _connection.TimeExecutionEvent -= del; onExecutionComplete?.Invoke(t2.TotalSeconds); }; _connection.TimeExecutionEvent += del; _onCmdExecution = true; return _connection.Execute(query, args); } } }