Insert entity in NestJS / TypeOrm / Postgres - postgresql

Here is my entity :
import { BaseEntity, Column, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
import { Client } from './client.entity';
#Entity({ name: 'directory_dir' })
export class Directory extends BaseEntity {
#PrimaryGeneratedColumn("uuid", { name: 'dir_id' })
id: string;
#Column( { name: 'dir_name' } )
name: string;
#JoinColumn({ name: 'cli_client_id'})
#ManyToOne(() => Client, { eager: true })
client: Client;
}
The table is created via liquibase :
<changeSet id="3" author="Me">
<createTable tableName="DIRECTORY_DIR">
<column name="DIR_ID" type="uuid">
<constraints primaryKey="true" nullable="false"/>
</column>
<column name="DIR_NAME" type="varchar(64)">
<constraints nullable="false"/>
</column>
<column name="CLI_CLIENT_ID" type="uuid">
<constraints nullable="false" foreignKeyName="FK_DIRECTORY_DIR_CLI_CLIENT_ID" references="CLIENT_CLI(CLI_ID)"/>
</column>
</createTable>
</changeSet>
I struggle to have it inserted into the database. I have tried several syntaxes but every time, I get an error because the id is not auto-generated:
null value in column "dir_id" of relation "directory_dir" violates not-null constraint
I tried this :
const directory = new Directory();
/* Also tried this one
* const directory = this.directoryRepository.create({
* name: makeDirRequest.name,
* client: user.client
* });
*/
directory.name = makeDirRequest.name;
directory.client = user.client;
this.logger.log('directory', JSON.stringify(directory));
// Also tried with insert instead of save
return await this.directoryRepository.save(directory);
In the logs, I can see that there is no dir_id but, in the way I understand it, it should not be a problem, as I expect TypeOrm to do it when generating the INSERT statement.
When I insert entities in the database with SQL statements, I can easily find them from typeORM so the typeORM configuration seems ok.

The problem came from the definition of the table in PostgreSQL. A default value must be supplied in order to explain how to auto-generate the primary key.
Declaring the column like this in Liquibase does the job :
<column name="DIR_ID" type="uuid" defaultValue="gen_random_uuid()">
<constraints primaryKey="true" nullable="false"/>
</column>
I just added defaultValue="gen_random_uuid()".
gen_random_uuid() is the new uuid_generate_v4(), available from Postgres 13
From this point, I could just create the entity and insert it like this :
return await Directory.create({
name: makeDirRequest.name,
client: user.client
}).save();

Related

Change Doctrine translations "ext_translations" public schema to a custom one

I'm using stof/doctrine-extensions-bundle with the Translatable extension for my entities (& doctrine/doctrine-migrations-bundle) and want to move ext_translations table from the public schema to a custom schema (e.g. product)
product.ext_translations table is created with bin/console doctrine:migrations:migrate
but when I want to import some data with this script:
use App\Infrastructure\Translatable\Entity\Translation\Translation;
...
$repository = $em->getRepository(Translation::class);
$colorEntity = new Color();
$colorEntity->setName("bleu");
$repository->translate($colorEntity, 'name', 'en', 'blue');
$em->persist($colorEntity);
$em->flush();
I get this error
[error] Migration App\Migrations\VersionXXX failed during Post-Checks. Error: "An exception occurred while executing a query: SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "ext_translations" does not exist
LINE 1: INSERT INTO ext_translations (locale, object_class, field, f...
Here is my conf:
doctrine.yaml
orm:
mappings:
Translatable:
type: annotation
is_bundle: false
prefix: App\Infrastructure\Translatable\Entity
dir: '%kernel.project_dir%/src/Infrastructure/Translatable/Entity'
alias: GedmoTranslatable
Metadata:
is_bundle: false
type: xml
dir: '%kernel.project_dir%/src/Infrastructure/ORM/Mapping/Metadata'
prefix: 'App\Domain\Metadata'
alias: Metadata
Color.orm.xml mapping file
<entity name="App\Domain\Metadata\Color" table="colors" schema="product" repository-class="App\Infrastructure\ORM\Repository\ColorRepository">
<id name="id" type="integer" column="id">
<generator strategy="AUTO"/>
</id>
<field name="name" type="string">
<gedmo:translatable/>
</field>
...
<gedmo:translation entity="App\Infrastructure\Translatable\Entity\Translation" locale="locale"/>
</entity>
App\Infrastructure\Translatable\Entity\Translation
<?php
namespace App\Infrastructure\Translatable\Entity;
use ...
/**
* #ORM\Table(name="ext_translations", schema="product", indexes={
* #ORM\Index(name="translations_lookup_idx", columns={"locale", "object_class", "field", "foreign_key"})
* })
* #ORM\Entity(repositoryClass="Gedmo\Translatable\Entity\Repository\TranslationRepository")
*/
class Translation extends AbstractTranslation
{
/**
* All required columns are mapped through inherited superclass
*/
}

what is the xml mapping for json like this?

Tables:
Create table development(
developmentName varchar(100) primary key,
description varchar(100)
);
Create table Student(
name varchar(100) primary key,
dateType varchar(100),
developmentName foreign key reference development(developmentName)
);
Input Json:
The json would come in the format
{ "DevelopmentName":"comp", "description":"Descrizione Tracciatro 1", "Student":[ {
"name":"String",
"dateType":"String",
"DevelopmentName":"comp"
},
{
"name":"String",
"date_type":"String"
"DevelopmentName":"comp"
}]}
DevelopmentName is primary key and which is foreign key for Student.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="it.eng.billing.mapper.Development">
<resultMap id="BaseResultMap" type="it.eng.billing.model.Development">
<result column="DevelopmentName" jdbcType="VARCHAR" property="DevelopmentName" />
<result column="description" jdbcType="VARCHAR" property="description" />
</resultMap>
<insert id="insert" parameterType="it.eng.billing.model.Development" >
insert into Development (DevelopmentName, description) values (#{DevelopmentName,jdbcType=VARCHAR},#{description,jdbcType=VARCHAR})
</insert>
<insert id="insertOptions" parameterType="it.eng.billing.model.Student">
INSERT INTO Student (name,DevelopmentName, datatype)
VALUES
<foreach collection="list" item="option" open="(" separator="),(" close=")" >
#{option.name},#{option.DevelopmentName},#{option.datatype}
</foreach>
</insert>
</mapper>
There is problem with the XML. The json is not getting saved into database.
public interface DevelopmentMapper{
default void save(DevelopmentDto record) {
insert(record);
insertOptions(record.getStudent());
}
from service class, calling developmentMapper.save(DevelopmentDto obj)

how can I create a table for another schema owner in hsql

I am writing test cases for a Spring batch application. I need to setup an HSQL database that mirrors a remote mainframe db2 database so I can run my tests quickly.
I have to setup the db table in such as way that the following SQL statement will succeed:
SELECT PROJ_TYP, SYS_CD, ... FROM CMNREF.CNTRCT_EXTRNL_KEY_REF_V WITH UR
I believe the CMNREF above is the Schema owner. How can I create that table and schema in HSQL db so this SELECT will work?
Update:
Doing some research on the topic here, I've learned that I need to do the following:
1) Use the SA default user to create new user CMNREF
2) Grant some ROLES to user CMNREF (i.e. SELECT)
However, I also noticed that the default user SA has the DBA role, which means it can do anything on that database.... so I wonder if I even need to bother with creating the 1 and 2 above....
My Test Case:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "/load-BMS-data-job-launcher-context.xml" })
public class SimpleJobLaunchFunctionalTests {
#Autowired
private JobLauncherTestUtils jobLauncherUtils;
#Qualifier("jdbcTemplate")
#Autowired
private JdbcOperations jdbcTemplate;
#Qualifier("jdbcTemplateBMS")
#Autowired
private JdbcOperations jdbcTemplateBMS;
#Before
public void setUp() {
jdbcTemplateBMS.update("DELETE from CMNREF.CNTRCT_EXTRNL_KEY_REF_V");
jdbcTemplate.update("DELETE from SHADOW_BMS");
// jdbcTemplate.update("DELETE from CMNREF.CNTRCT_EXTRNL_KEY_REF_V");
Calendar calendar = Calendar.getInstance();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(calendar.getTime().getTime());
// Insert one test data record
jdbcTemplate.update("INSERT INTO CMNREF.CNTRCT_EXTRNL_KEY_REF_V(PROJ_TYP_CD, SYS_CD, STAT_CK_CD, EXTRNL_KEY_CD, EXTRNL_SYS_CD, CNTRCT_NUM, PROJ_NUM, CNTRCT_LINE_ITM, CUST_NUM, CUST_CNTL_NUM, CUST_NM, CHRG_CD, PRDCT_ID, BILNG_CRNCY_CD, BILNG_ISO_CRNCY_CD, BILNG_CRNCY_DCM_NUM, CFTS_CRNCY_EXCH_RT, CFTS_CRNCY_EXCH_RT_EXPIR_DT, CHRG_CRNCY_CD, CHRG_ISO_CRNCY_CD, CTRY_CD, CMPNY_CD, OFFERING_CD, CNTL_GRP_CD, ORIG_CTRY_CD, ORIG_CMPNY_CD, ORIG_LOC_CD, NOTES_ID, INET_ID, CFTS_GBI_IND, CFTS_CHRG_TYP_CD, CFTS_SPCL_HNDL_CD, CC_PMT_METH_IND, STAT_CD, REFRESH_TMS) VALUES('PROJT1', 'SCD', 'STC', 'EXTKEY','EXTSYSCODE', 'CTR923','PROJN293', 23, 'CNUM32', 'CN', 'NAME THIS CUST', 'CHCD', '2903-920','BCD', 'BIC', 23, 1.345, '2017-01-23','CCC', 'CIC', 'CCD', 'IBM', '9203L-98', 'CTLGRP', 'USA', 'IBM001', 'OLC', 'me#us.ibm.com', 'ME/US/IBM/COM', 'G', 'T', 'H', 'P', 'OPEN', '2016-01-02 19:29:23.271' )");
}
My DB Script is there:
CREATE USER CMNREF PASSWORD 'pw';
CREATE SCHEMA CMNREF AUTHORIZATION DBA;
ALTER USER CMNREF SET INITIAL SCHEMA CMNREF;
SET SCHEMA CMNREF;
CREATE TABLE CMNREF.CNTRCT_EXTRNL_KEY_REF_V (
PROJ_TYP_CD VARCHAR(10),
SYS_CD VARCHAR(3),
STAT_CK_CD VARCHAR(12),
EXTRNL_KEY_CD VARCHAR(36),
EXTRNL_SYS_CD VARCHAR(10),
CNTRCT_NUM VARCHAR(15),
PROJ_NUM VARCHAR(8),
CNTRCT_LINE_ITM INTEGER,
CUST_NUM VARCHAR(8),
CUST_CNTL_NUM VARCHAR(2),
CUST_NM VARCHAR(35),
CHRG_CD VARCHAR(4),
PRDCT_ID VARCHAR(15),
BILNG_CRNCY_CD VARCHAR(3),
BILNG_ISO_CRNCY_CD VARCHAR(3),
BILNG_CRNCY_DCM_NUM SMALLINT,
CFTS_CRNCY_EXCH_RT DECIMAL,
CFTS_CRNCY_EXCH_RT_EXPIR_DT DATE,
CHRG_CRNCY_CD VARCHAR(3),
CHRG_ISO_CRNCY_CD VARCHAR(3),
CTRY_CD VARCHAR(3),
CMPNY_CD VARCHAR(10),
OFFERING_CD VARCHAR(8),
CNTL_GRP_CD VARCHAR(8),
ORIG_CTRY_CD VARCHAR(3),
ORIG_CMPNY_CD VARCHAR(10),
ORIG_LOC_CD VARCHAR(3),
NOTES_ID VARCHAR(100),
INET_ID VARCHAR(100),
CFTS_GBI_IND VARCHAR(1),
CFTS_CHRG_TYP_CD VARCHAR(1),
CFTS_SPCL_HNDL_CD VARCHAR(1),
CC_PMT_METH_IND VARCHAR(1),
STAT_CD VARCHAR(12),
REFRESH_TMS TIMESTAMP
) ;
My DataSources are defined here:
<!-- Initialise the database before every test case: -->
<jdbc:initialize-database data-source="dataSource">
<jdbc:script location="${batch.drop.script}"/>
<jdbc:script location="${batch.schema.script}"/>
<jdbc:script location="${batch.business.schema.script}"/>
</jdbc:initialize-database>
<!-- Initialize the mock BMS database -->
<jdbc:initialize-database data-source="BMSdataSource" ignore-failures="DROPS">
<jdbc:script location="${bmsmock.business.schema.script}"/>
</jdbc:initialize-database>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${batch.jdbc.driver}" />
<property name="url" value="${batch.jdbc.url}" />
<property name="username" value="${batch.jdbc.user}" />
<property name="password" value="${batch.jdbc.password}" />
<property name="maxActive" value="${batch.jdbc.pool.size}"/>
<property name="validationQuery" value="${batch.jdbc.validationQuery}"/>
<property name="testWhileIdle" value="${batch.jdbc.testWhileIdle}"/>
</bean>
<bean id="BMSdataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${bmsmock.jdbc.driver}" />
<property name="url" value="${bmsmock.jdbc.url}" />
<property name="username" value="${bmsmock.jdbc.user}" />
<property name="password" value="${bmsmock.jdbc.password}" />
<property name="maxActive" value="${bmsmock.jdbc.pool.size}"/>
<property name="validationQuery" value="${bmsmock.jdbc.validationQuery}"/>
<property name="testWhileIdle" value="${bmsmock.jdbc.testWhileIdle}"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" lazy-init="true">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- Set up or detect a System property called "ENVIRONMENT" used to construct a properties file on the classpath. The default is "hsql". -->
<bean id="environment"
class="org.springframework.batch.support.SystemPropertyInitializer">
<property name="defaultValue" value="hsql"/>
<property name="keyName" value="ENVIRONMENT"/>
</bean>
<bean id="placeholderProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
depends-on="environment">
<property name="location" value="classpath:batch-${ENVIRONMENT}.properties" />
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="order" value="1" />
</bean>
My HSQLDB Properties are below:
batch.jdbc.driver=org.hsqldb.jdbcDriver
batch.jdbc.url=jdbc:hsqldb:mem:testdb;sql.enforce_strict_size=true;hsqldb.tx=mvcc
batch.jdbc.user=sa
batch.jdbc.password=
batch.jdbc.testWhileIdle=false
batch.jdbc.validationQuery=
batch.drop.script=classpath:/org/springframework/batch/core/schema-drop-hsqldb.sql
batch.schema.script=classpath:/org/springframework/batch/core/schema-hsqldb.sql
batch.business.schema.script=classpath:/db/custom-db-assets.sql
batch.database.incrementer.class=org.springframework.jdbc.support.incrementer.HsqlMaxValueIncrementer
batch.database.incrementer.parent=columnIncrementerParent
batch.lob.handler.class=org.springframework.jdbc.support.lob.DefaultLobHandler
batch.jdbc.pool.size=6
batch.grid.size=6
batch.verify.cursor.position=true
batch.isolationlevel=ISOLATION_SERIALIZABLE
batch.data.source.init=true
batch.table.prefix=BATCH_
bmsmock.jdbc.driver=org.hsqldb.jdbcDriver
bmsmock.jdbc.url=jdbc:hsqldb:mem:testbms;sql.enforce_strict_size=true;hsqldb.tx=mvcc
bmsmock.jdbc.user=SA
bmsmock.jdbc.password=
bmsmock.jdbc.pool.size=6
bmsmock.jdbc.testWhileIdle=false
bmsmock.jdbc.validationQuery=
bmsmock.business.schema.script=db/mock-bms-tables.sql
It is a good idea to use a different user without the DBA role.
In HSQLDB a user and a schema are separate concepts, with no automatic schema per user. What you have done is fine. Alternatively you can
CREATE USER CMNREF PASSWORD 'pw'
CREATE SCHEMA CMNREF AUTHORIZATION CMNREF
With the above, the CMNREF user owns a schema of the same name. It can execute all statements in its own schema.
update: In your settings the SA user is used for all the operations. You need to run the user creation section of the DB script you quoted with the user SA, then run the tests with the user CMNREF.
My script (attached) shows exactly how to do it. It's right, nothing wrong with the script or schema definition. My problem was that my test case was refering to the wrong Jdbc template when inserting data into the CMNREF.C* table.... the correct stmt should have been:
jdbcTemplateBMS**.update("INSERT INTO CMNREF.CNTRCT_E
Also, I need to turn on the DB2 mode for my sql script to work properly

Extending Modx modResource schema errors

I'm trying to extend the modx modresource object, but keep getting errors & I can't seem to figure out why. It is related to the schema (I think) but everything looks correct.
Schema:
<?xml version="1.0" encoding="UTF-8"?>
<model package="extresource" baseClass="xPDOObject" platform="mysql" defaultEngine="MyISAM" tablePrefix="modx_" version="1.0.0">
<object class="extResource" extends="modResource">
<composite alias="ResourceData" class="ResourceData" local="id" foreign="internalKey" cardinality="one" owner="local"/>
</object>
<object class="ResourceData" table="resource_data" extends="xPDOSimpleObject">
<field key="internalKey" dbtype="int" precision="11" phptype="integer" null="false" attributes="unsigned"/>
<field key="views" dbtype="int" precision="11" phptype="integer" null="true" />
<field key="starred" dbtype="int" precision="10" phptype="integer" null="false" />
<index alias="internalKey" name="internalKey" primary="false" unique="true" type="BTREE" >
<column key="internalKey" length="" collation="A" null="false" />
</index>
<aggregate alias="Resource" class="modResource" local="internalKey" foreign="id" cardinality="one" owner="foreign"/>
</object>
</model>
I'm testing it using:
$resource = $modx->getObject('modResource', 11112);
echo $resource->get('pagetitle'); //test I have the resource
$data = $resource->getOne('ResourceData');
The errors I get are:
Could not getOne: foreign key definition for alias ResourceData not
found. No foreign key definition for parentClass: modDocument using
relation alias: ResourceData
The table exists & has data, the package is registered in the modx extension packages. I've been over the schema many times & it looks right.
What is causing these errors?
You have to use the right object class in $modx->getObject. Otherwise you will get a modResource object, that does not know the extended object data and relationship.
$resource = $modx->getObject('extResource', 11112);
Does the resource you are loading have its class_key field set to extResource? That's needed for it to load the right resource object class.

How can I declare a Clustered key on a many-to-many relationship table in CodeFluent Entities with Sql Server Producer

I have a CodeFluent Entities Model such as:
<cf:project defaultNamespace="S5T" xmlns:cf="http://www.softfluent.com/codefluent/2005/1" xmlns:cfx="http://www.softfluent.com/codefluent/modeler/2008/1" xmlns:cfmy="http://www.softfluent.com/codefluent/producers.mysql/2012/1" xmlns:cfom="http://www.softfluent.com/codefluent/producers.model/2005/1" xmlns:cfasp="http://www.softfluent.com/codefluent/producers.aspnet/2011/1" xmlns:cfaz="http://www.softfluent.com/codefluent/producers.sqlazure/2011/1" xmlns:cfps="http://www.softfluent.com/codefluent/producers.sqlserver/2005/1" defaultKeyPropertyTypeName="long" maxParameterNameLength="62" defaultConcurrencyMode="None" persistencePropertyNameFormat="{1}" defaultMethodAllowDynamicSort="false" defaultProducerProductionFlags="Default, Overwrite, RemoveDates" defaultMethodDistinct="false" createDefaultMethodForms="true" createDefaultApplication="false" createDefaultHints="false" productionFlags="Default, Overwrite, RemoveDates">
<cf:import path="Default.Surface.cfp" />
<cf:producer name="SQL Server" typeName="CodeFluent.Producers.SqlServer.SqlServerProducer, CodeFluent.Producers.SqlServer">
<cf:configuration produceViews="true" targetDirectory="..\Model7Bom\Persistence" connectionString="Server=MY-MACHINE\SQLEXPRESS;Database=model7;Integrated Security=true;Application Name=S5T;Password=MyPassword;User ID=MyUser" cfx:targetProject="..\Model7Bom\Model7Bom.vbproj" cfx:targetProjectLayout="Update, DontRemove" />
</cf:producer>
<cf:entity name="User" namespace="S5T">
<cf:property name="Id" key="true" cfps:hint="CLUSTERED" />
<cf:property name="Name" />
<cf:property name="Roles" typeName="{0}.RoleCollection" relationPropertyName="Users" />
</cf:entity>
<cf:entity name="Role" namespace="S5T">
<cf:property name="Id" key="true" cfps:hint="CLUSTERED" />
<cf:property name="Name" />
<cf:property name="Users" typeName="{0}.UserCollection" relationPropertyName="Roles" />
</cf:entity>
</cf:project>
I could sucessfully decorate the cf:property name="Id" on both entities with cfps:hint="CLUSTERED". This got me Sql Server producer to correctly output
CONSTRAINT [PK_Use_Id_Use] PRIMARY KEY CLUSTERED
CONSTRAINT [PK_Rol_Id_Rol] PRIMARY KEY CLUSTERED
as opposed to default NONCLUSTERED.
How can I accomplish that with the THIRD TABLE generated by the model, to accomodate the many to many relationship?
By default, the table creation generated snippet is such as:
CREATE TABLE [dbo].[Role_Users_User_Roles] (
[Id] [bigint] NOT NULL,
[Id2] [bigint] NOT NULL,
CONSTRAINT [PK_Roe_Id_Id2_Roe] PRIMARY KEY NONCLUSTERED
(
[Id],
[Id2]
) ON [PRIMARY]
)
However, if I decorate both properties with cfps:hint="CLUSTERED" as in:
cf:property name="Roles" typeName="{0}.RoleCollection" relationPropertyName="Users" cfps:hint="CLUSTERED" /
cf:property name="Users" typeName="{0}.UserCollection" relationPropertyName="Roles" cfps:hint="CLUSTERED" /
I get a snippet generated with PRIMARY KEY CLUSTERED for the PK in TABLE [dbo].[Role_Users_User_Roles], BUT, in addition, I get an UNDESIRED effect of having an incorrect script generated for adding relations (generated filename ...relations_add.sql), such as:
ALTER TABLE [dbo].[Role_Users_User_Roles] WITH NOCHECK ADD CONSTRAINT [FK_Roe_Id_Id_Rol] FOREIGN KEY (
[Id]
) REFERENCES [dbo].[Role](
[Id]
) CLUSTERED
Along with the error from Sql Server:
Error 3 SQL80001: Incorrect syntax near 'CLUSTERED'.
And CodeFluent Producer Error:
CodeFluentRuntimeDatabaseException: CF4116: Execution of file ...path..._relations_add.sql statement at line 2
I need all three PKs CLUSTERED in the three tables generated, but not the side effect of syntax error for generating the relations.
This is not supported out-of-the-box. The hint declared on the a relation is rarely used, more meant as a Foreign Key hint than a column hint. There are several options you can use to do this.
The easiest is to use a post-generation .SQL script to add the clustered setting manually. This is described here: How to: Execute custom T-SQL scripts with the Microsoft SQL Server producer.
You could also use the Patch Producer to remove the CLUSTERED word from the file once it has been created : Patch Producer
Otherwise, here is another solution that involves an aspect I've written as a sample here. You can save the following piece of XML as a file, and reference it as an aspect in your model.
This aspect will add the CLUSTERED hint to primary keys of all Many To Many tables inferred from entities that have CLUSTERED keys. It will add the hint before the table scripts are created and ran, and will remove it after (so it won't end up in the relations_add script).
<cf:project xmlns:cf="http://www.softfluent.com/codefluent/2005/1">
<!-- assembly references -->
<?code #reference name="CodeFluent.Producers.SqlServer.dll" ?>
<?code #reference name="CodeFluent.Runtime.Database.dll" ?>
<!-- namespace includes -->
<?code #namespace name="System" ?>
<?code #namespace name="System.Collections.Generic" ?>
<?code #namespace name="CodeFluent.Model.Code" ?>
<?code #namespace name="CodeFluent.Model.Persistence" ?>
<?code #namespace name="CodeFluent.Model.Code" ?>
<!-- add global code to listen to inference steps -->
<?code
Project.StepChanging += (sender1, e1) =>
{
if (e1.Step == ImportStep.End) // hook before production begins (end of inference pipeline)
{
var modifiedTables = ProjectHandler.AddClusteredHint(Project);
// get sql server producer and hook on production events
var sqlProducer = Project.Producers.GetProducerInstance<CodeFluent.Producers.SqlServer.SqlServerProducer>();
sqlProducer.Production += (sender, e) =>
{
// determine what SQL file has been created
// we want to remove hints once the table_diffs has been created, before relations_add is created
string script = e.GetDictionaryValue("filetype", null);
if (script == "TablesDiffsScript")
{
ProjectHandler.RemoveClusteredHint(modifiedTables);
}
};
}
};
?>
<!-- add member code to handle inference modification -->
<?code #member
public class ProjectHandler
{
public static IList<Table> AddClusteredHint(Project project)
{
var list = new List<Table>();
foreach (var table in project.Database.Tables)
{
// we're only interested by tables inferred from M:M relations
if (table.Relation == null || table.Relation.RelationType != RelationType.ManyToMany)
continue;
// check this table definition is ok for us
if (table.RelationKeyColumns.Count < 1 || table.RelationRelatedKeyColumns.Count < 1)
continue;
// check clustered is declared on both sides
string keyHint = GetSqlServerProducerHint(table.RelationKeyColumns[0].Property);
string relatedKeyHint = GetSqlServerProducerHint(table.RelationKeyColumns[0].Property);
if (keyHint.IndexOf("clustered", StringComparison.OrdinalIgnoreCase) < 0 ||
relatedKeyHint.IndexOf("clustered", StringComparison.OrdinalIgnoreCase) < 0)
continue;
// force hint now, we only need to do this on one of the keys, not all
table.PrimaryKey.Elements[0].SetAttribute("hint", CodeFluent.Producers.SqlServer.Constants.SqlServerProducerNamespaceUri, "clustered");
// remember this table
list.Add(table);
}
return list;
}
public static void RemoveClusteredHint(IEnumerable<Table> list)
{
foreach (var table in list)
{
table.PrimaryKey.Elements[0].RemoveAttribute("hint", CodeFluent.Producers.SqlServer.Constants.SqlServerProducerNamespaceUri);
}
}
// helper method to read XML element's hint attribute in the SQL Server Producer namespace
private static string GetSqlServerProducerHint(Node node)
{
if (node == null)
return null;
return node.GetAttributeValue<string>("hint", CodeFluent.Producers.SqlServer.Constants.SqlServerProducerNamespaceUri, null);
}
}
?>
</cf:project>