com.guru.unity.sdk.core/Runtime/GuruLibs/Datebase/DBService.cs

190 lines
4.9 KiB
C#

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;
/// <summary>
/// 获取数据库的路径
/// </summary>
public string DatabasePath => _dbPath;
/// <summary>
/// 启动服务
/// </summary>
/// <param name="name"></param>
/// <param name="isDebug"></param>
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;
}
/// <summary>
/// 关闭连接
/// </summary>
public void Close() => _connection?.Close();
/// <summary>
/// 建立连接, 若不存在则创建数据库
/// </summary>
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);
/// <summary>
/// 部署默认的 Database
/// 将内置在 StreamingAssets 中的数据库文件部署到 PersistentDataPath 中
/// </summary>
/// <returns></returns>
public void DeployEmbeddedDB(string embeddedPath, Action<bool> 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);
};
}
/// <summary>
/// 获取表格
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public IEnumerable<T> CreatOrLoadTable<T>() where T: new()
{
_connection.CreateTable<T>();
return _connection.Table<T>();
}
public List<T> GetTableList<T>() where T: new()
{
var tb = CreatOrLoadTable<T>();
return tb?.ToList() ?? new List<T>();
}
public int Insert<T>(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<T>(object primaryKey)
{
return _connection.Delete<T>(primaryKey);
}
public int UpdateAll(IEnumerable data)
{
return _connection.UpdateAll(data);
}
public T Get<T>(object primaryKey) where T : new()
{
return _connection.Get<T>(primaryKey);
}
public T Find<T>(Expression<Func<T, bool>> predicate) where T : new()
{
return _connection.Find<T>(predicate);
}
private bool _onCmdExecution = false;
/// <summary>
/// 执行 SQL 语句
/// </summary>
/// <param name="query"></param>
/// <param name="onExecutionComplete"></param>
/// <param name="args"></param>
/// <returns></returns>
public int Execute(string query, Action<double> 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);
}
}
}