Tuesday, May 24, 2022

Azure Synapse Link for SQL: From production to a data warehouse in a few clicks

The Link technology in Synapse is used to synchronize data from different data sources to Synapse Analytics. Synapse Link for CosmoDB and Synapse Link for Dataverse were already released. Now it’s time for a new and very important one: Azure Synapse Link for SQL.

The Azure Synapse Link for SQL can be used with Azure SQL Database and SQL Server 2022 to synchronize tables using these databases as sources and a Synapse Dedicated Pool as a destination.

When using Synapse Link, you are not really creating a Data Warehouse, but you are executing a big step in this direction.

The process between production and the Data Warehouse is called ETL – Extract, Transform and Load. You must execute these three steps: Extract from production, Transform the extracted data for the data warehouse structure, and Load the data into the data warehouse.

Sometimes these steps can be executed in a different sequence and many times it’s more complex with even more steps. The steps can also be expressed as an ELT process, Extract, Load and Transform. As you may notice, the difference is the sequence of the steps. In this case, you first load the data, and, after that, you transform the data.

The Load process is usually done to a staging area, where you will execute the transformation of the data to the format required by a data warehouse.

Synapse Link doesn’t execute any transformation on the data. It extracts the data from the source and loads it into the destination. In summary, using Synapse Link, you create a staging environment using very simple steps to transfer the data.

The staging environment is important because it reduces the workload over the production environment. If you transform the data before loading, the production environment would be affected by the transformation workload. On the other hand, loading the data to a staging environment and leaving the transformation for later, the transformation workload will be executed over the staging environment.

Another benefit of this staging environment is the possibility to use this environment for reporting, instead of run reports over production. In some cases, you may would like to use Synapse Link specially for that, even if you are not planning the further transformations into a data warehouse yet.

Diagram Description automatically generated

Besides relieving the production environment from the transformation workload, the staging environment can also help in scenarios with multiple data sources with similar structures. For example, imagine a company with a main office and many different branches. Each branch has its own database, but the data stored has the same schema, for the same business.

In this scenario, Azure Synapse Link for SQL can be used to synchronize the data from all the branches to a centralized staging environment. This becomes an additional benefit of Azure Synapse Link for SQL and the staging area it can easily create.

Azure Synapse Link for SQL basic elements

The structure of Azure Synapse Link for SQL uses two key elements which are always present in the different scenarios where you can implement it.

Change Feed: The change feed is a new feature included in Azure SQL Database and SQL Server 2022 to provide support to Azure Synapse Link for SQL. You may already know SQL Server has two different features to allow the control of changes in a production environment: the Change Data Capture, also known as CDC and Change Tracking. However, Microsoft decided to implement a third method to ensure the workload over the production environment would be as light as possible. This is the purpose of the Change Feed.

Integration Runtime: The IR is the same one used for pipeline execution. The IR is responsible for the start/stop operations on the source database. It can be used as an autoresolved IR or a self-hosted IR, according to the scenario which will be implemented.

Azure Synapse Link for SQL Scenarios

Azure Synapse Link for SQL can be implemented in 3 different scenarios:

Azure SQL Database: The fact both services are online inside Azure makes the implementation easier. Azure SQL Database makes some steps easier.

SQL Server 2022 in an Azure VM: SQL Server 2022 requires some additional steps for the use of Azure Synapse Link for SQL. The fact it’s installed in an Azure VM makes the process easier, allowing use of an Autoresolved integration runtime. This scenario worked well during my tests, but it’s not confirmed yet as a fully supported scenario. Officially, for SQL Server 2022, a self-hosted integration runtime is required.

SQL Server 2022 on premises: This is the scenario requiring the most work. Since the server is on premises, you will need to use a self-hosted integration runtime installed on premises to send the data to the landing zone in the cloud. The services in the cloud will not access the on-premises environment. The self-hosted IR will be the responsible for start/stop operations, and the SQL Server on premises will send the data to the cloud.

Azure Synapse Link for SQL Architecture

The basic architecture is always the same: an integration runtime is used to control the start/stop of the Link on the source database. The source database needs to support the change feed feature, it means it needs to be an Azure SQL Database or SQL Server 2022.

The source database will send all the new or changed records to a landing zone. The Synapse Workspace will load the data from the landing zone to the target database.

Diagram Description automatically generated

If the source database is an Azure SQL Database, the landing zone will be internal to the Synapse Workspace. There will not be access to the landing zone. The Azure SQL Database will need to have a system managed identity which will be used to access and save the data in this internal landing zone.

Internally, Synapse Analytics has an Ingestion Service responsible for loading the data from the landing zone to the Dedicated SQL Pool

Diagram Description automatically generated

If the source database is a SQL Server 2022, the landing zone will be explicitly created as an ADLS Gen 2 Account. During the start of the link the integration runtime (IR) will create a database scoped credential to allow SQL Server to access the ADLS Gen 2 Account. This credential will be using a SAS token to authenticate to the ADLS Gen 2 Account.

The start/stop process is executed by the IR, which will connect to the source database using the authentication provided on the linked service.

The authentication to the source SQL can use SQL Standard Authentication or Managed Identity. If it uses managed identity, the Azure AD user will need to receive access the source SQL.

Diagram Description automatically generated

Finally, if the source SQL is on premises, the IR will need to be a self-hosted IR in the on-premises environment.

Chart, diagram Description automatically generated with medium confidence

Provisioning the Azure Synapse Link for SQL

The Azure Synapse Link for SQL provisioning is done using Synapse Studio. Some steps are slightly different depending on the provisioning scenario.

  1. On the Synapse Studio left toolbar, click the Integrate button
  2. Click the Add button ‘+’

Graphical user interface, application, Word Description automatically generated

  1. Click the Link Connection menu item
  2. On the New Link Connection window select Azure SQL as the source type

Graphical user interface, text, application, email Description automatically generated

  1. On Source Linked Service, select New to create a new linked service

Linked Services are used by Synapse Analytics to establish a connection to external services. Every linked service uses an integration runtime (IR) to execute actions on the connected service.

Graphical user interface, text, application, email Description automatically generated

  1. On the Name textbox, type the name AdventureSQL
  2. Choose the integration runtime to be used. For Azure SQL, the auto-resolved runtime works, you don’t need to use a self-hosted one.

Table Description automatically generated with medium confidence

  1. Select the Azure SQL you will be connecting to.

You can select the Azure SQL from a subscription you have access to, or you can manually insert a connection string. The result for the service will be the same. This creates an interesting level of flexibility:

  • You can configure the Link Connection even if your azure account doesn’t have access to the source server. The connection string can be inserted manually, and the authentication can be recovered from an Azure Key Vault
  • Theoretically, the connection could be established to any SQL Server, including SQL Server on premise or in other clouds. In practice, Link Connections can only be established with Azure SQL Database or SQL Server 2022. Anyway, the creation of a linked service can have other purposes beyond the use for the Synapse Link.

Graphical user interface, text, application, email Description automatically generated

  1. Choose the Authentication Type which will be used.

Graphical user interface, text, application, email Description automatically generated

SQL authentication is a very well-know authentication. The other types are the following:

System Assigned Managed Identity: This is the Managed Identity automatically assigned to the Synapse Workspace by Azure

User Assigned Managed Identity: This is the customized managed identity assigned to the workspace by the developer. You can assign custom managed identities on the Identity menu item on the workspace, as you may notice on the images below. You can assign multiple managed identities, because in it’s possible to control the permissions to each linked service in an isolated way. This option is not supported by Synapse Link at the moment

Graphical user interface, text, application Description automatically generated

Application Description automatically generated with low confidence

Service Principal: Service principal is a special kind of identity. This identity is often used by applications to connect to azure resources. Create this kind of identity by creating an app registration on the Azure Active Directory. This option is not supported by Synapse Link at the moment

Even if the authentication used is the SQL authentication, the user making the configuration doesn’t need to know the password, the password could be retrieved from Azure Key Vault.

You may notice that although a linked service has 4 authentication options to an Azure SQL Database, only two of them, SQL authentication and System Assigned Managed Identity, are supported at the moment. This once again highlights the fact that Linked Services are used for many purposes in Synapse Analytics, not only for Azure Synapse Link for SQL.

When using a System Assigned Managed Identity, Identity with Azure SQL Database, you will need to add it as db_owner of the Azure SQL Database. The code bellow illustrates this with a System Managed Identity.

CREATE USER maltasynapselink FROM EXTERNAL PROVIDER;

ALTER ROLE [db_owner] ADD MEMBER maltasynapselink;

 

  1. Click the Test Connection link

The access to Azure SQL Database is controlled by a firewall. Using Azure Synapse Link for SQL, it’s Synapse which will access the Azure SQL Database. In order to allow this access, there are three options:

Enable access to Azure Services: This option opens the firewall to any service inside Azure, either the service is in your tenant or not. It’s the easiest option, used very often, but has the highest risk. I wrote about this in this article https://www.red-gate.com/simple-talk/cloud/azure/eight-azure-sql-configurations-you-may-have-missed/
Open the firewall to the Synapse Ips: Synapse has a specific range of Ips in Azure. You can open the Azure SQL Database firewall to this specific range of Ips. It’s safer than enabling access to all Azure services, but you can’t be sure that only your Synapse Workspace will be able to pass through the firewall.

In the future, the use of Private Endpoints may become available for Azure Synapse Link for SQL, but at the moment it’s not supported.

I delivered a technical session about Azure SQL networking, you can watch on this link https://www.youtube.com/watch?v=RKZy5MkqFDQ&list=PLNbt9tnNIlQ5pVwZFRVpoBG8uQTs8aIcz&index=20

Background pattern Description automatically generated with low confidence

  1. Click the Create button
  2. Select the tables you would like to include in your Link Connection

Graphical user interface, application Description automatically generated

The image above contains the Source managed identity ID. When using Azure SQL Database as a source, it needs to have a managed identity. Synapse will provide access permissions to this identity to access the internal landing zone, as explained before in this article.

You can read more about Azure SQL Managed Identity here https://www.red-gate.com/simple-talk/blogs/azure-sql-and-managed-identity/

  1. Select the target dedicated SQL Pool and database

A picture containing graphical user interface Description automatically generated

  1. On the New Link Connection window, in the Link Connection Name textbox, type sqldbconnection

Graphical user interface, text, application, email Description automatically generated

  1. Select the number of cores you would like to use for the ingestion service running behind the Link Connection.

You don’t need to use one single Link Connection for all your tables. You can break down your tables in multiples Link Connections. One reason to do so is the number of transactions each table receives. You can create Link Connections with a higher number of cores for the heaviest tables and a different Link Connection for the tables with a smaller number of transactions.

  1. Click the Ok button. This will complete the initial Link Connection creation, and you will see the Link Connection configuration window as the image below.

Graphical user interface, application Description automatically generated

  1. On the following window, you have the option to select the distribution type (Round Robin, Hash or Replicated).

Graphical user interface, text, application, chat or text message Description automatically generated

You can read more about table distribution here: https://docs.microsoft.com/en-us/azure/synapse-analytics/sql-data-warehouse/sql-data-warehouse-tables-distribute?WT.mc_id=DP-MVP-4014132

    1. On the same window, you have the option to select the table structure (Clustered Columnstore Index, Heap or Clustered Index)

Graphical user interface, text, application, chat or text message Description automatically generated

You can read more about table design here: https://docs.microsoft.com/en-us/azure/synapse-analytics/sql-data-warehouse/sql-data-warehouse-tables-overview?WT.mc_id=DP-MVP-4014132

      1. Still on the same window, you can customize the schema and table name.

Important: Initially the schema and table name will be the same as in the source system. However, the schema will not be created by Azure Synapse Link for SQL. If the schema doesn’t exist in the target dedicated pool the execution will generate an error. If you are using a schema other than DBO, you need to create the schema before starting the link

Additional Options

There are two additional options you can set before publishing the Link Connection. The image below illustrates these options

Graphical user interface, application Description automatically generated

Drop and recreate table on target

When this option is selected, if the target tables already exist, they will be dropped. This means the synchronization will need to start again, transferring all the data from the source to the target.

This is something you would not like to happen. However, it’s important to keep in mind how the Stop button for the Link Connection works. It’s easy: Don’t stop the link. Every time you stop the link, when you start it again, it will be required to drop the destination tables and start from the beginning.

There is no need to stop the link. If you would like to include or exclude tables, you can do this without stopping the link. If you remove a table from the Link Connection and add it again, the table will be re-seeded, but only this single table, not all tables in the Link Connection.

Very Important: You never stop a Link Connection. If you stop a Link Connection, you will need to drop the target tables and start the synchronization again from the beginning and this will be heavy. Interruptions can happen, you can stop the SQL Pool, but there is no need to stop the Link Connection and you shouldn’t do it.

Enable transaction consistency across tables

This option will ensure the records will be transaction consistent across the tables in the same Link connection.

Of course, not all tables in your source database will have this transactional relation. You don’t need to limit yourself to a single link connection for each source. You can break down your tables among multiple link connections, grouping the tables according to the transactional consistency needed.

Starting the Link Connection

After configuring the Link Connection, you must publish the changes on the workspace before starting the link.

The Publish button is always highlighted when there are pending changes in the workspace. Once you click the Publish button, you can review the changes on the Publish All window and click the new Publish button on this window.

Graphical user interface Description automatically generated with low confidence

After publishing, you can click the Start button on the Link Connection. Once started, as mentioned before on this article, you don’t stop the Link Connection. If you stop the Link Connection, you will need to start the synchronization again from the beginning.

Monitoring the Link Connection

Once you start the Link Connection, you can monitor it on the Monitor tab, Link Connections menu item.

Graphical user interface, application Description automatically generated

The monitoring information is displayed in two different levels: The existing link connections and the tables inside each link connection.

Graphical user interface, application Description automatically generated

There are two levels of possible errors:

      • Link Level errors: Errors on the level of the link. For example, if the link can’t reach the source machine to start the configuration, this is a link level error. The link level errors are also highlighted on the Link window on the Integrate tab.
      • Table Level errors: Any error specific to one table. For example, if the primary key of the table is not acceptable for the table, it will appear as a table level error.

Important: Even if all the tables have errors, they will not appear as errors on the Link window. The message on the Link window advises you to check the monitoring even if it appears the Link is running correctly. This is a good advice, as you may notice in the image below, from the Link window, in the Integrate tab.

Once you click one existing link connection inside the Link Connections monitoring window, you can see the tables inside the link connection, like the example below.

Graphical user interface, application Description automatically generated

There are three possible statuses for the tables inside the Link Connection:

      • Snapshotting, when the initial table snapshot is being created to initialize the link.
      • Replicating, when the replication is running correctly.
      • Error, when an error has happened

Azure Synapse Link for SQL and SQL Server 2022

There are very few differences when implementing the Azure Synapse Link for SQL with SQL Server 2022. Let’s analyse them.

The source database requires a master key

As explained before, a database scoped credential will be created to allow SQL Server to access the landing ADLS Gen 2 account. If your database doesn’t have a master key yet, you can create it using the statement below.

create master key encrypt by password='YourPassword'

 

After starting the Link Connection, you can check the database scoped credential by using the query below.

select * from sys.database_credentials

 

Graphical user interface, text, application Description automatically generated

The source database requires an Owner

Sometimes, when restoring a database from a backup or after some other activities, the database can end up without a database owner.

This is not a good practice and the lack of the owner in the configuration can cause some other problems as well.

You can use the statement below to set the owner for the database. In the statement below, I’m defining SA as the owner. This is not a good practice. You may need to plan better which login you will set as the database owner.

alter authorization on Database::AdvWorks2019 to sa

 

You can read more about the importance of the database owner choice on this article: https://www.red-gate.com/simple-talk/blogs/careful-trustworthy-setting/

The landing area is explicitly created as an ADLS Gen 2 Account

When creating a Link Connection using SQL Server as a source, the landing area is provisioned together the Link Connection. As you may notice on the image below, you will need to configure an ADLS Gen 2 Account as a landing area.

Graphical user interface, text, email Description automatically generated with medium confidence

Some considerations at this point:

      • The ADLS Gen 2 Account will be connected to the Synapse Workspace using a linked service.
      • The connection from SQL Server to the landing zone will be made using a SAS key which will be created in the source SQL Server during the process of starting the link
      • The Link Connection will use the IR configured in the linked service to access the landingzone. It will use the linked service authentication to access the landing zone
      • The ADLS Gen 2 account needs to be created before the Azure Synapse Link for SQL provisioning process.
      • You can create the SAS key during the Link Connection provisioning process by clicking the Generate Token link. This will open the window you can see on the image below.

      • As every SAS key, this one also has an expiration date and will need to be rotated.

You rotate the key without stopping the Azure Synapse Link for SQL (what is something you should never do, as mentioned before). The image below shows the Rotate Token button on the Link Connection properties window.

Graphical user interface, text, application, chat or text message Description automatically generated

The Rotate Token window is slightly different than the window to create the token. When rotating the token, you have the option to create a new SAS key or input one manually. This means that you can decide about using an Azure Storage Account Policy later, after the container is already in use.

Graphical user interface, text, application, email Description automatically generated

Graphical user interface, text Description automatically generated

      • You can create the SAS key manually instead of letting the provisioning process create the key for you.

Creating the key manually allows you to create the key linked to an azure storage policy, which can make it easier to automate the rotation of the key. You can read more about the benefit of Storage Account policies on this link: https://www.red-gate.com/simple-talk/blogs/azure-storage-policies-control-sas-from-the-server-side/

If you decide to create the SAS key manually, it’s important to mind the SAS key will need the following permissions: RACWDL (Read, Add, Create, Write, Delete and List)

Summary

The Azure Synapse Link for SQL is not the entire way from production to a data warehouse, but it makes the ETL/ELT process way easier by synchronizing the data with the Synapse dedicated SQL Pool, relieving the production environment from further ETL workload, and allowing you to proceed from this point with the transformation of the data for the data warehouse.

The post Azure Synapse Link for SQL: From production to a data warehouse in a few clicks appeared first on Simple Talk.



from Simple Talk https://ift.tt/wrNKqks
via

The VALUES clause or building tables out of nothing

The VALUES clause is probably one of the most misused features in SQL. If you look at SQL forums online, you’ll see people use it as the second clause in an insertion statement, but they only use it to construct a single row at a time, thus:

BEGIN
INSERT INTO Zodiac (astro_sign, astro_start_date, astro_end_date)
 VALUES ('Aries', '2022-03-21', '2022-04-19');
INSERT INTO Zodiac (astro_sign, astro_start_date, astro_end_date)
 VALUES ('Taurus', '2022-04-20', '2022-05-20');
… 
INSERT INTO Zodiac (astro_sign, astro_start_date, astro_end_date)
 VALUES ('Pisces', '2023-02-19', '2023-03-20');
END;

Each insertion statement ends with a semi-colon, so they will be executed separately and in the order presented. An optimizer doesn’t dare combine them because there might be a forward reference to previous insertions.

I think people write this kind of code because that this is how you would read punch cards. Each card goes into a card reader, gets buffered, and written in the order presented to the magnetic tape or disk file. Welcome to 1960! Stop mimicking old programming languages like FORTRAN or BASIC that had WRITE statements and put one record at a time into a file. Start thinking of working with entire sets.

Using VALUES to insert rows

The VALUES clause is more appropriately called a table constructor. Each row constructor within the table is a comma-separated list enclosed in parentheses. Officially, there is an optional keyword ROW. They can be placed at the start of each list. Nobody does this, and it is a bit redundant, but was required in MySQL.

One of the worst ways of constructing a table is to use the CREATE or DECLARE construct to build a temporary table, load it with insertion statements, and finally insert the table into the desired destination. This leads to multiple statements with no way to really optimize the insertion and shows that you are really not thinking in sets yet.

The entire zodiac can be inserted with a single statement like this:

INSERT INTO Zodiac (astro_sign, astro_start_date, astro_end_date)
VALUES (
 ('Aries', '2022-03-21', '2022-04-19'),
 ('Taurus', '2022-04-20', '2022-05-20'),
 ('Gemini', '2022-05-21', '2022-06-21'),
 ('Cancer', 2022-06- 22', '2022-07-22'),
 ('Leo', '2022-07-23', '2022-08-22'),
 ('Virgo', '2022-08-23', '2022-09-22'),
 ('Libra', '2022-09-23', '2022-10-23'),
 ('Scorpius', '2022-10-24', '2022-11-21'),
 ('Sagittarius', '2022-11-22', '2022-12-21'),
 ('Capricorn', '2022-12-22', '2023-01-19'),
 ('Aquarius', '2023-01-20', '2023-02-18'),
 ('Pisces', '2023-02-19', '2023-03-20')
);

Given a whole set of rows, the optimizer can deal with a single atomic statement. Not only does it save execution time as compared to the row-at-a-time model of insertion, but it presents the optimizer with an opportunity to improve things. The insertion statement can rearrange the list of new rows and pick an optimal ordering. It also means that if one of my rows had an error in it, I wouldn’t have to back out all of the other rows. If I wanted a proper ACID transaction model, I would’ve had to back out each individual insert up until I came to the insertion that gave me the error.

Here’s the basic syntax. Please note that besides including an expression of the proper data type, you can use the keywords DEFAULT or NULL in a row constructor. Obviously, those values must make sense in relation to the declaration of the table into which you are inserting.

VALUES (<row value expression list>) [ , ...n ]
 <row value expression list> ::= {<row value expression> } [ , ...n ]
 <row value expression> ::= { DEFAULT | NULL | <expression> }

Please remember that an expression is not always a simple constant. In fact, it’s very handy to use the CAST (<exp> AS <data type>) function as a way to assure that a column in the constructed virtual table has a known data type:

VALUES (CAST(‘foobar’, AS NVARCHAR(10), 
      CAST(42 AS INTEGER), CAST(3.14159 AS REAL))

The AS keyword can also be used, to give the constructed tables each a name. Here is skeleton:

SELECT X.a, X.b, X.c, Y.a, Y.b, Y.c
 FROM
(VALUES (1,2,3) , (4,5,6) ) AS X(a, b, c) ,
(VALUES (1,2,3), (4,5,6) ) AS Y(a,b,c)
WHERE X.a =Y.a
 AND X.b = Y.b
 AND X.c <= 0.0;

MERGE with VALUES Clause

The MERGE statement was added to Standard SQL several years ago. It was based on a proposal by ANSI representatives from Oracle and IBM, but forms of it had already existed in other products, though under a different name. The most common one was UPSERT from Postgres. Let’s jump right into it.

One table expression is the target, the table you are trying to modify. The other table expression is the source, the table that provides the modifications. Presumably, you want the target to persist, but you don’t need the source to persist after the updates and insertions are done.

The MERGE clause defines the target; the USING clause defines the source. And the ON clause matches the two tables. The WHEN [NOT] MATCHED ...THEN clauses determine the action to be taken

MERGE INTO Sales.Sales_Reasons AS Target
USING (VALUES ('Recommendation', 'Other'), 
          ('Review', 'Marketing'), ('Internet', 'Promotion'))
  AS Source (new_sales_name, new_reason_type)
ON Target.sales_name = Source.new_sales_name
WHEN MATCHED
THEN UPDATE SET reason_type = Source.new_reason_type
WHEN NOT MATCHED
THEN INSERT (sales_name, reason_type)
VALUES (new_sales_name, new_reason_type);

 

It’s easier to think of the MERGE statement as a program, written as a single statement Instead of having IF–THEN–ELSE logic or CASE expressions in multiple statements.

Obviously, updating makes sense only when there is a match, and inserting makes sense only when there is not a match. The standards allow for either of these clauses to include an optional … AND <search condition>, so you can add quite a bit of logic to this one statement. Technically, the WHEN clauses list can finish with the ELSE IGNORE; it acts as a placeholder just as the ELSE clause did in the CASE expression. Microsoft has more extensions to the syntax, and there have been some performance issues. If you are using it in SQL Server, I strongly suggest checking both the syntax and current performance in whichever version of SQL Server you’re running.

Conclusion

The VALUES clause is ANSI standard and implemented by many relational database vendors. The VALUES clause can save typing, and it’s also the rare case when easier can mean better performance because the rows will be treated as a set.

 

The post The VALUES clause or building tables out of nothing appeared first on Simple Talk.



from Simple Talk https://ift.tt/kec5hyv
via

Monday, May 23, 2022

Power BI: When a Power Query Native Query is not enough

In Power BI, when importing data with Power Query, one basic performance concept is the use of native queries. The transformations will perform better if they can be converted to a native query, especially a single native query for all transformations.

However, this is just a starting point for the optimizations. Sometimes, native queries for the transformations are not enough.

Test Environment

This will be the starting point:

  • An Azure SQL Database using the sample AdventureWorskLT
  • You need to execute the script Make_big_adventure.SQL adapted for the AdventureWorksLT. You can find it on https://github.com/DennesTorres/BigAdventureAndQSHints/blob/main/make_big_adventureLT.sql
  • Recommendation: The Azure SQL Database is recommended to have 10 DTU’s or more. Less than that and some slowness may be noticed
  • In Power BI we will import the tables BigProduct, BigTransactionHistory and SalesLT.ProductModel

Graphical user interface, text, application Description automatically generated

Transformations and a Date Dimension

A model needs a date dimension. Every fact happens on a date and the date is an important dimension to analyse the fact. In this example, the TransactionDate column is found in the TransactionHistory table.

Why is the TransactionDate field is not enough, you may ask.

When analysing the facts, it might be analysed by Year, Month, Day, Day of the week, and much more. If relying only on the TransactionDate field, you will need to create DAX measures, and this would impact the performance of your model.

Building a date dimension, you will not have the need to build so many DAX expressions and the model will have better performance.

We can build a dynamic date dimension, retrieving the minimum and maximum date from the TransactionHistory table for that. That’s where our problems start.

The Wrong way

1) On TransactionHistory table, select the column TransactionDate

2) Change the Data Type of the column to Date

If you need to handle time in your model, date and time needs to be two different dimensions and two different fields in the fact table. A time dimension will have only 24 rows if built with hour granularity, 1440 if built with minute granularity and so on. On the other hand, if Date and Time were managed as a single dimension, we would have 1440 rows for each day, or something similar. That’s why date and time needs to be different dimensions.

In our example, we don’t really have time information. We will just ignore the time by changing the data type to date.

Table Description automatically generated

3) Righ-click the TransactionHistory table

4) Select the Reference menu item

We can duplicate the TransactionHistory query or make a reference to it. Let’s start with a reference and understand the consequences later.

Graphical user interface, application, Word Description automatically generated

5) On the new query, select the TransactionDate column

6) Click the Remove Other Columns menu item

Graphical user interface, application, table Description automatically generated

7) Click the button on the right side of the TransactionDate column header

8) Click the Sort Ascending menu item

Graphical user interface, application Description automatically generated

9) Click the menu option Keep Top Rows

Graphical user interface, application, Word Description automatically generated

10) On the Keep Top Rows window, type “1” to keep only 1 row

Graphical user interface Description automatically generated

11) Right click the value of the row and click the menu item Drill down

Even with a single row and field, the result of the query is still a table. We need to transform it to a single value to use it as a parameter for the function we will build next.

Graphical user interface, text, application Description automatically generated

12) Right-click the “TransactionHistory (2)” table and disable the option Enable Load

We don’t need this value to be part of the model. But if we leave the load enabled, a new step will be created in the end of the query to transform it into a table, and it will end up failing.

Graphical user interface, application Description automatically generated

13) Rename the “TransactionHistory (2)” table to MinDate

Graphical user interface, application Description automatically generated

14) Repeat the steps 4-12, but now sorting in descending order

15) Rename the new table to MaxDate

Power Query: The Problem

If you right click the Keep Top Rows step of the MinDate query, you may notice the View Native Query is active. This option is only disabled on the Drill Down to the TransactionDate field.

Graphical user interface, application Description automatically generated

All the most expensive steps were transformed into a native query. A superficial view would make us believe the transformations are as optimized as possible, but that’s not true at all.

The query below is the native query built by Power BI.

Graphical user interface, text, application Description automatically generated

Let’s analyse the execution plan. We can copy the query from Power BI to SSMS and check the estimated execution plan. As you may notice, this execution plan is terrible:

A picture containing Word Description automatically generated

  • It’s using a table scan, there is no index for this execution plan
  • There is a Sort operation. Sort operations in execution plans are very heavy and should be avoided at all costs.

The first idea would be to create an index based on the TransactionDate, the column used in the transformations. The Create Index statement would be like this one:

CREATE NONCLUSTERED INDEX [inddate]
  ON [dbo].[bigTransactionHistory] ( [transactiondate] ASC )

go 

After creating the index, this will be the new query plan:

Graphical user interface, application Description automatically generated

The table scan was replaced by an Index Scan, but the Sort operation is still present, and you may notice it takes 95% of the query cost.

You may ask why the Sort was not solved by the index itself. If you check the query, you may notice the inner queries use a Convert function over the TransactionDate field to transform it to the Date type.

The Order By is executed over the result of the Convert, so it can’t use the index. The Convert function needs to be executed first and the result needs to be ordered.

In Summary: The order of the transformations is affecting the query performance. If the data type were one of the last transformations, the query plan could be better. But before reaching the solution, we will need to solve another problem.

Reference vs Duplicate

The data type transformation is located on the TransactionHistory table. The queries to calculate the MaxDate and MinDate have reference to the TransactionHistory query, so they all contain the data type conversion.

We could think about removing the data type conversion from the TransactionHistory query, but this would not work very well.

On the result, the TransactionHistory table will need to be linked with the date dimension. Both date fields will need to have the same data type, so the TransactionHistory query will need the data type transformation.

The solution for this problem is to use duplicate, instead of reference. If we duplicate the TransactitonHistory query before applying the data type transformation, we will have control of the data type transformation on the MinDate and MaxDate query and we will still be able to apply the same data type transformation on the TransactionHistory without affecting the other ones.

This is a very interesting example because we can clearly see the difference between Reference and Duplicate of a query and this example will only have good performance if we duplicate the query.

But when duplicating the query, aren’t we multiplying the execution time? If the queries are completely transformed in different native queries, the “duplication” of the execution time would happen anyway but isolating the queries with the Duplicate option we can optimize each one to make them faster.

In summary, on our example the secret is duplicate the TransactionHistory before changing the data type, implement each of the duplications, leaving the change of the data type for last and finally changing the data type of the TransactionDate field in the TransactionHistory query.

The Result

The sequence of the tasks is different, we leave the change data type and drill down for last. They will be executed over a single value and will not become part of the native query.

Graphical user interface, application Description automatically generated

The native query is simplified, without the type conversion.

Graphical user interface, text, application, email Description automatically generated

This makes a way better query plan, making a good use of the index for the transformations and making the result way faster

Text Description automatically generated with medium confidence

After Match

After analysing and solving these performance problems, let’s complete the example creating the date dimension.

We can use a function written in M by Chris Web. You can find the function on this link https://blog.crossjoin.co.uk/2013/11/19/generating-a-date-dimension-table-in-power-query/

  1. On the top menu, click the button New Query-> Blank Query

Diagram Description automatically generated with medium confidence

  1. Click on the menu View->Advanced Editor

Graphical user interface, application, table Description automatically generated

  1. In the Advanced Editor window, paste the query copies from the Chris Webb blog

Text Description automatically generated

  1. Click the Done button
  2. Rename the function to BuildDateDimension

Graphical user interface, application Description automatically generated

  1. On the top menu, click the button New Query-> Blank Query
  2. Click on the menu View->Advanced Editor
  3. Add the following Query:

let
  Source = BuildDateDimension(MinDate,MaxDate)
in
  Source
  1. Click the Done button
  2. Rename the query to DateDim

Graphical user interface, application, Word Description automatically generated

Lessons Learned

  • It’s important to know SQL Server and query optimization to work with Power BI
  • Sometimes the optimization is beyond Power BI, it’s on the source system
  • In Power bi ELT’s, if you make table level transformations and filters first and leave column level transformations for last, the native queries may be easier to optimize
  • You need to take care with the decision between Reference and Duplicate

The post Power BI: When a Power Query Native Query is not enough appeared first on Simple Talk.



from Simple Talk https://ift.tt/KMpgRCu
via

Inline PDF Viewer in an Angular App? Now you can

PDF and web have never been friends — so much so that most users always download a PDF before viewing it. This has changed a lot in recent years. Browsers do support the viewing of pdfs in separate tabs nowadays. For most use cases, downloading plus the ability to show a PDF in a tab would suffice.

But, developers have been hungry. They wanted to show the PDF inside their website so that users could view and sign them, read them like a book, and so on. In short, a better user experience was lacking when users were forced to download a PDF or open it in a separate tab/window. This created the need for a PDF viewer which can be easily integrated into Angular. There were a lot of small and partial solutions arising in this space, yet none was available for Angular developers.

Angular developers like myself have suffered greatly due to a lack of a quality library that can be used to show a pdf without losing the user experience.

Enter ng2-pdfjs-viewer, and the Angular developer’s fight with PDF is over!

The ng2-pdfjs-viewer component is built on top of Mozilla’s viewerjs and pdfjs, so its core is solid. It does have easy-to-use attributes along with the ability to customize anything which pdfjs supports. You can find the code demonstrated in this article here.

Usage can be as simple as

<ng2-pdfjs-viewer pdfSrc="sample.pdf"></ng2-pdfjs-viewer>

And viola, the PDF sits right inside the Angular application like this:

Diagram Description automatically generated

Now the question is – what else can I get out of it?

Here are some examples. Suppose you wanted to show two versions of the same document for comparison side by side in your web application. Now you can. Do you want to open the PDF in a separate browser window for traditional viewing? No problem. Do you like to show a print preview dialog automatically after opening the PDF in a new browser window? Piece of cake. Automatically download the pdf? Got it.

This pdf viewer supports tons of other features, and you have fine control of what to do with it.

Setup ng2-pdfjs-viewer in an Angular App

Follow these steps to set up the component:

1. Installation – Like any other package – get it from the npm registry

$ npm install ng2-pdfjs-viewer --save

This is a standard npm package installation command. Make sure it gets installed in dependencies using the --save parameter.

2. Configuration – Let your app know you would like to use it

Set it up in your angular AppModule:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { PdfJsViewerModule } from 'ng2-pdfjs-viewer'; // <-- Import PdfJsViewerModule module
@NgModule({
  declarations: [
        AppComponent,
  ],
  imports: [
        BrowserModule,
        PdfJsViewerModule // <-- Add to declarations
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

As shown here, the module to be imported is PdfJsViewerModule; this is required as this is the module that makes sure ng2-pdfjs-viewer is ready to be used.

It is equally important to add the module PdfJsViewerModule into the imports section of @NgModule. With this step, you are almost ready to use the inline PDF viewer.

3. Build – Add a build step, so that your angular app has a copy of pdfjs

The ng2-pdfjs-viewer component is built on top of pdfjs, which also means that it’s needed for this angular component to work properly. There are several ways this can be achieved, from the manual process of copying relevant files to automated build scripts. Here are the two most popular mechanisms angular developers use when they need extra files to be copied as part of the build step.

Either add an angular build step into angular.json:

"assets": [
  { "glob": "**/*", "input": "node_modules/ng2-pdfjs-viewer/pdfjs", "output": "/assets/pdfjs" },
]

Or use webpack or similar bundlers (Hmm, are you still using webpack?)

var TransferWebpackPlugin = require('transfer-webpack-plugin');
...
plugins: [
  new TransferWebpackPlugin([
        { from: 'node_modules\ng2-pdfjs-viewer\pdfjs', to: path.join(__dirname, 'assets') }
  ])
]

PDF Loading Events

Often, you might like to tap into the PDF pipeline of printing or loading to execute a task. This could be to show a message to the user that the PDF is loaded for large PDFs or that the PDF is successfully printed, etc. The code found here provides several events hooks for that.

HTML

<!-- your.component.html -->
<ng2-pdfjs-viewer pdfSrc="gre_research_validity_data.pdf"
                viewerId="MyUniqueID"
                (onBeforePrint)="testBeforePrint()"
                (onAfterPrint)="testAfterPrint()"
                (onPagesLoaded)="testPagesLoaded($event)">
</ng2-pdfjs-viewer>

For events to work properly, you should set viewerId. This helps event routing understand which component the event is to be sent to, even if there is more than one ng2-pdfjs-viewer component on the page. viewerId should be a unique id (like a guid).

Angular component

Once capturing these events, developers can execute custom tasks/code to take action based on these events. Given below is an event which emits and displays a number of pages in PDF.

<!-- your.component.ts -->
public testBeforePrint() {
        console.log("testBeforePrint() successfully called");
}
public testAfterPrint() {
        console.log("testAfterPrint() successfully called");
}
public testPagesLoaded(count: number) {
        console.log("testPagesLoaded() successfully called. Total pages # : " + count);
}

You can see the events that are emitted on the developer console as shown below.

Graphical user interface, text, application, email Description automatically generated

What about PDF files returned from an API?

The ng2-pdfjs-viewer component can also work with other server-side APIs to render returned PDFs. To get this going, you would convert the PDF into a byte[] array or blob and give it to the viewer.

A bit of HTML in an Angular component

<!-- your.component.html -->
<div style="height: 600px">
        <ng2-pdfjs-viewer #pdfViewer></ng2-pdfjs-viewer>
</div>

Notice the #pdfViewer. This is your reference.

Some download code

The downloadFile() function calls the API; you may use any HTTP querying mechanism here. The requirement is that the API endpoint returns the pdf as a byte array.

<!-- your.component.ts -->       
 @ViewChild('pdfViewer') public pdfViewer;
constructor(private http: HttpClient) {
        let url = "api/document/getmypdf";
        this.downloadFile(url).subscribe(
        (res) => {
                this.pdfViewer.pdfSrc = res; // pdfSrc can be Blob or Uint8Array
                this.pdfViewer.refresh(); // Ask pdf viewer to load/refresh pdf
        }
        );
}
private downloadFile(url: string): any {
        return this.http.get(url, { responseType: 'blob' })
        .pipe(
                map((result: any) => {
                return result;
                })
        );
}

A sample API using C# and ASP.NET Core

[HttpGet]
[Route("GetMyPdf")]
public IActionResult GetMyPdf()
{
        var pdfPath = Path.Combine(Directory.GetCurrentDirectory(),"sample.pdf");
        byte[] bytes = System.IO.File.ReadAllBytes(pdfPath);
        return File(bytes, "application/pdf");
}

I used ASP.NET Core and some C# here. Don’t worry; you can do this in Python or Ruby or whatever server-side technology you prefer, or any APIs supplying pdf through HTTP endpoints.

Wrap up

The ng2-pdfjs-viewer component is a powerful tool to display PDF files without losing the user experience. If you are a student programmer who is building a pdf book library angular app or an enterprise programmer who wants to display a PDF stored away somewhere in SharePoint, this library is useful. The ability to show more than one PDF on the same page also helps with the comparison of different versions of a document. More on that later!

 

The post Inline PDF Viewer in an Angular App? Now you can appeared first on Simple Talk.



from Simple Talk https://ift.tt/CBbOdpL
via

Friday, May 20, 2022

Security in MySQL: Part One

Security is a critical part of any infrastructure – it’s even more so in the database world, where one step in the wrong direction can be the cause of system disruptions and downtime, customer dissatisfaction, and in the worst-case scenario – deaths.

As MySQL is one of the primary relational database management systems being used in the world today, it’s critical to understand how to go about properly the database infrastructure to keep data breaches away from the organization’s websites or, if they’ve happened already, to become a thing of the past.

Why secure MySQL?

First, the basics – why should you secure your MySQL infrastructure in the first place?

You see, chances are that both you and people that use software developed by you, whether knowingly or not, provide the website with data that is then processed by a database. Regardless of what the website is about, data is still a critical part of any database-backed infrastructure. Users inside of the database mean more exposure to a specific project, blog posts probably mean marketing, and products and customers inside of it usually mean revenue to your business.

However, the sad fact is that people usually think about securing their most critical infrastructure only when it’s too late to do so; once a data breach happens, everyone’s scrambling to save themselves from identity theft by using data breach search engines and archives and putting efforts into research related to how they should go about protecting their database in the future. As sad as it would be to state it, such efforts are often futile; if you don’t put efforts into database security before a thief comes knocking on the door, the data taken from a MySQL database will be exploited for identity theft purposes, sold (then reused for identity theft attacks), twisted in other ways, and finally, archived somewhere in a dark alley of black-hat hackers evaluating the strength of the next database – their next upcoming victim. Doesn’t sound like a very promising scenario, does it?

How to secure MySQL?

The security of MySQL infrastructure can be conveniently split into multiple categories:

  • Access control.
  • User security.
  • The components and plugins that help keep MySQL safe.
  • Security considerations and general security guidelines.
  • Enterprise-level security controls.

In the list above, I have outlined seemingly few categories – however, if you think about it, the majority of security issues fall somewhere within their range from one side or another: improper access control is often the cause of SQL injection escalation, insecure user accounts might mean guessable passwords, missing security plugins mean missing out on the security features offered by MySQL which makes the job easier for an attacker.

I’m now going to go through these points one by one in detail. One article is probably not sufficient to cover all of these issues, though, so if something’s missing in this one, please head over to the following parts of this guide.

Access control in MySQL

Controlling access in MySQL is arguably the cornerstone of its security. After all, if access to every resource were so heavily restricted that nobody except the people who absolutely need it could access it, there would be many fewer issues related to data theft, right?

While there is a degree of truth in that statement because, with MySQL, everything gets a little more complex. In this RDBMS, access control usually entails several aspects, including, but not limited to the following:

  • Properly setting up privileges for every user.
  • Limiting a specific account.
  • Account locking and unlocking.
  • User activity control.
  • Password security.

Properly setting up privileges is one of the most important aspects of access control. Simple GRANT and REVOKE statements can either give or, as the name suggests, revoke privileges to and from users. The proper assignment of privileges is said to be crucial for the security of any infrastructure backed by MySQL; the stronger strategy of assigning the privileges is, the less chance the attacker has to penetrate the defenses.

Privileges span multiple categories: they can be either administrative (meaning that they can enable users to control what operations MySQL performs and how it does it), they can apply to a specific database, or span database objects (i.e., things that are stored inside a database.) Some of the privileges are as follows:

Privilege

Explanation

ALL

Granting this privilege would, as the privilege itself suggests, grant ALL privileges to a specific user. Dangerous from a security point of view, but can be used in a local environment when testing features and whatnot.

CREATE

Enables a specific user to create databases and tables within them.

ALTER

Enables a user to alter a specific table – in other words, enables a user to change table structure.

DELETE or DROP

Enables a user to delete rows or drop entire tables and databases.

 

Privileges in MySQL also have a couple of brothers named roles. Roles are collections of privileges, and granting a specific role to a user means granting all of the privileges assigned to that role; it’s all pretty self-explanatory. Find the full list of privileges here, and for a more thorough explanation of what privileges are and what they do, head over to this part of the documentation.

It can be very useful to limit specific accounts, but such a feature is often overlooked. It’s possible to set a limit on the number of queries that can be issued every hour by a specific account, how many times an account can connect to the server, how many connections can a specific account make to the server at one moment, etc. The MAX_USER_CONNECTIONS variable defines how many connections a given account can make at the same time; the MAX_CONNECTIONS_PER_HOUR variable will define how many connections per hour can be made; MAX_UPDATES_PER_HOUR will set boundaries on how many UPDATE queries can be run in an hour, and so on. The usage of such variables will look similar to the following query (replace YOUR_VARIABLE with the variable you want to set.) Also, keep in mind that all variables set by the client revert back to normal if they’re not specified inside of my.cnf.

ALTER USER ‘your_user’@’localhost’ WITH [YOUR_VARIABLE] 0;

Accounts can also easily be locked (that prohibits any further activity from originating from them) by issuing a simple ACCOUNT LOCK command. It works when creating or modifying the account:

[CREATE USER / ALTER USER] demo_account IDENTIFIED BY ‘verystrongpasswordhere’ ACCOUNT LOCK;

You can check if a specific account is locked by issuing a query such as the one below which also tells on which which host it resides):

Image with query SELECT host, account_locked FROM mysql.user where user = 'root'; and results localhost, N

You can unlock an account by specifying ACCOUNT UNLOCK instead of ACCOUNT LOCK. That’s it!

Password security comes down to a couple of simple things as well: MySQL allows password expiration. You can set a “lifetime” for passwords by using a default_password_lifetime variable in my.cnf. You can also impose password reuse restrictions through the use of password_history, which defines how many previous passwords need to be “blacklisted” before being allowed to be used again, and password_reuse_interval, which prohibits using any passwords that were used within the last X days.

User security

Another thing closely related to access control and password security is the security of MySQL users themselves. The majority of the recommendations within this sphere can seem pretty basic at first glance, but when combined with the things mentioned above, they all can create a powerful force of security within MySQL. To further user account security within MySQL, consider not sending passwords over plain text and send them using SSL instead (use the REQUIRE SSL option when creating a user once SSL is configured on your server), avoid running MySQL as root (the root user has the FILE privilege which can cause the server to create files), and, of course, require all users to have strong passwords. I will elaborate on this in the next part of this series, but completing the outlined steps should be a good preventative to ensure that your database stays secure whatever happens.

Summary

I hope that this article has widened your horizons in the MySQL space. Follow the advice outlined in this blog post by tightening up your users and using proper access controls, and your database will surely ride fast on the security highway. However, that’s not it. To properly secure your database, you will also need to take care of plugins that help keep MySQL safe from attacks, keep an eye on enterprise-level security control, and follow general security guidelines whenever you’re working with it.

I hope that this article has been informational, and you will share it (or at least the knowledge contained within this article) with your friends to help them secure their MySQL instances. My next article will cover more ways to secure MySQL. Until next time, be sure to put what you’ve learned in practice.

 

The post Security in MySQL: Part One appeared first on Simple Talk.



from Simple Talk https://www.red-gate.com/simple-talk/databases/mysql/security-in-mysql-part-one/
via

Friday, May 13, 2022

Creating unique datasets with managed code

Figuring out uniqueness in large datasets is somewhat trivial in SQL via the DISTINCT statement. This DISTINCT technique, however, puts a load on the SQL box to where it is more beneficial to scale out horizontally in managed code instead. Typically, it is much easier to spin more web boxes to handle traffic than it is to stand up a beefier database. Moving the work into managed code scales indefinitely to increase throughput and reduces SQL pressure.

In this take, I will show you some techniques when working with duplicate data in managed code. I will explore common gotchas and show you what to do about this.

The code will be written in C# in .NET 6, so be sure to install a copy on your local machine. If preferred, LinqPad can be used, and you will be able to copy-paste and execute code in this tool. Alternatively, feel free to clone the sample code from GitHub.

To begin, be sure to bring in the following using statements. I will use the stopwatch and write to the console often, so it is good to have these available.

Using System.Diagnostics;
using static System.Console;

I will use a timer to take performance snapshots for each technique. The goal here isn’t to be precise but to get a general feel for what is happening under the covers. I am running this code using a Debug build on an Intel 11th gen i7 1.4 GHz with 8 cores and 32GB of RAM. Your exact results may vary on your machine.

A simple example

A typical use case, and one you may already have experience with, is figuring out distinct numbers in a list of arbitrary numbers. C# makes this relatively painless via Distinct.

WriteLine("Simple Distinct");
new[] {1, 1, 2, 3, 4, 5}.Distinct()
  .ToList()
  .ForEach(n => Write(n + " ")); // 1 2 3 4 5
WriteLine();
WriteLine();

Because value types have good equality support, the built-in functionality works effortlessly. The underlying algorithm can distinguish between different numbers and find unique values in the set. However, a real issue starts to emerge with reference types.

Bare distinct

In the real world, complex data types dominate business applications. Say I have a bunch of lab rats, three million to be exact, and I need to figure out a distinct set without any duplicates.

In object-oriented fashion, a lab rat might look like this:

public class LabRatA
{
  public string Name { get; set; } = string.Empty;
  public int TrackingId { get; set; }
  public Color Color { get; set; }
}

public enum Color
{
  Black,
  White,
  Brown
};

This lab rat has a name, tracking id, and color. This is an anaemic type because it is just a collection of properties without any encapsulated logic.

To generate three million rats, an extension method like Times comes in handy:

const int uniqueEntries = 300;

var ratsA = 3000000.Times(x => new LabRatA
{
  Name = "LabRat_" + x % uniqueEntries,
  TrackingId = x % uniqueEntries,
  Color = (Color)(x % uniqueEntries)
}).ToList();

public static class EnumerableExtensions
{
  public static Ienumerable<T> Times<T>(
    this int count, Func<int, T> func)
  {
    for (var i = 1; i <= count; i++) yield return func(i);
  }
}

A modulus with uniqueEntries will generate duplicate data every three hundred entries. This makes the entries 300/3,000,000 unique or about 0.01 percent unique. A somewhat realistic scenario when you have a ton of duplicate records.

The extension method makes this a bit more fluent and easier to express in code. This method extends an integer like 3000000 and lets the code dot into a lambda expression that generates lab rats.

A way to figure out distinct entries can be done like this:

WriteLine("Bare Distinct");
stopWatch.Start();
WriteLine(ratsA.Distinct().Count()); // 3000000
stopWatch.Stop();
WriteLine($"{stopWatch.ElapsedMilliseconds} ms"); // 451 ms
WriteLine();

This, of course, does not work as intended and lacks good performance. This is because the algorithm has no choice but to check each instance, and every lab rat takes a unique reference in memory. There is quite a bit of churn here since every entry is considered unique.

To remedy this issue, it will need a way to do equality checks on complex types. Remember that without knowing the equality between lab rats, the algorithm is left with no choice but to do reference checks which is undesirable. Every complex type has a default comparer, and what is shown here is the bare behavior without explicitly defining equality.

Naïve distinct

One way to establish equality is via the EqualityComparer<T> interface. This requires two methods: Equals and GetHashCode. Figuring out equality is trivial but computing a hash code is optional.

public class LabRatANaiveComparer : EqualityComparer<LabRatA>
{
  public override bool Equals(LabRatA? x, LabRatA? y) =>
    x?.Name == y?.Name &&
    x?.TrackingId == y?.TrackingId &&
    x?.Color == y?.Color;

  public override int GetHashCode(LabRatA obj) => 1;
}

This implementation decided to skip computing the hash code by forcing a constant. This is a nice shortcut, and without knowing what this hash exactly does, it feels like the right choice.

To test what this does:

WriteLine("Naive Distinct");
stopWatch.Restart();
WriteLine(ratsA.Distinct(
    new LabRatANaiveComparer())
  .Count()); // 300
stopWatch.Stop();
WriteLine($"{stopWatch.ElapsedMilliseconds} ms"); // 4397 ms
WriteLine();

This returns the correct number of distinct lab rats, but the performance is a dismal 4.4 seconds. Ten times slower than the simple incorrect implementation, which puts this code in a precarious situation. Of course, the opposite might be true, but, oftentimes, correctness is preferable to better performance. Ideally, you want the code to give you both correctness and good performance.

Proper distinct

There is a way to compute a hash for multiple properties based on a tuple to put in a good hash code calculation. Say there is a name, tracking id, and color for a lab rat. A tuple with these three properties has a somewhat unique hash code.

public class LabRatAProperComparer : EqualityComparer<LabRatA>
{
  public override bool Equals(LabRatA? x, LabRatA? y) =>
    x?.Name == y?.Name &&
    x?.TrackingId == y?.TrackingId &&
    x?.Color == y?.Color;

  public override int GetHashCode(LabRatA obj) =>
    (obj.Name,
    obj.TrackingId,
    obj.Color) // tuple
    .GetHashCode();
}

The Equals method remains intact, and this uses the hash from the tuple instead of a dumb constant. With a properly computed hash code, check to see what this does:

WriteLine("Proper Distinct");
stopWatch.Restart();
WriteLine(ratsA.Distinct(
    new LabRatAProperComparer())
  .Count()); // 300
stopWatch.Stop();
WriteLine($"{stopWatch.ElapsedMilliseconds} ms"); // 252 ms
WriteLine();

This time the performance is even better than the bare distinct, about twice as fast, and this returns a correct result. The reasons for the performance gains are twofold: this no longer churns through millions of records, and there is something very interesting happening with this hash code.

Why is this happening?

To find out what is happening, I will need to F12 into the Distinct method and decompile the code. This is possible in LinqPad, and any IDE available today. The focus is .NET 6, so keep in mind that implementation details are likely to change in future releases.

This is what you might see, it is not the entire code but only a small chunk of it:

public class DistinctIterator
{
  private readonly LabRatA?[] _entries; // hash set
  private readonly IEqualityComparer<LabRatA> _comparer;
  public DistinctIterator()
  {
    _entries = new LabRatA[300]; // max 300 rats
    _comparer = new LabRatAProperComparer();
  }
  public IEnumerable<LabRatA> Distinct(List<LabRatA> rats) =>
    rats.Where(AddIfNotPresent); // loops
  private bool AddIfNotPresent(LabRatA rat)
  {
    var hashCode = _comparer.GetHashCode(rat);
    var bucket = GetBucketRef(hashCode);
    var i = (int)bucket;
    while (i >= 0)
    {
      var entry = _entries[i];
      if (entry != null &&
        _comparer.GetHashCode(entry) == hashCode &&
        _comparer.Equals(entry, rat))
      {
        return false;
      }
      i = -1; // churn
    }
    if (_entries[bucket] != null) return false; // collision
    _entries[bucket] = rat;
    return true;
  }
  private uint GetBucketRef(int hashCode) =>
    (uint)hashCode % (uint)_entries.Length;
}

These are the findings:

  • The DistinctIterator loops through the entire list at least once
  • The algorithm builds an internal hash set to nuke duplicate entries
  • The hash code optimizes the nested while loop via buckets
  • When the hash code causes collisions, the algorithm churns inside the nested loop

Please note that this code is far from complete and only focuses on the hash code. The nested while loop does not actually churn but escapes the loop, which means it can’t find all distinct values. This is mostly for the sake of brevity to avoid smacking you with a wall of code.

What is most interesting is this explains the poor performance seen in the naïve comparator. When the hash code collides for all entries, the algorithm must work harder. This spikes the complexity to a quadratic, or Big-O O(n^2) complexity. If the hash theoretically causes no collisions, expect linear or O(n) complexity.

In performance-sensitive code, it may make sense to do away with the built-in hash code entirely and switch to one that causes even fewer collisions, like murmur hash, for example.

Even though this implementation is far from complete, it is still possible to run the code:

WriteLine("Simple DistinctIterator");
stopWatch.Restart();
WriteLine(new DistinctIterator()
  .Distinct(ratsA)
  .Count()); // 194
stopWatch.Stop();
WriteLine($"{stopWatch.ElapsedMilliseconds} ms"); // 284 ms
WriteLine();

The Count does not find all distinct lab rats and this count changes per execution. This is because the built-in hash code changes per run, which means that the hash isn’t deterministic but dynamic.

Although the implementation of Distinct might be updated in the future, it is unlikely that this external hash code contract will change because it is a critical part of determining equality and optimizing internal algorithms in .NET.

A bit of asynchrony

Say there are two lists that need to be turned into a unique set and they are coming from asynchronous data sources. Unfortunately, the framework has nothing built-in to deal with this but this extension method can come in handy.

Public static async Task<Ienumerable<TR>> SelectManyAsync<T, TR>(
  this Ienumerable<T> enumeration,
  Func<T, Task<List<TR>>> func) =>
  (await Task.WhenAll(enumeration.Select(func))
      .ConfigureAwait(false))
    .SelectMany(s => s);

Be sure to put this inside the existing EnumerableExtensions static class.

This grabs a parameter list and feeds it to the lambda function. Then, runs everything in parallel and returns a combined list with all the duplicate records.

To get a unique set from the combined async list:

WriteLine("Async Distinct");
stopWatch.Restart();
WriteLine((await new []{"A", "B"} // parameter list
    .SelectManyAsync(GetLabRats))
  .Distinct(new LabRatAProperComparer())
  .Count()); // 300
stopWatch.Stop();
WriteLine($"{stopWatch.ElapsedMilliseconds} ms"); // 516 ms
WriteLine();

Task<List<LabRatA>> GetLabRats(string type) => type switch
{
  "A" => Task.FromResult(ratsA),
  "B" => Task.FromResult(ratsA),
  _ => throw new ArgumentException("Invalid rat type")
};

This technique remains performant because the elapsed time only grows linearly based on the number of records, which is now six million so double the records. This has linear complexity because the parameter list remains constant. If the parameters become a boundless list, each with millions of records, then the code will spike to a quadratic complexity.

Distinct with C# records

If you are already on .NET Core, C# +8 introduces records to the mix; these provide built-in functionality for encapsulating data. One of its core features is value equality. For record types, two records are equal is they have the same type and store the same values.

To play with records, fire up another lab rat:

public record LabRatB(string Name, int TrackingId, Color Color);

This has the same properties as before but expressed in less code. Because equality is built-in, it is possible to figure out distinct lab rats without implementing a comparer.

var ratsB = 3000000.Times(x => new LabRatB
(
  "LabRat_" + x % uniqueEntries,
  x % uniqueEntries,
  (Color)(x % uniqueEntries)
)).ToList();

WriteLine("Record Distinct");
stopWatch.Start();
WriteLine(ratsB.Distinct().Count()); // 300
stopWatch.Stop();
WriteLine($"{stopWatch.ElapsedMilliseconds} ms"); // 948 ms
WriteLine();

Notice the performance gets dinged a bit. This is because the built-in implementation does not use the tuple technique, which causes more collisions.

This code is equivalent to the following but using a class instead of a record:

public class LabRatC : IEquatable<LabRatC>
{
  protected virtual Type EqualityContract => typeof(LabRatC);

  public string Name { get; init; } = string.Empty;
  public int TrackingId { get; init; }
  public Color Color { get; init; }

  public override int GetHashCode() =>
    HashCode.Combine(
      EqualityComparer<Type>.Default
        .GetHashCode(EqualityContract),
      Name.GetHashCode(),
      TrackingId.GetHashCode(),
      Color.GetHashCode());

  public bool Equals(LabRatC? other) =>
    Name == other?.Name &&
    TrackingId == other.TrackingId &&
    Color == other.Color;
}

The biggest difference here is using the hash combine helper, which is what a C# record uses internally, and this can be overridden. Notice it is also possible to avoid defining a comparer by simply inheriting IEquatable in the target class. Records implement this equatable interface too to provide equality functionality.

Now to verify this code works:

var ratsC = 3000000.Times(x => new LabRatC
{
  Name = "LabRat_" + x % uniqueEntries,
  TrackingId = x % uniqueEntries,
  Color = (Color)(x % uniqueEntries)
}).ToList();

WriteLine("IEquatable Distinct");
stopWatch.Start();
WriteLine(ratsC.Distinct().Count()); // 300
stopWatch.Stop();
WriteLine($"{stopWatch.ElapsedMilliseconds} ms"); // 1092 ms
WriteLine();

The elapsed time is different here is because the built-in hash code calculation is dynamic. This is one tidbit to keep in mind, hash codes are more of a moving target so don’t expect consistency between different types.

Conclusion

Figuring out uniqueness in managed code can be useful in taking the load off the database. The hash code dictates the efficiency of the distinct algorithm, so the best approach is to avoid too many collisions.

If you like this article, you might also like Functional monads in C#

The post Creating unique datasets with managed code appeared first on Simple Talk.



from Simple Talk https://ift.tt/6q3cFtg
via