RSND/RSND/Core/Database.cs

87 lines
2.1 KiB
C#
Raw Normal View History

2022-06-01 22:24:42 +00:00
using Newtonsoft.Json;
2022-06-02 18:07:45 +00:00
using Pastel;
2022-06-01 22:24:42 +00:00
using RSND.Core.DbInternals;
using RSND.Core.Querying.Queries;
namespace RSND.Core;
public class Database
{
2022-06-02 19:55:16 +00:00
private string Name { get; set; }
private List<Table> _tables = new();
2022-06-01 22:24:42 +00:00
2022-06-02 19:55:16 +00:00
public Database(string name)
{
Name = name;
}
public void SetupFiles()
{
if (File.Exists($"{Name}.json"))
{
Console.WriteLine($"[{Name}] The file exists.");
2022-06-02 19:55:16 +00:00
var json = File.ReadAllText($"{Name}.json");
var db = JsonConvert.DeserializeObject<List<Table>>(json);
if (db != null)
_tables = db;
}
else
{
Console.WriteLine($"[{Name}] The file is getting created.");
2022-06-02 19:55:16 +00:00
File.Create($"{Name}.json");
}
}
public void Save()
{
try
{
var json = JsonConvert.SerializeObject(_tables);
File.WriteAllText($"{Name}.json", json);
}
catch
{
// slim chance there might be file structure issues.
// let's attempt to fix that.
SetupFiles();
}
2022-06-02 19:55:16 +00:00
}
2022-06-02 18:07:45 +00:00
public void CreateTable(Table query)
2022-06-01 22:24:42 +00:00
{
2022-06-02 19:55:16 +00:00
if (_tables.Any(x => x.Name == query.Name))
2022-06-02 18:07:45 +00:00
{
2022-06-02 19:55:16 +00:00
_tables.RemoveAll(x => x.Name == query.Name);
2022-06-02 18:07:45 +00:00
}
2022-06-02 19:55:16 +00:00
_tables.Add(query);
Save();
2022-06-01 22:24:42 +00:00
}
public string GetValue(GetQuery? query)
{
2022-06-02 19:55:16 +00:00
Console.WriteLine(_tables.Count.ToString().Pastel("#ff0000"));
2022-06-01 22:24:42 +00:00
var table = query?.Table;
var where = query?.Where;
var split = where?.Split("|");
var colName = split?[0];
var condition = split?[1];
2022-06-02 19:55:16 +00:00
var value = split?[2];
2022-06-01 22:24:42 +00:00
if (query?.Select != "*") return "";
2022-06-02 19:55:16 +00:00
var tableToReturn = _tables.Find(x => x.Name == table);
var rows = tableToReturn?.Rows?.Where(x => x.Columns?.FirstOrDefault(y => y.Name == colName)?.Value == value).ToArray();
2022-06-02 21:04:46 +00:00
return JsonConvert.SerializeObject(rows);
2022-06-01 22:24:42 +00:00
}
2022-06-02 18:07:45 +00:00
2022-06-01 22:24:42 +00:00
public static void Loop()
{
while (true)
{
2022-06-02 18:07:45 +00:00
2022-06-01 22:24:42 +00:00
}
}
}