Skip to content

Commit

Permalink
Добавлено SQLCLR проект для чтения метаданных напрямую из базы данных…
Browse files Browse the repository at this point in the history
… средствами TSQL

- Добавлено решение YellowMetadataReader - SQLCLR проект для чтения метаданных напрямую из базы данных средствами TSQL
- Актуализация описания проектов раздела SQLCLR
  • Loading branch information
YPermitin committed Apr 23, 2023
1 parent 799cfd3 commit 27d8200
Show file tree
Hide file tree
Showing 90 changed files with 6,450 additions and 2 deletions.
11 changes: 10 additions & 1 deletion SQL-Server-SQLCLR/Projects/DevAdmHelpers/Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

Расширение SQLCLR для SQL Server с различными функциями для разработчиков и администраторов.

## Собранное решение

Собранную DLL для установки расширения SQLCLR можно скачать в разделе [релизы](https://github.com/YPermitin/SQLServerTools/releases).

## Обратная связь и новости

Вопросы, предложения и любую другую информацию [отправляйте на электронную почту](mailto:[email protected]).
Expand Down Expand Up @@ -60,10 +64,15 @@
1. Собрать проект **DevAdmHelpers** в режиме **Release**.
2. Полученную DLL **DevAdmHelpers.dll** скопировать на сервер, где установлен экземпляр SQL Server. Пусть для примера путь к DLL на сервере будет **"C:\Share\SQLCLR\DevAdmHelpers.dll"**.
3. Выбрать базу для установки. Например, пусть она называется **SQLServerMaintenance**.
4. Для упрощения настройки опустим некоторые аспекты безопасности и разрешим установку неподписанных расширений.

4. [Включим интеграцию с CLR](https://learn.microsoft.com/en-us/sql/relational-databases/clr-integration/clr-integration-enabling?view=sql-server-ver16). Для упрощения настройки опустим некоторые аспекты безопасности и разрешим установку неподписанных расширений.

```sql
EXEC sp_configure 'clr enabled', 1;
RECONFIGURE;
GO
ALTER DATABASE SQLServerMaintenance SET TRUSTWORTHY ON;
GO
```

Также разрешим текущему пользователю доступ к внешним ресурсам. Например, это пользователь **YY\ypermitin**.
Expand Down
289 changes: 288 additions & 1 deletion SQL-Server-SQLCLR/Projects/YellowMetadataReader/Readme.md

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
</configuration>
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using YPermitin.SQLCLR.YellowMetadataReader;

namespace YellowMetadataReader.CLI
{
internal class Program
{
static void Main()
{
EntryBase.ConnectionString = "server=localhost;database=master;trusted_connection=true;";

var infobases = EntryMetadata.GetInfobases();
foreach (var infobase in infobases)
{
EntryMetadata.GetInfobasesFillRow(infobase,
out _,
out _,
out _,
out _,
out _,
out _, out _);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System.Reflection;
using System.Runtime.InteropServices;

// Общие сведения об этой сборке предоставляются следующим набором
// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
// связанные с этой сборкой.
[assembly: AssemblyTitle("YellowMetadataReader.CLI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("YellowMetadataReader.CLI")]
[assembly: AssemblyCopyright("Copyright © 2023")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
// из модели COM задайте для атрибута ComVisible этого типа значение true.
[assembly: ComVisible(false)]

// Следующий GUID представляет идентификатор typelib, если этот проект доступен из модели COM
[assembly: Guid("27c4a27c-9ec9-4c96-aeee-9aa2a6e26a7e")]

// Сведения о версии сборки состоят из указанных ниже четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер сборки
// Номер редакции
//
// Можно задать все значения или принять номера сборки и редакции по умолчанию
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{27C4A27C-9EC9-4C96-AEEE-9AA2A6E26A7E}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>YellowMetadataReader.CLI</RootNamespace>
<AssemblyName>YellowMetadataReader.CLI</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\YellowMetadataReader\YellowMetadataReader.csproj">
<Project>{c4503533-bfbd-4e7e-a00e-941746748ddd}</Project>
<Name>YellowMetadataReader</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.33530.505
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "YellowMetadataReader", "YellowMetadataReader\YellowMetadataReader.csproj", "{C4503533-BFBD-4E7E-A00E-941746748DDD}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Libs", "Libs", "{2489FF06-C047-4ACE-A97B-6FE70C906F0B}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Docs", "Docs", "{6CF64E2A-0BDA-4E45-BAB0-924BEBCE20B1}"
ProjectSection(SolutionItems) = preProject
Readme.md = Readme.md
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Apps", "Apps", "{04251AC8-3B7D-4FEC-963B-C3A3FBE63FE6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "YellowMetadataReader.CLI", "YellowMetadataReader.CLI\YellowMetadataReader.CLI.csproj", "{27C4A27C-9EC9-4C96-AEEE-9AA2A6E26A7E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C4503533-BFBD-4E7E-A00E-941746748DDD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C4503533-BFBD-4E7E-A00E-941746748DDD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C4503533-BFBD-4E7E-A00E-941746748DDD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C4503533-BFBD-4E7E-A00E-941746748DDD}.Release|Any CPU.Build.0 = Release|Any CPU
{27C4A27C-9EC9-4C96-AEEE-9AA2A6E26A7E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{27C4A27C-9EC9-4C96-AEEE-9AA2A6E26A7E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{27C4A27C-9EC9-4C96-AEEE-9AA2A6E26A7E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{27C4A27C-9EC9-4C96-AEEE-9AA2A6E26A7E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{C4503533-BFBD-4E7E-A00E-941746748DDD} = {2489FF06-C047-4ACE-A97B-6FE70C906F0B}
{27C4A27C-9EC9-4C96-AEEE-9AA2A6E26A7E} = {04251AC8-3B7D-4FEC-963B-C3A3FBE63FE6}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {21E37607-AD9A-4719-B74C-B40CB809F021}
EndGlobalSection
EndGlobal
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SQL/@EntryIndexedValue">SQL</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=UTF/@EntryIndexedValue">UTF</s:String>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Enricher/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Enrichers/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Infobase/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Infobases/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Permitin/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=SQLCLR/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
using System;
using YPermitin.SQLCLR.YellowMetadataReader.Models;
using YPermitin.SQLCLR.YellowMetadataReader.Models.Enums;
using YPermitin.SQLCLR.YellowMetadataReader.Models.MetaObjects;
using YPermitin.SQLCLR.YellowMetadataReader.Services;

namespace YPermitin.SQLCLR.YellowMetadataReader.Enrichers
{
public sealed class AccountEnricher : IContentEnricher
{
private Configurator Configurator { get; }
public AccountEnricher(Configurator configurator)
{
Configurator = configurator;
}
public void Enrich(MetadataObject metadataObject)
{
if (!(metadataObject is Account account)) throw new ArgumentOutOfRangeException();

ConfigObject configObject = Configurator.FileReader.ReadConfigObject(account.FileName.ToString());

account.Uuid = configObject.GetUuid(new[] { 1, 3 });
account.Name = configObject.GetString(new[] { 1, 15, 1, 2 });
ConfigObject alias = configObject.GetObject(new[] { 1, 15, 1, 3 });
if (alias.Values.Count == 3)
{
account.Alias = configObject.GetString(new[] { 1, 15, 1, 3, 2 });
}
account.CodeType = CodeType.String;
account.CodeLength = configObject.GetInt32(new[] { 1, 22 });
account.DescriptionLength = configObject.GetInt32(new[] { 1, 23 });

Configurator.ConfigurePropertyСсылка(account);
Configurator.ConfigurePropertyВерсияДанных(account);
Configurator.ConfigurePropertyПометкаУдаления(account);
Configurator.ConfigurePropertyПредопределённый(account);
Configurator.ConfigurePropertyРодитель(account);

if (account.CodeLength > 0)
{
Configurator.ConfigurePropertyКод(account);
}
if (account.DescriptionLength > 0)
{
Configurator.ConfigurePropertyНаименование(account);
}

Configurator.ConfigurePropertyПорядок(account);
Configurator.ConfigurePropertyВид(account);
Configurator.ConfigurePropertyЗабалансовый(account);

// 6 - коллекция реквизитов плана счетов
ConfigObject properties = configObject.GetObject(new[] { 7 });
// 6.0 = 6e65cbf5-daa8-4d8d-bef8-59723f4e5777 - идентификатор коллекции реквизитов плана счетов
Guid propertiesUuid = configObject.GetUuid(new[] { 7, 0 });
if (propertiesUuid == new Guid("6e65cbf5-daa8-4d8d-bef8-59723f4e5777"))
{
Configurator.ConfigureProperties(account, properties, PropertyPurpose.Property);
}

Configurator.ConfigureSharedProperties(account);

// Признаки учета плана счетов
ConfigObject propertiesAccounting = configObject.GetObject(new[] { 8 });
// 6.0 = 78bd1243-c4df-46c3-8138-e147465cb9a4 - идентификатор коллекции реквизитов плана счетов
Guid propertiesUuidAccounting = configObject.GetUuid(new[] { 8, 0 });
if (propertiesUuidAccounting == new Guid("78bd1243-c4df-46c3-8138-e147465cb9a4"))
{
Configurator.ConfigureProperties(account, propertiesAccounting, PropertyPurpose.Property);
}

// 5 - коллекция табличных частей плана счетов
ConfigObject tableParts = configObject.GetObject(new[] { 5 });
// 5.0 = 932159f9-95b2-4e76-a8dd-8849fe5c5ded - идентификатор коллекции табличных частей плана счетов
Guid collectionUuid = configObject.GetUuid(new[] { 5, 0 });
if (collectionUuid == new Guid("4c7fec95-d1bd-4508-8a01-f1db090d9af8"))
{
Configurator.ConfigureTableParts(account, tableParts);
}

Configurator.ConfigurePredefinedValues(account);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
using System;
using YPermitin.SQLCLR.YellowMetadataReader.Models;
using YPermitin.SQLCLR.YellowMetadataReader.Models.Enums;
using YPermitin.SQLCLR.YellowMetadataReader.Models.MetaObjects;
using YPermitin.SQLCLR.YellowMetadataReader.Services;

namespace YPermitin.SQLCLR.YellowMetadataReader.Enrichers
{
public sealed class AccountingRegisterEnricher : IContentEnricher
{
private Configurator Configurator { get; }
public AccountingRegisterEnricher(Configurator configurator)
{
Configurator = configurator;
}
public void Enrich(MetadataObject metadataObject)
{
if (!(metadataObject is AccountingRegister register)) throw new ArgumentOutOfRangeException();

ConfigObject configObject = Configurator.FileReader.ReadConfigObject(register.FileName.ToString());

register.Name = configObject.GetString(new[] { 1, 15, 1, 2 });
ConfigObject alias = configObject.GetObject(new[] { 1, 15, 1, 3 });
if (alias.Values.Count == 3)
{
register.Alias = configObject.GetString(new[] { 1, 15, 1, 3, 2 });
}

Configurator.ConfigurePropertyПериод(register);
Configurator.ConfigurePropertyНомерЗаписи(register);
Configurator.ConfigurePropertyАктивность(register);
Configurator.ConfigurePropertyСчетДт(register);
Configurator.ConfigurePropertyСчетКт(register);

// 7 - коллекция измерений
ConfigObject properties = configObject.GetObject(new[] { 3 });
// 7.0 = 35b63b9d-0adf-4625-a047-10ae874c19a3 - идентификатор коллекции измерений
Guid propertiesUuid = configObject.GetUuid(new[] { 3, 0 });
if (propertiesUuid == new Guid("35b63b9d-0adf-4625-a047-10ae874c19a3"))
{
Configurator.ConfigureProperties(register, properties, PropertyPurpose.Dimension);
}
// TODO: ???
// Configurator.ConfigurePropertyDimHash(register);
// Справка 1С: Хеш-функция измерений.
// Поле присутствует, если количество измерений не позволяет организовать уникальный индекс по измерениям.

// 5 - коллекция ресурсов
properties = configObject.GetObject(new[] { 5 });
// 5.0 = 63405499-7491-4ce3-ac72-43433cbe4112 - идентификатор коллекции ресурсов
propertiesUuid = configObject.GetUuid(new[] { 5, 0 });
if (propertiesUuid == new Guid("63405499-7491-4ce3-ac72-43433cbe4112"))
{
Configurator.ConfigureProperties(register, properties, PropertyPurpose.Measure);
}

// 6 - коллекция реквизитов
properties = configObject.GetObject(new[] { 7 });
// 6.0 = 9d28ee33-9c7e-4a1b-8f13-50aa9b36607b - идентификатор коллекции реквизитов
propertiesUuid = configObject.GetUuid(new[] { 6, 0 });
if (propertiesUuid == new Guid("9d28ee33-9c7e-4a1b-8f13-50aa9b36607b"))
{
Configurator.ConfigureProperties(register, properties, PropertyPurpose.Property);
}

Configurator.ConfigureSharedProperties(register);
}
}
}
Loading

0 comments on commit 27d8200

Please sign in to comment.