Skip to content

add support for PostgreSQL #72

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ public void Execute()
{
using (var cmd = _connection.CreateCommand())
{
//TODO: # not support in Coderr.Server.PostgreSQL but need a procedure or view in this case.
var sql = $@"CREATE TABLE #Incidents (Id int NOT NULL PRIMARY KEY, NumberOfItems int)
INSERT #Incidents (Id, NumberOfItems)
SELECT TOP(100) IncidentId, Count(Id) - @max
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,8 @@ public override void Store(IConfigurationSection section)
{
cmd.CommandText +=
string.Format(
"INSERT INTO Settings (Section, Name, Value) VALUES(@section, @name{0}, @value{0})",
index);
"INSERT INTO Settings (Section, Name, Value) VALUES(@section, @name{0}, @value{0});",
index) ;
cmd.AddParameter("name" + index, kvp.Key);
cmd.AddParameter("value" + index, kvp.Value);
++index;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Data;
using System.Security.Claims;

namespace Coderr.Server.Infrastructure
{
Expand All @@ -19,7 +20,7 @@ public interface ISetupDatabaseTools
/// </summary>
/// <returns>Connection</returns>
IDbConnection OpenConnection();

IDbConnection GetConnection(string connectionString, ClaimsPrincipal arg);
void TestConnection(string connectionString);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<RootNamespace>Coderr.Server.PostgreSQL</RootNamespace>
<AssemblyName>Coderr.Server.PostgreSQL</AssemblyName>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DotNetCqs" Version="2.0.14" />
<PackageReference Include="Griffin.Framework" Version="2.1.1" />
<PackageReference Include="log4net" Version="2.0.8" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
<PackageReference Include="Npgsql" Version="4.1.1" />
<PackageReference Include="System.Data.SqlClient" Version="4.7.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Coderr.Server.Api\Coderr.Server.Api.csproj" />
<ProjectReference Include="..\Coderr.Server.App\Coderr.Server.App.csproj" />
<ProjectReference Include="..\Coderr.Server.Domain\Coderr.Server.Domain.csproj" />
<ProjectReference Include="..\Coderr.Server.Infrastructure\Coderr.Server.Infrastructure.csproj" />
<ProjectReference Include="..\Coderr.Server.Abstractions\Coderr.Server.Abstractions.csproj" />
<ProjectReference Include="..\Coderr.Server.ReportAnalyzer.Abstractions\Coderr.Server.ReportAnalyzer.Abstractions.csproj" />
<ProjectReference Include="..\Coderr.Server.ReportAnalyzer\Coderr.Server.ReportAnalyzer.csproj" />
</ItemGroup>

<ItemGroup>
<EmbeddedResource Include="Schema\*.sql" />
</ItemGroup>

</Project>
25 changes: 25 additions & 0 deletions src/Server/Coderr.Server.PostgreSQL/Core/Accounts/AccountMapper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using System;
using Coderr.Server.Domain.Core.Account;
using Griffin.Data.Mapper;

namespace Coderr.Server.PostgreSQL.Core.Accounts
{
public class AccountMapper : CrudEntityMapper<Account>
{
public AccountMapper() : base("Accounts")
{
Property(x => x.Id)
.PrimaryKey(true);

Property(x => x.AccountState)
.ToPropertyValue(o => (AccountState) Enum.Parse(typeof(AccountState), (string) o, true))
.ToColumnValue(o => o.ToString());

Property(x => x.UpdatedAtUtc)
.ToColumnValue(DbConverters.ToSqlNull);

Property(x => x.LastLoginAtUtc)
.ToColumnValue(DbConverters.ToSqlNull);
}
}
}
230 changes: 230 additions & 0 deletions src/Server/Coderr.Server.PostgreSQL/Core/Accounts/AccountRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Threading.Tasks;
using Coderr.Server.Abstractions.Boot;
using Coderr.Server.Domain.Core.Account;
using Coderr.Server.ReportAnalyzer.Abstractions;
using Griffin.Data;
using Griffin.Data.Mapper;
using log4net;

namespace Coderr.Server.PostgreSQL.Core.Accounts
{
[ContainerService]
public class AccountRepository : IAccountRepository
{
private readonly IAdoNetUnitOfWork _uow;
private ILog _logger = LogManager.GetLogger(typeof(AccountRepository));

public AccountRepository(IAdoNetUnitOfWork uow)
{
_uow = uow ?? throw new ArgumentNullException(nameof(uow));
LogManager.GetLogger(typeof(AccountRepository)).Info("UOW hash: " + _uow.GetHashCode());
}

/// <inheritdoc />
public Task<int> CountAsync()
{
return Task.FromResult((int)_uow.ExecuteScalar("SELECT CAST(count(*) as int) FROM Accounts;"));
}


/// <inheritdoc />
public async Task CreateAsync(Account account)
{
await _uow.InsertAsync(account);
}

/// <inheritdoc />
public async Task<Account> FindByActivationKeyAsync(string activationKey)
{
using (var cmd = _uow.CreateCommand())
{
cmd.CommandText = "SELECT * FROM Accounts WHERE ActivationKey=@key;";
cmd.AddParameter("key", activationKey);
var accounts= await cmd.ToListAsync(new AccountMapper());
if (accounts.Count == 0)
return null;

_logger.Error($"Found {accounts.Count} accounts, expected one.");
return accounts.First();
}
}

/// <inheritdoc />
public async Task UpdateAsync(Account account)
{
using (var cmd = (DbCommand) _uow.CreateCommand())
{
cmd.CommandText =
"UPDATE Accounts SET " +
" Username = @Username, " +
" HashedPassword = @HashedPassword, " +
" Salt = @Salt, " +
" CreatedAtUtc = @CreatedAtUtc, " +
" AccountState = @AccountState, " +
" Email = @Email, " +
" UpdatedAtUtc = @UpdatedAtUtc, " +
" ActivationKey = @ActivationKey, " +
" LoginAttempts = @LoginAttempts, " +
" LastLoginAtUtc = @LastLoginAtUtc " +
"WHERE Id = @Id;";
cmd.AddParameter("@Id", account.Id);
cmd.AddParameter("@Username", account.UserName);
cmd.AddParameter("@HashedPassword", account.HashedPassword);
cmd.AddParameter("@Salt", account.Salt);
cmd.AddParameter("@CreatedAtUtc", account.CreatedAtUtc);
cmd.AddParameter("@AccountState", account.AccountState.ToString());
cmd.AddParameter("@Email", account.Email);
cmd.AddParameter("@UpdatedAtUtc",
account.UpdatedAtUtc == DateTime.MinValue ? (object) null : account.UpdatedAtUtc);
cmd.AddParameter("@ActivationKey", account.ActivationKey);
cmd.AddParameter("@LoginAttempts", account.LoginAttempts);
cmd.AddParameter("@LastLoginAtUtc",
account.LastLoginAtUtc == DateTime.MinValue ? (object) null : account.LastLoginAtUtc);
await cmd.ExecuteNonQueryAsync();
}
}

/// <inheritdoc />
public async Task<Account> FindByUserNameAsync(string userName)
{
if (userName == null) throw new ArgumentNullException(nameof(userName));

using (var cmd = (DbCommand) _uow.CreateCommand())
{
cmd.CommandText = "SELECT TOP 1 * FROM Accounts WHERE UserName=@uname;";
cmd.AddParameter("uname", userName);
return await cmd.FirstOrDefaultAsync(new AccountMapper());
}
}

public async Task<Account> GetByIdAsync(int id)
{
if (id <= 0) throw new ArgumentNullException(nameof(id));

using (var cmd = _uow.CreateCommand())
{
cmd.CommandText = "SELECT * FROM Accounts WHERE Id=@id;";
cmd.AddParameter("id", id);
return await cmd.FirstAsync<Account>();
}
}

/// <inheritdoc />
public async Task<Account> FindByEmailAsync(string emailAddress)
{
if (emailAddress == null) throw new ArgumentNullException(nameof(emailAddress));

using (var cmd = _uow.CreateCommand())
{
cmd.CommandText = "SELECT * FROM Accounts WHERE Email=@email;";
cmd.AddParameter("email", emailAddress);
return await cmd.FirstOrDefaultAsync(new AccountMapper());
}
}

/// <inheritdoc />
public async Task<IEnumerable<Account>> GetByIdAsync(int[] ids)
{
if (ids == null) throw new ArgumentNullException(nameof(ids));

using (var cmd = (DbCommand) _uow.CreateCommand())
{
var idStr = string.Join(",", ids.Select(x => "'" + x + "'"));
cmd.CommandText = $"SELECT * FROM Accounts WHERE Id IN ({idStr});";
return await cmd.ToListAsync<Account>();
}
}


/// <inheritdoc />
public async Task<bool> IsEmailAddressTakenAsync(string email)
{
if (email == null) throw new ArgumentNullException(nameof(email));

using (var cmd = _uow.CreateDbCommand())
{
cmd.CommandText = "SELECT TOP 1 Email FROM Accounts WHERE Email = @Email;";
cmd.AddParameter("Email", email);
var result = await cmd.ExecuteScalarAsync();
return result != null && result != DBNull.Value;
}
}


/// <inheritdoc />
public async Task<bool> IsUserNameTakenAsync(string userName)
{
if (userName == null) throw new ArgumentNullException(nameof(userName));

using (var cmd = _uow.CreateDbCommand())
{
cmd.CommandText = "SELECT TOP 1 UserName FROM Accounts WHERE UserName = @userName;";
cmd.AddParameter("userName", userName);
var result = await cmd.ExecuteScalarAsync();
return result != null && result != DBNull.Value;
}
}

public void Create(Account account)
{
if (account == null) throw new ArgumentNullException(nameof(account));
using (var cmd = _uow.CreateCommand())
{
//for systems where ID must be specified
if (account.Id > 0)
{
cmd.CommandText =
"INSERT INTO Accounts (Id, Username, HashedPassword, Salt, CreatedAtUtc, AccountState, Email, UpdatedAtUtc, ActivationKey, LoginAttempts, LastLoginAtUtc) " +
" VALUES(@Id, @Username, @HashedPassword, @Salt, @CreatedAtUtc, @AccountState, @Email, @UpdatedAtUtc, @ActivationKey, @LoginAttempts, @LastLoginAtUtc); RETURNING Id;";
cmd.AddParameter("id", account.Id);

}
else
{
cmd.CommandText =
"INSERT INTO Accounts (Username, HashedPassword, Salt, CreatedAtUtc, AccountState, Email, UpdatedAtUtc, ActivationKey, LoginAttempts, LastLoginAtUtc) " +
" VALUES(@Username, @HashedPassword, @Salt, @CreatedAtUtc, @AccountState, @Email, @UpdatedAtUtc, @ActivationKey, @LoginAttempts, @LastLoginAtUtc); RETURNING Id;";
}
cmd.AddParameter("@Username", account.UserName);
cmd.AddParameter("@HashedPassword", account.HashedPassword);
cmd.AddParameter("@Salt", account.Salt);
cmd.AddParameter("@CreatedAtUtc", account.CreatedAtUtc);
cmd.AddParameter("@AccountState", account.AccountState.ToString());
cmd.AddParameter("@Email", account.Email);
cmd.AddParameter("@UpdatedAtUtc",
account.UpdatedAtUtc == DateTime.MinValue ? (object) null : account.UpdatedAtUtc);
cmd.AddParameter("@ActivationKey", account.ActivationKey);
cmd.AddParameter("@LoginAttempts", account.LoginAttempts);
cmd.AddParameter("@LastLoginAtUtc",
account.LastLoginAtUtc == DateTime.MinValue ? (object) null : account.LastLoginAtUtc);

if (account.Id > 0)
{
cmd.ExecuteNonQuery();
}
else
{
var value = (int) cmd.ExecuteScalar();
account.GetType().GetProperty("Id").SetValue(account, value);
}
}
}

public async Task<Account> GetByUserNameAsync(string userName)
{
if (userName == null) throw new ArgumentNullException(nameof(userName));

using (var cmd = _uow.CreateCommand())
{
cmd.CommandText = "SELECT * FROM Accounts WHERE UserName=@userName;";
cmd.AddParameter("userName", userName);
return await cmd.FirstAsync(new AccountMapper());
}
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System;
using System.Threading.Tasks;
using Coderr.Server.Api.Core.Accounts.Queries;
using Coderr.Server.Domain.Core.Account;
using DotNetCqs;
using Coderr.Server.ReportAnalyzer.Abstractions;

namespace Coderr.Server.PostgreSQL.Core.Accounts.QueryHandlers
{
public class GetAccountEmailByIdHandler : IQueryHandler<GetAccountEmailById, string>
{
private readonly IAccountRepository _accountRepository;

public GetAccountEmailByIdHandler(IAccountRepository accountRepository)
{
if (accountRepository == null) throw new ArgumentNullException(nameof(accountRepository));
_accountRepository = accountRepository;
}

public async Task<string> HandleAsync(IMessageContext context, GetAccountEmailById query)
{
var usr = await _accountRepository.GetByIdAsync((int) query.AccountId);
return usr.Email;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System.Threading.Tasks;
using Coderr.Server.Api.Core.Accounts.Queries;
using DotNetCqs;
using Griffin.Data;
using Griffin.Data.Mapper;

namespace Coderr.Server.PostgreSQL.Core.Accounts.QueryHandlers
{
public class ListAccountsHandler : IQueryHandler<ListAccounts, ListAccountsResult>
{
private readonly IAdoNetUnitOfWork _unitOfWork;
private static readonly IEntityMapper<ListAccountsResultItem> _mapper = new MirrorMapper<ListAccountsResultItem>();

public ListAccountsHandler(IAdoNetUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}

public async Task<ListAccountsResult> HandleAsync(IMessageContext context, ListAccounts query)
{
var sql = "SELECT Id AccountId, UserName, CreatedAtUtc, Email FROM Accounts;";
var users = await _unitOfWork.ToListAsync(_mapper, sql);
return new ListAccountsResult() { Accounts = users.ToArray() };
}
}
}
Loading