Skip to content
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
36 changes: 22 additions & 14 deletions CommandRunner/CodeGeneration/Subsystems/TableRetrievalStatics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -176,23 +176,27 @@ internal static void WritePartialClass( DBConnection cn, string libraryBasePath,

private static void writeCacheClass( DBConnection cn, TextWriter writer, IDatabase database, Table table, TableColumns tableColumns, bool isRevisionHistoryTable ) {
var cacheKey = table.Name.TableNameToPascal( cn ) + "TableRetrieval";
var pkTupleTypeArguments = getPkTupleTypeArguments( tableColumns );

writer.WriteLine( "private partial class Cache {" );
// We use a struct here as the key to the cache. Comparisons are easy/fast and it doesn't have a limit of 7 like Tuples do.
writer.WriteLine( "internal struct Key {" );
writer.WriteLine( getPkStructMembers( tableColumns ) );
writer.WriteLine( "}" ); // Key struct.

writer.WriteLine( "internal static Cache Current { get { return DataAccessState.Current.GetCacheValue( \"" + cacheKey + "\", () => new Cache() ); } }" );
writer.WriteLine( "private readonly TableRetrievalQueryCache<Row> queries = new TableRetrievalQueryCache<Row>();" );
writer.WriteLine(
$"private readonly Dictionary<{TypeNames.Tuple}<{pkTupleTypeArguments}>, Row> rowsByPk = new Dictionary<{TypeNames.Tuple}<{pkTupleTypeArguments}>, Row>();" );
$"private readonly Dictionary<Key, Row> rowsByPk = new Dictionary<Key, Row>();" );
if( isRevisionHistoryTable ) {
writer.WriteLine(
$"private readonly Dictionary<{TypeNames.Tuple}<{pkTupleTypeArguments}>, Row> latestRevisionRowsByPk = new Dictionary<{TypeNames.Tuple}<{pkTupleTypeArguments}>, Row>();" );
$"private readonly Dictionary<Key, Row> latestRevisionRowsByPk = new Dictionary<Key, Row>();" );
}

writer.WriteLine( "private Cache() {}" );
writer.WriteLine( "internal TableRetrievalQueryCache<Row> Queries => queries; " );
writer.WriteLine( $"internal Dictionary<{TypeNames.Tuple}<" + pkTupleTypeArguments + ">, Row> RowsByPk => rowsByPk;" );
writer.WriteLine( $"internal Dictionary<Key, Row> RowsByPk => rowsByPk;" );
if( isRevisionHistoryTable ) {
writer.WriteLine( $"internal Dictionary<{TypeNames.Tuple}<" + pkTupleTypeArguments + ">, Row> LatestRevisionRowsByPk { get { return latestRevisionRowsByPk; } }" );
writer.WriteLine( "internal Dictionary<Key, Row> LatestRevisionRowsByPk { get { return latestRevisionRowsByPk; } }" );
}

writer.WriteLine( "}" );
Expand Down Expand Up @@ -228,14 +232,14 @@ private static void writeGetRowsMethod(

writer.WriteLine( "var cache = Cache.Current;" );
var pkConditionVariableNames = tableColumns.KeyColumns.Select( i => i.CamelCasedName + "Condition" );
var newKeyStructObject = "new Cache.Key {" + StringTools.ConcatenateWithDelimiter( ", ", tableColumns.KeyColumns.Select( kc => $"{kc.PascalCasedName} = {kc.CamelCasedName}Condition.Value" ) ) + "}";
writer.WriteLine(
"var isPkQuery = " + StringTools.ConcatenateWithDelimiter( " && ", pkConditionVariableNames.Select( i => i + " != null" ).ToArray() ) + " && conditions.Count() == " +
tableColumns.KeyColumns.Count() + ";" );
writer.WriteLine( "if( isPkQuery ) {" );
writer.WriteLine( "Row row;" );
writer.WriteLine(
"if( cache." + ( excludePreviousRevisions ? "LatestRevision" : "" ) + $"RowsByPk.TryGetValue( {TypeNames.Tuple}.Create( " +
StringTools.ConcatenateWithDelimiter( ", ", pkConditionVariableNames.Select( i => i + ".Value" ).ToArray() ) + " ), out row ) )" );
"if( cache." + ( excludePreviousRevisions ? "LatestRevision" : "" ) + $"RowsByPk.TryGetValue( {newKeyStructObject}, out row ) )" );
writer.WriteLine( "return new [] {row};" );
writer.WriteLine( "}" );

Expand Down Expand Up @@ -291,11 +295,11 @@ private static void writeGetRowMatchingPkMethod(
writer.WriteLine( "} );" );

var rowsByPkExpression = $"cache.{( isRevisionHistoryTable ? "LatestRevision" : "" )}RowsByPk";
var pkTupleCreationArguments = pkIsId ? id : StringTools.ConcatenateWithDelimiter( ", ", tableColumns.KeyColumns.Select( i => i.CamelCasedName ) );
var newKeyStructObject = "new Cache.Key {" + StringTools.ConcatenateWithDelimiter( ", ", tableColumns.KeyColumns.Select( kc => $"{kc.PascalCasedName} = { ( pkIsId ? "id" : kc.CamelCasedName )}" ) ) + "}";
writer.WriteLine( $"if( !{returnNullIfNoMatch} )" );
writer.WriteLine( $"return {rowsByPkExpression}[ {TypeNames.Tuple}.Create( {pkTupleCreationArguments} ) ];" );
writer.WriteLine( $"return {rowsByPkExpression}[ {newKeyStructObject} ];" );
writer.WriteLine( "Row row;" );
writer.WriteLine( $"return {rowsByPkExpression}.TryGetValue( {TypeNames.Tuple}.Create( {pkTupleCreationArguments} ), out row ) ? row : null;" );
writer.WriteLine( $"return {rowsByPkExpression}.TryGetValue( {newKeyStructObject}, out row ) ? row : null;" );
}
else {
var condition = pkIsId
Expand Down Expand Up @@ -397,11 +401,10 @@ cn.DatabaseInfo is OracleInfo

// Add all results to RowsByPk.
writer.WriteLine( "foreach( var i in results ) {" );
var pkTupleCreationArgs = tableColumns.KeyColumns.Select( i => "i." + Utility.GetCSharpIdentifier( i.PascalCasedNameExceptForOracle ) );
var pkTuple = "System.Tuple.Create( " + StringTools.ConcatenateWithDelimiter( ", ", pkTupleCreationArgs.ToArray() ) + " )";
writer.WriteLine( $"cache.RowsByPk[ {pkTuple} ] = i;" );
var newKeyStructObject = "new Cache.Key {" + StringTools.ConcatenateWithDelimiter( ", ", tableColumns.KeyColumns.Select( kc => $"{kc.PascalCasedName} = i.{kc.PascalCasedName}" ) ) + "}";
writer.WriteLine( $"cache.RowsByPk[ {newKeyStructObject} ] = i;" );
if( excludesPreviousRevisions )
writer.WriteLine( $"cache.LatestRevisionRowsByPk[ {pkTuple} ] = i;" );
writer.WriteLine( $"cache.LatestRevisionRowsByPk[ {newKeyStructObject} ] = i;" );
writer.WriteLine( "}" );

writer.WriteLine( "return results;" );
Expand All @@ -416,13 +419,18 @@ private static string getInlineSelectExpression(

private static string getCommandConditionAddingStatement( string commandName ) => $"foreach( var i in commandConditions ) {commandName}.AddCondition( i );";

// GMS NOTE: Really unsure of the RowVersion feature in TDL and whether or not it should be stripped out. If we keep it it needs much more testing/support.
private static string getPkAndVersionTupleTypeArguments( DBConnection cn, TableColumns tableColumns ) =>
"{0}, {1}".FormatWith( getPkTupleTypeArguments( tableColumns ), cn.DatabaseInfo is OracleInfo ? oracleRowVersionDataType : tableColumns.RowVersionColumn.DataTypeName );

private static string getPkTupleTypeArguments( TableColumns tableColumns ) {
return StringTools.ConcatenateWithDelimiter( ", ", tableColumns.KeyColumns.Select( i => i.DataTypeName ).ToArray() );
}

private static string getPkStructMembers( TableColumns tableColumns ) {
return StringTools.ConcatenateWithDelimiter( Environment.NewLine, tableColumns.KeyColumns.Select( i => $"internal {i.DataTypeName} {i.PascalCasedName};" ).ToArray() );
}

private static void writeToIdDictionaryMethod( TextWriter writer, TableColumns tableColumns ) {
writer.WriteLine( "public static Dictionary<" + tableColumns.KeyColumns.Single().DataTypeName + ", Row> ToIdDictionary( this IEnumerable<Row> rows ) {" );
writer.WriteLine( "return rows.ToDictionary( i => i." + Utility.GetCSharpIdentifier( tableColumns.KeyColumns.Single().PascalCasedNameExceptForOracle ) + " );" );
Expand Down
17 changes: 11 additions & 6 deletions CommandRunner/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,13 @@
using TypedDataLayer.Tools;

namespace CommandRunner {
class Program {
static int Main( string[] args ) {
var log = new Logger( args.Any( a => a == "-debug" ) );
public class Program {
/// <summary>
/// Loads config and always runs UpdateDependentLogic.
/// </summary>
public static int Main( string[] args ) {
var debug = args.Any( a => a == "-debug" );
var log = new Logger( debug );

if( args.Any( a => a == "-attachDebugger" ) ) {
log.Info( "Waiting 15s for debugger" );
Expand All @@ -24,15 +28,16 @@ static int Main( string[] args ) {
}

log.Debug( "TypedDataLayer version " + Assembly.GetExecutingAssembly().GetName().Version );

log.Debug( "args: " + string.Join( " ", args ) );

var command = args[ 0 ];
var workingDirectory = Environment.CurrentDirectory;
return LoadConfigAndRunUpdateAllDependentLogic( workingDirectory, debug );
}

public static int LoadConfigAndRunUpdateAllDependentLogic( string workingDirectory, bool debug ) {
var log = new Logger( debug );
log.Debug( "Executing directory: " + AppDomain.CurrentDomain.BaseDirectory );
log.Info( "Current working directory: " + workingDirectory );
log.Info( "Running " + command );

var sw = new Stopwatch();
try {
Expand Down
8 changes: 8 additions & 0 deletions TdlTestFp/App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="WorkingDirectory" value="C:\GitHub\TypedDataLayer\TdlTestFp"/>
<add key="TypedDataLayer.SupportedDatabaseType" value="SqlServer"/>
<add key="TypedDataLayer.ConnectionString" value="data source=(local);Initial Catalog=TdlTest;Integrated Security=SSPI;"/>
</appSettings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/></startup></configuration>
37 changes: 37 additions & 0 deletions TdlTestFp/CreateTestDb.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
CREATE DATABASE TdlTest
GO

USE TdlTest
GO
ALTER DATABASE TdlTest SET PAGE_VERIFY CHECKSUM
ALTER DATABASE TdlTest SET AUTO_CREATE_STATISTICS ON (INCREMENTAL = ON)
ALTER DATABASE TdlTest SET AUTO_UPDATE_STATISTICS_ASYNC ON
ALTER DATABASE TdlTest SET ALLOW_SNAPSHOT_ISOLATION ON
ALTER DATABASE TdlTest SET READ_COMMITTED_SNAPSHOT ON WITH ROLLBACK IMMEDIATE
GO

CREATE TABLE GlobalInts(
ParameterName varchar( 50 )
NOT NULL
CONSTRAINT GlobalIntsPk PRIMARY KEY,
ParameterValue int
NOT NULL
)

INSERT INTO GlobalInts VALUES( 'LineMarker', 0 )
GO

CREATE SEQUENCE PrimarySequence AS int start with 1;
GO

CREATE TABLE States (
StateId int NOT NULL CONSTRAINT pkStates PRIMARY KEY,
StateName nvarchar( 50 ) NOT NULL CONSTRAINT uniqueStateName UNIQUE,
Abbreviation nvarchar( 2 ) NOT NULL CONSTRAINT uniqueStateAbbr UNIQUE
)
GO
INSERT INTO States VALUES( 1, 'Alabama', 'AL' );
INSERT INTO States VALUES( 2, 'Alaska', 'AK' );
INSERT INTO States VALUES( 3, 'Arizona', 'AZ' );
INSERT INTO States VALUES( 4, 'Arkansas', 'AR' );
GO
15 changes: 15 additions & 0 deletions TdlTestFp/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TdlTestFp {
class Program {
static void Main( string[] args ) {
Debug.WriteLine( "Hello World!" );
CommandRunner.Program.LoadConfigAndRunUpdateAllDependentLogic( @"C:\GitHub\TypedDataLayer\TdlTestFp", true );
}
}
}
36 changes: 36 additions & 0 deletions TdlTestFp/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle( "TdlTestFp" )]
[assembly: AssemblyDescription( "" )]
[assembly: AssemblyConfiguration( "" )]
[assembly: AssemblyCompany( "" )]
[assembly: AssemblyProduct( "TdlTestFp" )]
[assembly: AssemblyCopyright( "Copyright © 2020" )]
[assembly: AssemblyTrademark( "" )]
[assembly: AssemblyCulture( "" )]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible( false )]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid( "634b4b52-ba61-4cb5-bc77-1ceaac391e72" )]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion( "1.0.0.0" )]
[assembly: AssemblyFileVersion( "1.0.0.0" )]
5 changes: 5 additions & 0 deletions TdlTestFp/Readme.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
This test project is not central to the design or function of the TDL tool.

This test project should not need to build in order to use/deploy/modify TDL.

This test project should not fail to build just because the machine does not have the/a test database. The dev should not be obligated to create a test database.
78 changes: 78 additions & 0 deletions TdlTestFp/TdlTestFp.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?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>{634B4B52-BA61-4CB5-BC77-1CEAAC391E72}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>TdlTestFp</RootNamespace>
<AssemblyName>TdlTestFp</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
</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>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<PlatformTarget>x64</PlatformTarget>
<OutputPath>bin\x64\Debug\</OutputPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<PlatformTarget>x64</PlatformTarget>
<OutputPath>bin\x64\Release\</OutputPath>
</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" />
<Compile Include="TypedDataLayer\GeneratedCode\TypedDataLayer.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CommandRunner\CommandRunner.csproj">
<Project>{a81039df-def4-40b8-a770-6dd3450e0961}</Project>
<Name>CommandRunner</Name>
</ProjectReference>
<ProjectReference Include="..\TypedDataLayer\TypedDataLayer.csproj">
<Project>{86a9c472-70ea-4dd1-b36e-5276c754e720}</Project>
<Name>TypedDataLayer</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Content Include="CreateTestDb.sql" />
<Content Include="Readme.txt" />
<Content Include="TypedDataLayer\Configuration.xml" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
25 changes: 25 additions & 0 deletions TdlTestFp/TypedDataLayer/Configuration.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8" ?>
<systemDevelopmentConfiguration xmlns="http://samrueby.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:rs="http://samrueby.com" xsi:schemaLocation="http://samrueby.com ..\TypedDataLayerConfig.xsd">
<LibraryNamespaceAndAssemblyName>Tdl.Tester</LibraryNamespaceAndAssemblyName>
<databaseConfiguration xsi:type="SqlServerDatabase">
<ConnectionString>data source=(local);Initial Catalog=TdlTest;Integrated Security=SSPI;</ConnectionString>
</databaseConfiguration>
<database>
<CommandTimeoutSeconds>5</CommandTimeoutSeconds>
<rowConstantTables>
<table tableName="dbo.States" nameColumn="Abbreviation" valueColumn="StateId"/>
</rowConstantTables>
<SmallTables>
<Table>dbo.States</Table>
</SmallTables>
<queries>
<query name="PrimarySequence">
<selectFromClause>SELECT NEXT VALUE FOR PrimarySequence as Id</selectFromClause>
<postSelectFromClauses>
<postSelectFromClause name="Next"></postSelectFromClause>
</postSelectFromClauses>
</query>
</queries>
</database>
</systemDevelopmentConfiguration>
Loading