有时候我们会存储 json 到 db,也有时会只取json部分数据,或者通过json部分数据进行过滤
所以sv.db 也支持这些场景,(目前只有 db 实现,json的操作都是依靠db json 函数)
举例:
数据
a.ExecuteNonQuery("""
INSERT INTO Weather
(name, value)
VALUES ('Hello', '{"a":2}'),('A', '{"a":3,"c":[4,5,{"f":7}]}')
""");
然后配置字段允许json
[Db(StaticInfo.Demo)]
[Table(nameof(Weather))]
public class Weather
{
[Select, Where, OrderBy]
public string Name { get; set; }
[Select(Field = "Value"), Where, OrderBy, Column(IsJson = true)]
public string V { get; set; }
}
api 方法不用做额外的实现
[HttpGet]
public async Task<object> Selects()
{
return await this.QueryByParamsAsync<Weather>();
}
用户查询api 时就可以对json字段进行任意操作,比如
curl --location 'http://localhost:5259/weather?Fields=v,json(v,'$.a',vvva)&OrderBy=json(v,'$.a') asc&Where=json(v,'$.a') != 1'
结果
{
"totalCount": null,
"rows": [
{
"vvva": 2,
"v": "{\"a\":2}"
},
{
"vvva": 3,
"v": "{\"a\":3,\"c\":[4,5,{\"f\":7}]}"
}
]
}
ps:json 实现对应 db json 函数
db | json 函数 |
---|---|
SQLite | json_extract |
PostgreSQL | jsonb_path_query_first |
MySql | json_unquote(json_extract()) |
sql server | JSON_QUERY |
默认会对解析的statement结果进行字段验证,不通过的会返回 400
验证:
如需改变 验证逻辑或自行验证,可以通过 SelectStatementOptions
自行处理
public record class SelectStatementOptions
{
public bool AllowNotFoundFields { get; init; } = false;
public bool AllowNonStrictCondition { get; init; } = false;
public Action<Statement> Visiter { get; init; } = null;
}
安装 swagger
<PackageReference Include="SV.Db.Sloth.Swagger" Version="0.0.2.3" />
swagger gen 配置 sv.db 方法
builder.Services.AddSwaggerGen(c =>
{
c.AddDbSwagger();
});
api 方法配置 swagger
[DbSwaggerByType(typeof(Weather))]
[HttpGet]
public async Task<object> Selects()
{
return await this.QueryByParamsAsync<Weather>();
}
只需配置这些,swagger 将为大家自动生成字段描述
如想尝试,只需安装所需 package
<PackageReference Include="SV.Db.Sloth.Swagger" Version="0.0.2.3" />
<PackageReference Include="SV.Db.Sloth.WebApi" Version="0.0.2.3" />
<PackageReference Include="SV.Db.Analyzers" Version="0.0.2.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="SV.Db.Sloth.MSSql" Version="0.0.2.3" />
<PackageReference Include="SV.Db.Sloth.MySql" Version="0.0.2.3" />
<PackageReference Include="SV.Db.Sloth.PostgreSQL" Version="0.0.2.3" />
<PackageReference Include="SV.Db.Sloth.Sqlite" Version="0.0.2.3" />