You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Zero/ZeroLevel.SqLite/BaseSqLiteDB.cs

119 lines
3.0 KiB

2 years ago
using SQLite;
using System;
using System.Collections.Generic;
5 years ago
using System.IO;
2 years ago
using System.Linq.Expressions;
5 years ago
using ZeroLevel.Services.FileSystem;
namespace ZeroLevel.SqLite
{
2 years ago
public abstract class BaseSqLiteDB<T>
: IDisposable
where T : class, new()
5 years ago
{
2 years ago
protected SQLiteConnection _db;
public BaseSqLiteDB(string name)
5 years ago
{
2 years ago
_db = new SQLiteConnection(PrepareDb(name));
5 years ago
}
2 years ago
2 years ago
public int Append(T record)
5 years ago
{
2 years ago
return _db.Insert(record);
5 years ago
}
2 years ago
2 years ago
public CreateTableResult CreateTable()
5 years ago
{
2 years ago
return _db.CreateTable<T>();
5 years ago
}
2 years ago
public int DropTable()
5 years ago
{
2 years ago
return _db.DropTable<T>();
5 years ago
}
2 years ago
public IEnumerable<T> SelectAll()
5 years ago
{
2 years ago
return _db.Table<T>();
}
public IEnumerable<T> SelectBy(Expression<Func<T, bool>> predicate)
{
return _db.Table<T>().Where(predicate);
}
public T Single(Expression<Func<T, bool>> predicate)
{
return _db.Table<T>().FirstOrDefault(predicate);
}
public T Single<U>(Expression<Func<T, bool>> predicate, Expression<Func<T, U>> orderBy, bool desc = false)
{
if (desc)
5 years ago
{
2 years ago
return _db.Table<T>().Where(predicate).OrderByDescending(orderBy).FirstOrDefault();
5 years ago
}
2 years ago
return _db.Table<T>().Where(predicate).OrderBy(orderBy).FirstOrDefault();
5 years ago
}
2 years ago
public T Single<U>(Expression<Func<T, U>> orderBy, bool desc = false)
5 years ago
{
2 years ago
if (desc)
5 years ago
{
2 years ago
return _db.Table<T>().OrderByDescending(orderBy).FirstOrDefault();
5 years ago
}
2 years ago
return _db.Table<T>().OrderBy(orderBy).FirstOrDefault();
}
public IEnumerable<T> SelectBy(int N, Expression<Func<T, bool>> predicate)
{
return _db.Table<T>().Where(predicate).Take(N);
}
public long Count()
{
return _db.Table<T>().Count();
}
public long Count(Expression<Func<T, bool>> predicate)
{
return _db.Table<T>().Count(predicate);
}
public int Delete(Expression<Func<T, bool>> predicate)
{
return _db.Table<T>().Delete(predicate);
}
2 years ago
public int Update(T record)
2 years ago
{
2 years ago
return _db.Update(record);
5 years ago
}
protected static string PrepareDb(string path)
{
if (Path.IsPathRooted(path) == false)
{
path = Path.Combine(FSUtils.GetAppLocalDbDirectory(), path);
}
return Path.GetFullPath(path);
}
2 years ago
protected abstract void DisposeStorageData();
public void Dispose()
{
DisposeStorageData();
try
{
_db?.Close();
_db?.Dispose();
}
catch (Exception ex)
{
Log.Error(ex, "[BaseSqLiteDB] Fault close db connection");
}
}
5 years ago
}
}

Powered by TurnKey Linux.