Skip to content

Commit

Permalink
feat:add db persistance.(on development).
Browse files Browse the repository at this point in the history
  • Loading branch information
arthuridea committed Mar 5, 2024
1 parent bfe8ca9 commit 437c1e0
Show file tree
Hide file tree
Showing 16 changed files with 1,068 additions and 0 deletions.
14 changes: 14 additions & 0 deletions NetCore.AIGC.sln
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LLMService.OpenAI.ChatGPT",
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "02.Sample", "02.Sample", "{0B000384-47E8-4013-A1CE-59A465017EF2}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LLMService.DataProvider.Relational", "src\LLMService.DataProvider.Relational\LLMService.DataProvider.Relational.csproj", "{3B8B2207-56F2-4D98-858F-7BAB3858CD74}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LLMService.DataProvider.Migrator", "src\LLMService.DataProvider.Migrator\LLMService.DataProvider.Migrator.csproj", "{E2CC4393-ABF1-400F-A9B2-A56F99A2285E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -60,6 +64,14 @@ Global
{09322116-1405-47CE-BBB5-35E02167905D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{09322116-1405-47CE-BBB5-35E02167905D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{09322116-1405-47CE-BBB5-35E02167905D}.Release|Any CPU.Build.0 = Release|Any CPU
{3B8B2207-56F2-4D98-858F-7BAB3858CD74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3B8B2207-56F2-4D98-858F-7BAB3858CD74}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3B8B2207-56F2-4D98-858F-7BAB3858CD74}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3B8B2207-56F2-4D98-858F-7BAB3858CD74}.Release|Any CPU.Build.0 = Release|Any CPU
{E2CC4393-ABF1-400F-A9B2-A56F99A2285E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E2CC4393-ABF1-400F-A9B2-A56F99A2285E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E2CC4393-ABF1-400F-A9B2-A56F99A2285E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E2CC4393-ABF1-400F-A9B2-A56F99A2285E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -70,6 +82,8 @@ Global
{E73CB18F-26D3-4A6C-8AA2-E89FF17B65C5} = {01705FE5-59E6-4B65-B545-5DFD3AFB1F16}
{E3AE89E4-31A0-4EDA-9154-2D089E1FD8A4} = {01705FE5-59E6-4B65-B545-5DFD3AFB1F16}
{09322116-1405-47CE-BBB5-35E02167905D} = {01705FE5-59E6-4B65-B545-5DFD3AFB1F16}
{3B8B2207-56F2-4D98-858F-7BAB3858CD74} = {01705FE5-59E6-4B65-B545-5DFD3AFB1F16}
{E2CC4393-ABF1-400F-A9B2-A56F99A2285E} = {01705FE5-59E6-4B65-B545-5DFD3AFB1F16}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4FD3BE39-36D7-4A01-8EEC-39063ED813B4}
Expand Down
81 changes: 81 additions & 0 deletions src/LLMService.DataProvider.Migrator/ChatDbContextFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
using LLMService.DataProvider.Relational.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using Org.BouncyCastle.Tls;

namespace LLMService.DataProvider.Migrator
{
/// <summary>
///
/// </summary>
internal class ChatDbContextFactory : ChatDbContextFactoryGeneric<ChatDbContext>
{
}

/// <summary>
///
/// </summary>
/// <seealso cref="Microsoft.EntityFrameworkCore.Design.IDesignTimeDbContextFactory{TContext}" />
internal class ChatDbContextFactoryGeneric<TContext> : IDesignTimeDbContextFactory<TContext>
where TContext : DbContext
{
const string connectionKey = "DbConnection";
const string assemblyName = "LLMService.DataProvider.Migrator";

/// <summary>
/// Creates a new instance of a derived context.
/// </summary>
/// <param name="args">Arguments provided by the design-time service.</param>
/// <returns>
/// An instance of <typeparamref name="TContext" />.
/// </returns>
public TContext CreateDbContext(string[] args)
{
//
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddCommandLine(args)
.Build();
var dbContextBuilder = new DbContextOptionsBuilder<TContext>();
var connectionString = configuration.GetConnectionString(connectionKey);

string migrationDbProvider = configuration["DbProvider"] ?? "SqlServer";
//string contextTypeName = configuration["contextType"] ?? nameof(TContext);
/*
* Sample DI code goes here:
services.AddDbContext<TContext>(
options => _ = provider switch
{
"Sqlite" => options.UseSqlite(
configuration.GetConnectionString("SqliteConnection"),
x => x.MigrationsAssembly("SqliteMigrations")),
"SqlServer" => options.UseSqlServer(
configuration.GetConnectionString("SqlServerConnection"),
x => x.MigrationsAssembly("SqlServerMigrations")),
_ => throw new Exception($"Unsupported provider: {provider}")
});
*
*/

if (migrationDbProvider.Contains("SqlServer", StringComparison.InvariantCultureIgnoreCase)){
dbContextBuilder.UseSqlServer(connectionString, action => action.MigrationsAssembly(assemblyName));
}
else if(migrationDbProvider.Contains("MySql", StringComparison.InvariantCultureIgnoreCase))
{
dbContextBuilder.UseMySQL(connectionString, action => action.MigrationsAssembly(assemblyName));
}
else
{
throw new InvalidOperationException("Invalid DbProvider");
}

var dbContextInstance = (TContext)Activator.CreateInstance(typeof(TContext), dbContextBuilder.Options);

return dbContextInstance;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\LLMService.DataProvider.Relational\LLMService.DataProvider.Relational.csproj" />
</ItemGroup>


<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="MySql.EntityFrameworkCore" Version="8.0.0" />
</ItemGroup>


<ItemGroup>
<Folder Include="Migrations\" />
</ItemGroup>
</Project>
52 changes: 52 additions & 0 deletions src/LLMService.DataProvider.Migrator/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# 项目说明

本项目为独立的数据库迁移项目,支持在`appsettings.json`中配置数据库提供程序,目前支持`SqlServer``MySql`.

## 目录结构

例如,有3次迁移Migration1,Migration2,Migration3,文件结构大致如下:

```
.
├── Migrations /*迁移文件夹*/
│ ├── 时间戳1_Migration1.cs /*第1次迁移*/
│ ├── 时间戳2_Migration2.cs /*第2次迁移*/
│ ├── 时间戳3_Migration3.cs /*第3次迁移*/
│ ├── ChatDbContextModelSnapshot.cs /*迁移快照文件*/
│ └── Scripts /*迁移脚本文件夹*/
│ ├── Migration1.sql /*第1次迁移脚本*/
│ ├── Migration2.sql /*第2次迁移脚本*/
│ └── Migration3.sql /*第3次迁移脚本*/
├── ChatDbContextFactory.cs /*迁移配置程序*/
└── README.md /*说明文件*/
```

#### 创建迁移

`NewMigration`为迁移名称

##### VisualStudio 包管理器命令行
```
add-migration -c ChatDbContext NewMigration
```

#### 创建迁移脚本

`NewMigration`为本次迁移名称,`LastMigration`为上次迁移名称(可选),加入`-from` 参数创建`LastMigration`之后所做的增量脚本

##### VisualStudio 包管理器命令行

需要注意当前命令行执行的目录.

+ 仅创建迁移增量脚本
```
script-migration -o .\src\LLMService.DataProvider.Migrator\Migrations\Scripts\NewMigration.sql -Idempotent -from LastMigration
```

+ 创建整个数据库的建库脚本

`DbProvider`参数可选值:SqlServer,MySql
```
script-dbcontext -c ChatDbContext -Args "--DbProvider SqlServer"
```
9 changes: 9 additions & 0 deletions src/LLMService.DataProvider.Migrator/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"ConnectionStrings": {
"DbConnection": "Data Source=(localdb)\\mssqllocaldb;Database=LLMServiceHub_Db;Trusted_Connection=True;MultipleActiveResultSets=true"
//"DbConnection": "Server=.,3306;Database=LLMServiceHub_Db;Uid=sa;Pwd=pass;"
},
//database provider,optional values:SqlServer|MySql
"DbProvider": "SqlServer"
}

Loading

0 comments on commit 437c1e0

Please sign in to comment.