BuecherwurmAPI/Models/Repository.cs
2020-06-02 11:16:45 +02:00

98 lines
No EOL
3.4 KiB
C#

using System;
using System.Collections.Generic;
using BuecherwurmAPI.Models;
using Microsoft.Data.Sqlite;
using Microsoft.VisualBasic.CompilerServices;
namespace BuecherwurmAPI.Models
{
internal class Repository : IRepository
{
private SqliteConnection _dbConnection;
public Repository()
{
var connectionBuilder = new SqliteConnectionStringBuilder {DataSource = "LongWormMemory.db"};
_dbConnection = new SqliteConnection(connectionBuilder.ConnectionString);
_dbConnection.Open();
}
public bool IdExits(string table, long id)
{
using (var command = _dbConnection.CreateCommand())
{
command.Parameters.Add(new SqliteParameter("@Id", SqliteType.Integer)).Value = id;
// Certain parts of the query can't be filled with variables for security reasons.
switch (table)
{
case Tables.Table.Lends:
command.CommandText = @"SELECT EXISTS(SELECT 0 FROM Lends WHERE Id = @Id)";
break;
}
var dr = command.ExecuteReader();
long result = 0;
while (dr.Read())
{
result = (long) dr[0];
}
return result != 0;
}
}
public IEnumerable<Lend> GetAllLends()
{
var lends = new List<Lend>();
// using automatically disposes the command after completion
using (var command = _dbConnection.CreateCommand())
{
command.CommandText = @"SELECT * FROM Lends";
var dataReader = command.ExecuteReader();
while (dataReader.Read())
{
var returned = (long) dataReader["Returned"] == 1;
lends.Add(new Lend
{
Id = (long) dataReader["Id"],
Customer = (string) dataReader["Customer"],
ItemId = (long) dataReader["ItemId"],
Returned = returned,
ReturnDate = DateTime.Parse((string)dataReader["ReturnDate"])
});
}
}
return lends;
}
public Lend GetLendById(long id)
{
using (var command = _dbConnection.CreateCommand())
{
command.Parameters.Add(new SqliteParameter("@id", SqliteType.Integer)).Value = id;
command.CommandText = @"SELECT * FROM Lends WHERE Id = @id";
var dataReader = command.ExecuteReader();
while (dataReader.Read())
{
var returned = (long) dataReader["Returned"] == 1;
var lend = new Lend
{
Id = (long) dataReader["Id"],
Customer = (string) dataReader["Customer"],
ItemId = (long) dataReader["ItemId"],
Returned = returned,
ReturnDate = DateTime.Parse((string) dataReader["ReturnDate"])
};
return lend;
}
}
return null;
}
}
}