ose-net / yesql.net

YeSQL.NET is a class library for loading SQL statements from .sql files instead of writing SQL code in your C# source files

Home Page:https://ose-net.github.io/yesql.net

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support for multi database?

mike7ang1rdz opened this issue · comments

Hi.
I have a solution which Select the db engine depending on the environment... Is there a native configuration or db switch?

Thanks

Hello @mike7ang1rdz,

YeSQL.NET is not as such an ORM that allows support for multiple databases, however, there is a "trick" that can be applied to your situation. In your case, you need to create an abstraction layer that includes the repositories and each would have its own associated SQL file.

I will assume this is your project structure (is an example):

└── MyApp/
    ├── Contracts/
    │   ├── IUserRepository.cs
    │   └── IProductRepository.cs
    ├── Infrastructure/
    │   ├── SQLServer/
    │   │   ├── Users/
    │   │   │   ├── UserRepository.cs
    │   │   │   └── users.sql
    │   │   └── Products/
    │   │       ├── ProductRepository.cs
    │   │       └── products.sql
    │   └── SQLite/
    │       ├── Users/
    │       │   ├── UserRepository.cs
    │       │   └── users.sql
    │       └── Products/
    │           ├── ProductRepository.cs
    │           └── products.sql
    ├── Program.cs
    └── MyApp.csproj

The next step is to obtain the path where the SQL files are located depending on the name of the environment (if it is development or production), for example:

// This would go in Program.cs
// Obtain the environment name.
string environment = Environment.GetEnvironmentVariable("APP_ENVIRONMENT") ?? "Development";

// Obtain part of the route according to the environment.
string route = environment switch 
{
     "Development" => "Infrastructure/SQLite"
     "Production" => "Infrastructure/SQLServer",
      _ => throw new NotSupportedException("Unsupported environment");
};

// Prepare the complete route.
string[] paths = new[]
{
     Path.Combine(Directory.GetCurrentDirectory(), route)
};

// Load the SQL statements depending on the path previously obtained.
var loader = new YeSqlLoader();
ISqlCollection sqlCollection = loader.LoadFromDirectories(paths);

I'm not sure if your application is a web application, but if it is, Directory.GetCurrentDirectory() should return the root directory of the project (in this example it would be from MyApp/).

I hope you get the idea. This is the solution I can think of so far. Let me know if you have any questions.

Were you able to solve it? @mike7ang1rdz

thanks for your time nice approach