Monday, February 14, 2022

A Practical Guide to Dapper

The Data Access Layer (DAL) is often the most critical part of any application. Dapper is a micro-ORM built with simplicity, top-notch performance, and ease of use in mind. In this take, I will walk you through what Dapper has to offer and why it has become the tool of choice for many high-demand solutions.

Dapper is a lightweight shim around ADO.NET for data access via extension methods. To keep this relevant to any real application, there is quite a bit of code, which I won’t be able to show, so I recommend downloading the repo from GitHub. The focus here is to walk through the code API and follow best practices for building a DAL. The set of extension methods can feel overwhelming because there is a lot of functionality to cover.

I recommend general familiarity with LINQ and the List<> generic class in C#. This guide can be used as a reference so you can read one section at a time. At each pause, I encourage you to play with the code and allow the information to sink in.

I opted to use only async methods because these are the ones anyone should be using in a production environment. C# and .NET make this relatively painless via async/await, albeit with caveats.

You will need the .NET 6 SDK and a copy of SQL Server preloaded with the AdventureWorks database to run the code sample. The connection string in the repo points to the MSLocalDB instance, which you can get from SQL Server Express. It is also possible to point this to another SQL Server instance via the DataSource property. Fortunately, Visual Studio is not required unless you prefer to use this tool.

ExecuteAsync

Whenever you see the ExecuteAsync method, it is safe to assume this performs a mutation to the backend database. The method returns an int with the number of rows affected by the query. In SQL, this typically means INSERT, UPDATE, or DELETE statements.

public async Task<int> UpdateSalesOrder(int salesOrderId, byte status)
{
  const string sql = @"
    UPDATE Sales.SalesOrderHeader
    SET STATUS = @status
    WHERE SalesOrderID = @salesOrderId";

  var param = new {status, salesOrderId};
  using var conn = _db.GetAdventureWorksConnection();

  return await conn.ExecuteAsync(sql, param)
    .ConfigureAwait(false);
}

It is best to nuke any synchronization with the main thread at the data access layer because this can affect scalability. Therefore, it is a good idea to set configure await to false, so this does not wait on the main thread. Unfortunately, C# does not do this automatically for the developer, so it must come from muscle memory. A good rule of thumb is if you are working in the DAL, put ConfigureAwait(false) in every call stack method. If context information is necessary at this level, one technique is sending this data via a method parameter to avoid synchronization.

Failing to await the call in the repository bombs because the connection falls out of scope and gets closed before the task gets awaited. A best practice is to go ahead and do async/await but do it as efficiently as possible. If there are passthrough layers up in the call stack, it is acceptable to return a Task.

Note param is a throwaway POCO that does not need to be strongly typed. The one gotcha here is the property must match the SQL variable in the query without worrying about case sensitivity. T-SQL isn’t case sensitive and will bind correctly even if there isn’t an exact case match.

QueryAsync

This method gets a list of query results that can be enumerated. Specifying the return type via a generic parameter, i.e., <SalesOrder>, binds the results in managed code. Note if the query result is empty, this method will send back an empty list with a count of zero.

As a side note, binding to a C# record instead of class requires at least a parameterless default constructor otherwise, Dapper throws an exception.

public async Task<List<SalesOrder>> GetSalesOrders()
{
  const string sql = @"
    SELECT CustomerID, SalesOrderID,
    ROW_NUMBER() OVER(ORDER BY CustomerID) AS RowNumber
    FROM Sales.SalesOrderHeader";

  using var conn = _db.GetAdventureWorksConnection();

  return (await conn.QueryAsync<SalesOrder>(sql)
      .ConfigureAwait(false))
    .AsList();
}

The result from the query is a weakly typed enumerable with lazy load, and I recommend materializing the list in-memory with AsList. Without this technique, the code runs the risk of remunerating through the result set multiple times, which is inefficient. Unless the plan is to travel through the results one at a time without repeats, the safest option is to stash this in the heap and let the garbage collector do the rest. This technique works like a ToList in LINQ but does not duplicate the underlying list into another block of memory.

QueryFirstAsync

To pluck the first item in the result set, use the QueryFirstAsync method. Be sure to specify an ORDER BY in the SQL query to make the return object more predictable.

A word of caution here, sorting rows in SQL puts the workload on the SQL Server engine, which may not be ideal. An alternative is to query for the entire list and sort in managed code, which can scale horizontally.

public async Task<SalesOrder> GetFirstSalesOrder()
{
  const string sql = @"
    SELECT CustomerID, SalesOrderID,
    ROW_NUMBER() OVER(ORDER BY CustomerID) AS RowNumber
    FROM Sales.SalesOrderHeader
    ORDER BY SalesOrderID";

  using var conn = _db.GetAdventureWorksConnection();

  return await conn.QueryFirstAsync<SalesOrder>(sql)
    .ConfigureAwait(false);
}

This method only picks the first item on the list and returns the object. If the query comes back empty, you do not get back a null but a thrown exception. The good news is this at least guarantees a result from the query.

QueryFirstOrDefaultAsync

If getting a nullable object is preferred, this works like LINQ’s FirstOrDefault. The return type Task<SalesOrder?> declares this as nullable. This feature is available in C# +8 and specifies which type may return null. In .NET 6, new projects get this feature enabled by default via the Nullable flag in the project file. What’s nice is the compiler knows as much information as the method API call because queries do not throw when the return object is nothing. This nullable feature makes the compiler fire warnings when the code is at risk of null exceptions.

public async Task<SalesOrder?> GetFirstSalesOrderOrDefault(
  int customerId)
{
  const string sql = @"
    SELECT CustomerID, SalesOrderID,
    ROW_NUMBER() OVER(ORDER BY CustomerID) AS RowNumber
    FROM Sales.SalesOrderHeader
    WHERE CustomerID = @customerId
    ORDER BY SalesOrderID";

  var param = new {customerId};
  using var conn = _db.GetAdventureWorksConnection();

  return await conn.QueryFirstOrDefaultAsync<SalesOrder>(sql, param)
    .ConfigureAwait(false);
}

This method API blends seamlessly with the compiler because it knows the code can throw exceptions without proper null checks. I recommend automating this in the compiler so you get feedback on when it’s time to code defensively.

QuerySingleAsync

To grab a single item from the database, use this method.

public async Task<SalesOrder> GetSingleSalesOrder(int salesOrderId)
{
  const string sql = @"
    SELECT CustomerID, SalesOrderID,
    ROW_NUMBER() OVER(ORDER BY CustomerID) AS RowNumber
    FROM Sales.SalesOrderHeader
    WHERE SalesOrderID = @salesOrderId
    ORDER BY SalesOrderID";

  var param = new {salesOrderId};
  using var conn = _db.GetAdventureWorksConnection();

  return await conn.QuerySingleAsync<SalesOrder>(sql, param)
    .ConfigureAwait(false);
}

Note the query must return exactly a single row. If not, Dapper unwinds the call stack via a thrown exception. This guarantees one object in the return type, so the compiler can assume this is not nullable.

Typically, with these types of queries, expect to see a unique id in the table so it can return one row. If this assumption turns out to be false, then look out for exceptions in the logs. At the very least, this method reinforces data integrity in managed code because of the single object limitation.

QuerySingleOrDefaultAsync

Anytime you see OrDefault in the API method name, it is safe to assume the return type is nullable. A best practice is to let the compiler know this fact via a question mark in the return type. This keeps the feedback loop between compilations full of good information.

public async Task<SalesOrder?> GetSingleSalesOrderOrDefault(
  int salesOrderId)
{
  const string sql = @"
    SELECT CustomerID, SalesOrderID,
    ROW_NUMBER() OVER(ORDER BY CustomerID) AS RowNumber
    FROM Sales.SalesOrderHeader
    WHERE SalesOrderID = @salesOrderId
    ORDER BY SalesOrderID";

  var param = new {salesOrderId};
  using var conn = _db.GetAdventureWorksConnection();

  return await conn.QuerySingleOrDefaultAsync<SalesOrder>(sql, param)
    .ConfigureAwait(false);
}

In this method, the query has the option to return nothing without risking a thrown exception in Dapper. This method API returns exactly one object or the default value which is typically null.

QueryMultipleAsync

This method runs multiple queries simultaneously and binds the result via a grid reader. The reader can be strongly typed in C#, which returns a list of enumerable objects. This works like QueryAsync, except it runs multiple queries.

public async Task<List<SalesOrder>> GetSalesOrders(int customerId)
{
  const string sql = @"
    SELECT CustomerID, SalesOrderID as [SalesEyeDeed],
    ROW_NUMBER() OVER(ORDER BY CustomerID) AS RowNumber
    FROM Sales.SalesOrderHeader

    SELECT CustomerID, SalesOrderID,
    ROW_NUMBER() OVER(ORDER BY CustomerID) AS RowNumber
    FROM Sales.SalesOrderHeader
    ORDER BY SalesOrderID

    SELECT CustomerID, SalesOrderID,
    ROW_NUMBER() OVER(ORDER BY CustomerID) AS RowNumber
    FROM Sales.SalesOrderHeader
    WHERE CustomerID = @customerId
    ORDER BY SalesOrderID";

  var param = new {customerId};
  using var conn = _db.GetAdventureWorksConnection();
  using var query = await conn.QueryMultipleAsync(sql, param)
    .ConfigureAwait(false);

  var result = new List<SalesOrder>();

  result.AddRange((await query.ReadAsync<SalesOrder>()
      .ConfigureAwait(false))
    .AsList());

  result.AddRange((await query.ReadAsync<SalesOrder>()
      .ConfigureAwait(false))
    .AsList());

  result.AddRange((await query.ReadAsync<SalesOrder>()
      .ConfigureAwait(false))
    .AsList());

  return result;
}

Can you spot the typo? Go back and look for [SalesEyeDeed], unfortunately with these big blobs of SQL text, it is easy to mess these up. I recommend going over the SQL query thrice and making sure it matches the property name in the type without case-sensitivity. In this case, SalesOrderId is an int, so when Dapper can’t bind to anything, it defaults the value type to zero. Dapper does not throw an exception and defaults the property type, which can be undesirable in a production environment because this fails silently.

One alternative is to use a stored procedure, so it’s easier to spot mistakes in SQL. This provides some feedback, and you are not hunting for errors in a wall of text.

Stored Procedure

A stored procedure can be called via the CommandType parameter from System.Data.

public async Task<List<EmployeeManager>> GetEmployeeManagers(
  int businessEntityId)
{
  const string sql = "dbo.uspGetEmployeeManagers";

  var param = new {businessEntityId};
  using var conn = _db.GetAdventureWorksConnection();

  return (await conn.QueryAsync<EmployeeManager>(
        sql,
        param,
        commandType: CommandType.StoredProcedure)
      .ConfigureAwait(false))
    .AsList();
}

Be sure to specify just the stored procedure name in the SQL text because it does not need parameters or the exec statement. Dapper takes care of building the correct query before it gets sent. A common snag is to try to bind parameters manually like in other method APIs which fails.

Transaction

Explicit transactions from the SQL client can be initialized via the BeginTransaction method.

public async Task<int> UpdateSalesOrderTransaction(
  List<int> salesOrderIds,
  byte status)
{
  const string sql = @"
    UPDATE Sales.SalesOrderHeader
    SET Status = @status
    WHERE SalesOrderID = @salesOrderId";

  var result = 0;

  using var conn = _db.GetAdventureWorksConnection();
  conn.Open();
  using var trans = conn.BeginTransaction();

  foreach (var salesOrderId in salesOrderIds)
  {
    var param = new {status, salesOrderId};

    result += await conn.ExecuteAsync(sql, param, trans)
      .ConfigureAwait(false);
  }

  trans.Commit();

  return result;
}

One common gotcha is to forget to Open the connection because all other API methods do this implicitly. Be sure to set the transaction parameter in each individual query. The ExecuteAsync method has an optional transaction parameter, and the default is null. Without explicit transactions, each statement gets executed as a separate transaction. With a transaction, everything gets rolled back automatically if you forget to call the Commit method.

Table Value Parameter

One alternative to sending a bunch of statements with an explicit transaction is to send a TVP instead.

public async Task<int> UpdateSalesOrdersTvp(
  List<SalesOrderType> salesOrders)
{
  const string sql = @"
    UPDATE soh SET
      soh.Status = tvp.Status
    FROM Sales.SalesOrderHeader soh
    INNER JOIN @tvp tvp ON soh.SalesOrderId = tvp.SalesOrderId";

  var param = new
  {
    tvp = salesOrders
      .ToDataTable()
      .AsTableValuedParameter("SalesOrderType")
  };

  using var conn = _db.GetAdventureWorksConnection();

  return await conn.ExecuteAsync(sql, param)
    .ConfigureAwait(false);
}

TVPs are ideal when you have thousands of rows or less. For millions of rows, use Bulk Copy instead for better performance.

If joins against the TVP are necessary, it is possible to add a clustered index on the column of interest, for example, SalesOrderId. If columns in the TVP type are known to be not null, it is best to let the SQL engine know this fact. To boost performance, TVPs can be declared as memory-optimized so that they live in memory instead of tempdb.

Dapper provides the extension method AsTableValuedParameter, which expects a DataTable and the name of the TVP. The ToDataTable method is a custom extension method found in the GitHub repo, so I recommend peeking on your own time since it’s somewhat involved.

In general, the ToDataTable algorithm does the following:

  • New up a DataTable instance
  • Loop through property names in the POCO and add them as columns in the data table
  • Loop through the values and add them as rows in the data table

Unfortunately, Dapper expects the consuming code to do all this work but this ToDataTable extension method comes in handy when working with TVPs.

Unit Test

Finally, an argument can be made not to include any unit tests in the DAL. The reasoning is this does not actually test the SQL query, which is a valid argument.

If I may rebut, unit tests aren’t integration or functional tests but simple sanity checks to get even faster feedback on the code. What if I forget to pass in the SQL text or param to the extension method in Dapper? What happens when I set a transaction but didn’t mean to? These unit tests work like a safety net when any reasonable developer inevitably makes a dumb mistake.

No business logic belongs in the DAL, but there are exceptions to this rule. I often find conditionals, switches, loops, and somewhat complex logic in the data repository, which deserve test coverage.

The code sample uses Xunit and Moq to unit test the repository. Executing dotnet test in the test project automatically installs these dependencies and runs all unit tests. Your particular test project may not use Xunit, but I find Moq is used consistently throughout most C# test projects.

[Fact]
public async Task GetSalesOrdersMultiple()
{
  // arrange
  _reader
    .Setup(m => m.ReadAsync<SalesOrder>(true))
    .ReturnsAsync(new List<SalesOrder>());

  _db
    .Setup(m => m.QueryMultipleAsync(
      It.Is<string>(s => s != null),
      It.Is<object>(o => o != null),
      null,
      null,
      null))
    .ReturnsAsync(_reader.Object);

  // act
  var result = await _repo.GetSalesOrders(1);

  // assert
  Assert.NotNull(result);
}

You may be wondering, how is this even possible when Dapper is a bunch of untestable extension methods? To make this testable, this DAL puts extension methods in a wrapper class with an interface that can be mocked.

public async Task<IGridReader> QueryMultipleAsync(
  string sql,
  object? param = null,
  ISqlTransaction? transaction = null,
  int? commandTimeout = null,
  CommandType? commandType = null) =>
    new GridReaderWrapper(await _dbConnection.QueryMultipleAsync(
    sql,
    param,
    transaction?.GetTransaction(),
    commandTimeout,
    commandType).ConfigureAwait(false));

This works much like a lightweight proxy layer that delegates work to the extension method in Dapper. I encourage you to poke around in the code sample to get a better feel for this technique.

Architecture

This data access layer follows Clean Architecture via Inversion of Dependency and composition. Interfaces define what capability is available in Dapper without any guesswork. As a nice bonus, the ISqlConnection interface includes API code comments which pop up in IntelliSense. Most of the code you have seen so far goes in the repository class.

Figure 1. Data Access Layer with Clean Architecture

Note the interface lives in the Domain project, which is the consuming code. By inverting the dependency in this way, the business logic gets to decide what it needs without worrying about implementation details. The Data project then takes on this dependency to fulfil the interface contract.

Conclusion

Dapper gives you a ton of functionality out of the box via ADO.NET extension methods. With a bit of work, it is possible to build a data access layer that is testable, maintainable, and performant.

 

The post A Practical Guide to Dapper appeared first on Simple Talk.



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

Thursday, February 10, 2022

Mighty Tester – Here we go round the Mulberry bush

Commentary Competition

Enjoyed the topic? Have a relevant anecdote? Disagree with the author? Leave your two cents on this post in the comments below, and our favourite response will win a $50 Amazon gift card. The competition closes two weeks from the date of publication, and the winner will be announced in the next Simple Talk newsletter.

The post Mighty Tester – Here we go round the Mulberry bush appeared first on Simple Talk.



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

Wednesday, February 9, 2022

How to back up and restore in PostgreSQL: Learning PostgreSQL with Grant

The series so far:

  1. Connecting to PostgreSQL: Learning PostgreSQL with Grant
  2. Creating a Database and Tables in PostgreSQL: Learning PostgreSQL with Grant
  3. How to back up and restore with PostgreSQL: Learning PostgreSQL with Grant

One of the first things I worry about when I’m looking at a new system is the status of the backups. I don’t see anything in PostgreSQL that will lead me to a different conclusion. However, I didn’t realize just how big a can of worms I would open by pursuing backups and restores.

Instead of talking immediately about backups, let’s talk about restores.

Restore strategy

There’s a saying that, as far as I know, originated with Kimberly Tripp: Your backups are only as good as your last restore. In short, you have to take backups, but what’s important is the ability to restore the data. You can have an infinite number of backups, but if you can’t restore even one of them, that’s nothing but wasted space. So, before you start thinking about backups, you should be thinking about how you want to restore your systems.

Restoring a database is an enormous topic. This article could get into all sorts of permutations about all the different methods for restoring a database. However, to keep the size of this article to something reasonable, and because I haven’t learned everything I need to just yet, I’m going to focus on one restore mechanism: restore from a backup. It’s also possible to restore to a point-in-time, but I’m saving the details of how to do that for a future article.

A simple restore from a backup is meant to get the database back to the state it was in right at the point that a backup was taken. This kind of restore operation is acceptable for development and test systems. It’s an easy way to quickly migrate a database to a new server. However, it is limited in that you can only restore to the point of the backup. If data or structural changes occurred after the backup that you’d like to recover, you just can’t do it.

This is where the point in time restore comes into play. Generally, most organizations frown on data loss. For example, taking a backup once a day means that, if a problem occurs about 12 hours into the day, you’re going to lose all that data. A point-in-time recovery means you can get the last backup and all the changes to the database since that backup. Point-in-time recoveries are accomplished through the write ahead log (WAL) maintained by PostgreSQL.

The WAL is automatically created and maintained by your servers. You can configure the size and number of files in the WAL. In theory, an infinite number of WAL files can be played back to arrive at a point in time. However, that brings up another aspect of a restore strategy, recovery time.

A recovery strategy must be built to define how you would like to restore and how long you want it to take. Development systems usually require taking a quick database backup and you’re done. Production systems need point-in-time restores, so you probably want a database backup that requires managing the WAL files.

With the requirements defined, you can then walk over and pick up the right backup tool.

Database back up

If simple database restores are all you’re interested in, then the best tool for the job is pg_dump. The core syntax is simple:

pg_dump databasename > backupfile

However, because I’m running my databases, either in containers or out in the cloud, this simple syntax won’t work because the service is running under a different login than what I’m using to connect remotely. Instead, I can modify the command slightly:

pg_dump -U postgres postgrelearning > butest1

This command will work because I’m supplying the user that runs the service.

When running MySQL in Docker, you must open a shell command to the container like this where PostgreHome is the name of the container:

docker container exec -it PostgreHome /bin/bash

Then running the original syntax just works, and the backup file will be found in the directory from where you are running the command unless you supply a path.

When running the command supplying the user from the external command line pointing it to the container, it’s going to demand a password. Once supplied, though, again, it just works.

You can exercise more control by setting various options in pg_dump, and I’ll discuss several of these a little later. However, one option to immediately consider, especially when thinking about how you intend to restore the database, is to change the output. By default, pg_dump goes to a plain SQL file. Pg_dump can also go into a compressed, digital file format by adding -Fc which is the custom format:

Pg_dump -U postgres -Fc postgrelearning > bucustom.dmp

Using either of these two methods, you can back up your database. Now let’s talk about running a restore.

Database recovery

The output from the default pg_dump command is interesting. However, it gets very long, very quickly. I have a very simple database created from other scripts in this series so far. Here’s a small part of the output from pg_dump with the default format that you can see by using CAT:

--
-- PostgreSQL database dump
--
-- Dumped from database version 14.1 (Debian 14.1-1.pgdg110+1)
-- Dumped by pg_dump version 14.1
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;
--
-- Name: hsr; Type: SCHEMA; Schema: -; Owner: postgres
--
CREATE SCHEMA hsr;
ALTER SCHEMA hsr OWNER TO postgres;
SET default_tablespace = '';
SET default_table_access_method = heap;
--
-- Name: radiobrand; Type: TABLE; Schema: hsr; Owner: postgres
--
CREATE TABLE hsr.radiobrand (
    radiobrandid integer NOT NULL,
    radiobranddesc character varying(50) NOT NULL
);

It keeps going from there. In short, pg_dump is scripting out the database, structures, and data, into a file. It’s an SQL file that you can then run from psql or any other tool. You’ll get the objects and data created using the SQL from the pg_dump process. Since it does include data, this file could be extremely large, depending on the database.

Recovery then is just a question of replaying the scripts, in other words, just executing the SQL. You could open it in the GUI of your choice, or you could take advantage of the command line utility like this:

Psql -U postgres postgrelearning < butest1

Of course, you would have to ensure that you have an empty database, otherwise, this will attempt to rebuild and reinsert data that’s already there. You can drop the existing database, create a new one and then run the scripts, or you can drop all the objects from the database, and then run the scripts.

If you choose to get the custom file format, you won’t have a simple set of SQL scripts, so replaying them requires a new command, pg_restore.

The base command to use pg_restore is just as simple as pg_dump:

pg_restore -d postgrelearning -U postgres bucustom.dmp

The same rules apply. The database must be either a new database or one you’ve cleaned unless you want to take advantage of the additional functionality I talked about when using the custom file format. For example, you could restore to a database that still has all its objects inside. You can choose to drop the existing objects first by modifying the command as follows:

pg_restore -d postgrelearning -U postgres -c bucustom.dmp

The command -c, or --clean, will drop objects first, however, you could run into error messages if you add a new object after the backup was taken. You can also tell pg_restore to create the database first:

pg_restore -d postgres -U postgres -C bucustom.dmp

The -C, or --create, command will try to create a postgrelearning database. If one exists, you’ll get an error, so, you can again modify the pg_restore command:

pg_restore -d postgres -U postgres -C -c bucustom.dmp

Running both --clean and --create will result in pg_restore dropping and recreating your database. Note that you will initially connect to a different database with the -d option and that the restore will use the database name from the dump file.

While running the SQL scripts of a basic pg_dump command is simple, you don’t have much control. You will find there are quite a few options if you use the custom file format and pg_restore. Using pg_restore you can:

  • Restore just the data and not the schema
  • Restore only the schema and no data
  • Output the contents of the dump file as a list of objects
  • Define a specific list of objects to restore
  • Disable triggers
  • Use multiple concurrent jobs to make the restore run faster
  • Pick and choose individual objects to restore

There are a number of other behaviors you can control in pg_restore that don’t apply to a getting started article. However, to summarize, you get a lot more control over exactly what gets restored using pg_restore and the custom dump format instead of the standard SQL.

pg_dump options

I already introduced one option available to pg_dump, the custom file format. Several additional options enable you to control what, and how, things get backed up.

The options are defined in the command line as has been previously shown. You can use abbreviations like -a, which means only dump the data for a given database, or you can use the full option, --data_only. Some options are complete, and some require you to supply additional information.

For example, you can specify that the dump is ready to clean the database as part of the restore:

Pg_dump -c postgrelearning > pgl.sql

Now when you run the scripts, it will include DROP commands.

You can use include or exclude patterns to only move some of the objects in a database. For example, to exclude schemas that start with the string dev in them, you could run this:

Pg_dump -N dev* postgrelearning > nodev.sql

You also have commands to make it possible to:

  • Backup just the schema without data
  • Backup only the data, without a schema definition included
  • Define multiple concurrent jobs, so the backup occurs faster
  • Add in conditional commands, IF EXISTS, to clean up

And a whole lot more.

How to back up all the databases

It’s fairly likely that you have more than one database. You can script out pg_dump so that you run it over and over, specifying which database to backup and where it should go. If you have a very customized backup process where each database is unique, this is probably the way to go. However, you also have the option to use pg_dumpall. Instead of one database at a time, this will export all the databases on a given server to a single file. The pg_dumpall command is basically just a wrapper around pg_dump. However, since all databases are being dumped, pg_dumpall will also gather dependent objects for the databases that may be in a system table.

The problem with pg_dumpall is that it only outputs to the standard SQL format. You can’t get the compressed custom format. This also means you don’t get all the functionality of pg_restore. As before, this means that you can only restore to empty databases.

Other back up mechanisms

Like almost any major RDBMS, there are third-party solutions out there for PostgreSQL. Also, if you’re running AWS RDS, AWS Aurora, Azure Database for PostgreSQL, or GCP SQL Database for PostgreSQL, they all come with built-in backup and recovery mechanisms. You can also backup and restore from PGAdmin4 and restore from Azure Data Studio. Plus, there are multiple scripted solutions available through the PostgreSQL community. I would strongly recommend learning how to use the native tools to backup and restore your databases. However, once you’ve built the skill set, then moving to a different solution would be fine.

Conclusion

The ability to restore a PostgreSQL database is critical. Getting a quick backup is quite easy with the pg_dump command, and it’s most suited for development. This command creates a script file by default that you can play. There are several other options, including -Fc to create a backup with a custom format that can be used with the pg_restore command. The pg_dump command provides several options, including the ability to drop and create the database. If you need to back up all the databases, use the pg_dumpall command, however, it’s not as flexible.

Production databases usually need to be able to recover to a point-in-time, encrypt the backup, and there are often other requirements, so other options like WAL or a third-party tool must be used. I’ve purposely saved the point-in-time restore discussion for another article because it is quite complex compared to pg_dump.

The post How to back up and restore in PostgreSQL: Learning PostgreSQL with Grant appeared first on Simple Talk.



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

Tuesday, February 8, 2022

Eight Azure SQL configurations you may have missed

Azure SQL Database is Microsoft’s Platform as a service (PaaS) offering for SQL Server. It eliminates hardware, virtual machine, and operating system management and has automatic tuning, high availability, auto-scale capabilities, high-performance options, and much more. It’s easy to create an Azure SQL Server Database, but you may not know about best practices and some of the newer features. This article covers some of the essential configurations of Azure SQL you should be aware of. It explains some of the configurations or leaves you with links explaining the details of the more complex configurations.

These are the items covered in this article:

Once upon a time

Many of the items in this article are about Azure SQL Security. Years ago, before the cloud providers existed, organizations published sites from their own on-premises environments. Usually, an application server would be deployed in a virtual network called DMZ, protected by a firewall. This virtual network would be isolated from the rest of the company network by a second firewall, creating a level of isolation and making only the DMZ accessible from the internet.

The SQL Server would be located inside the company network, outside the DMZ. The application server on the DMZ would be the only server which would have access to the SQL Server, creating a secure connection from the internet to the company data.

Back when the technology was way more complex and difficult, we had all this security, so why would we think that provisioning an Azure SQL Database with a public endpoint in a cloud provider to be a good practice? Shouldn’t we change the defaults to make the security tighter like it was in the past?

Serverless is more than auto-pause

The Serverless option in Azure SQL is well-known for the ability to pause the service when it’s not being used.

An image showing the auto-pause delay of Azure SQL Database serverless.

However, this ability has many drawbacks:

  • There is no way to trigger the pause. As a result, the pause will only happen after the server stays without any request for the entire time of the auto-pause delay. The auto-pause delay has the minimum value of 1 hour
  • Several Azure features, such as Azure SQL Defender, will make calls to the serverless instance and prevent the serverless from getting into pause.
  • Several features such as long-term backup retention and elastic jobs are not compatible with auto-pause.
  • The serverless feature can be implemented only on the vCore mode. At the time of this writing, the cheapest DTU mode you can provision is € 5,00/Month. The most affordable vCore mode you can implement is €200/Month, besides the serverless, of course. The vCore cost of a serverless implementation is also a bit more expensive than other provisioning modes.

All these details will make the auto-pause benefits limited, however, there is one additional configuration: The serverless provisioning is a flexible vCore model, and you can establishing a minimum and maximum vCore amount for the server. In fact, this configuration is enabled by default when you choose the Serverless provisioning.

An image showing the Max and Min vCores configuration of serverless

By doing so, the Azure SQL will have a flexible charge based on the number of vCores actually used between the minimum and maximum established. You can even leave the auto-pause turned on if you want to do so. Auto-scaling is a benefit not available to any other provisioning model.

The image below shows an example of this. The subscription is always charged for minimum number of vCores (assuming that auto-pause is disabled) or the number of vCores used, saving money when the maximum number of vCores is not being used.

An image showing the CPU active, inactive and paused time periods of serverless.

(Image from Serverless compute tier – Azure SQL Database | Microsoft Docs)

Being able to scale up and scale down according to workload makes Serverless an attractive option when choosing your provisioning model. If you choose vCores, then you should consider Serverless with a minimum and maximum configuration.

You should not enable access to Azure Services on the Firewall

It’s easy and tempting to turn on the Allow Azure services and resources to access this server setting. You only need to enable it, and you will no longer have firewall problems with any Azure Service.

An image showing the "allow Azure services and resources to access this server" setting.

The problem is what most people ignore: The firewall will not be opened only to the services from your company. The firewall will be opened to any Azure services; it doesn’t matter to whom it belongs.

One security layer will be completely removed from the Azure SQL when this option is enabled. Of course, you still have the authentication, but is this enough?

You should not open firewall rules on the portal for database users

The firewall configuration is a common need in Azure SQL configuration. However, many administrators ignore the fact there are two levels of firewall configuration: You can configure the firewall on the server level, or you can configure the firewall on the database level.

An image showing database and server firewall rules.

(Image from IP firewall rules – Azure SQL Database and Azure Synapse Analytics | Microsoft Docs)

This happens because the UI in the portal can only configure the firewall at the server level. The firewall configuration on the database level needs to be done using T-SQL.

An image showing the Security menu options including Firewalls and virtual networks.

An image showing the firewall rules for a server

A basic security rule is always to set the minimum permissions needed by a user. If you open the firewall on the server level, you are not following this rule. A more secure way to open the firewall for database users is to open the firewall only for the database, not on the server level.

The statements below may be useful.

Creating a database firewall rule

EXECUTE sp_set_database_firewall_rule N'Example DB Rule','0.0.0.4','0.0.0.4';

Listing database firewall rules

select * from sys.database_firewall_rules

An image showing the results the query to find firewall rules

Delete a database firewall rule

EXECUTE sp_delete_database_firewall_rule N'Example DB Rule';

Once you adopt the practice of opening database firewall rules, the user connection needs to specify the database when connecting. Connections on the server level will not be accepted.

Using SSMS, this configuration is not typical and can be found on the advanced connection settings.

An image showing SSMS connecting to a server and specifying the database name.

Application connection strings always contain the database name, so this is not a big difference.

References

The secondary server is accessible on Business and Premium tiers

The Read Scale-Out of the Business or Premium tiers is a recent feature, but it’s quite interesting. It’s straightforward to set when provisioning the database.

An image showing the Read Scale-out setting

Microsoft uses the Always On feature in these tiers to ensure high availability. The image below illustrates how the failover is automatically implemented.

An image showing the Always On AG notes with Failover from Primary to Secondary

Enabling Read Scale-Out to the secondary servers makes it possible to create a balance for your applications. Applications that need to write data to the database will connect to the primary server, while applications only reading data will connect to the secondary server.

This connection is defined by the connection string of the application. The application only needs to specify the parameter ApplicationIntent on the connection string. ApplicationIntent can be defined as ReadOnly or ReadWrite. This single parameter will define if the connection will be made with the primary or the secondary server.

You can test this feature using SSMS: Using the Advanced Options you can set the ApplicationIntent parameter to one of these values, make the connection to the server and identify the server you are connected to.

An image showing the ApplicationIntent = Readonly option in the Connection dialog

The following query will allow you to identify if you are connected to the primary or secondary server:

SELECT DATABASEPROPERTYEX(DB_NAME(), 'Updateability');

References

Your azure applications should not route packages through the public network

Your Azure SQL is inside Azure (is there a more obvious statement than this one?).

If the applications which will access your Azure SQL are also inside Azure, the communication between both should happen entirely inside Azure. This means the network packages exchanged between the application and the Azure SQL should flow entirely inside the Microsoft Network, never through public network.

Once again, it appears obvious, but this is not the default behaviour. If you only “establish the connection” in the simplest way, the connection will be done through the public internet.

The best way to identify if the connection is done through Microsoft Network or through public internet is the firewall: If the connection is blocked by the firewall or you need to open the firewall for the source IP’s, then the connection is crossing the public internet. When the connection is configured to be go through the Microsoft Network, the IP configurations of the firewall will be bypassed.

For example, if a virtual machine on Azure shows the screen of the image below when connecting to Azure SQL, this means the communication between both will happen using public Ips.

An image showing the New Firewall Rule dialog

The steps to ensure the communication through the Microsoft Network are:

  • You need a virtual network
  • You need to ensure your application is being executed inside this virtual network
  • Create a service endpoint between your Azure SQL and your virtual network

An image showing the Service endpoints

  • On the Azure SQL Server, include permission for the virtual network to access the server

References

Additional Details

Your application is in a Virtual Machine: Virtual Machines already include a virtual network when they are provisioned, you only need to ensure the creation of the service link to your Azure SQL

PaaS: Each PaaS service in Azure has a different way to be included inside a virtual network. You need to verify the correct procedures for the PaaS you are using. However, this is a feature that may not be included on the lowest cost service levels available. That’s when you will need to decide to pay a bit more for the security or only ensure a good configuration of the firewall.

An image showing the configuration for the Outbound Traffic

An image showing the options for configuring networking for your app

You can dismiss the Firewall all together

If you manage to configure all your applications to access Azure SQL from the Microsoft Network, either because the application is in the network or using network communication such as VPN connections, you can completely Deny public network access on Azure SQL.

AN image showing the Firewalls and virtual network for you server. Deny Public network access is highlighted.

Once this change is complete, Azure SQL can only access the database from inside your company’s virtual network on Azure or through VPN.

The following configuration details are critical to this scenario:

  • Service Endpoint doesn’t work because it’s intended to establish a route to a feature with public access enabled
  • You need to create a Private Link on your virtual network
  • Private Links are based on DNS zones. When a private link is created, a DNS Zone is created as well (except on custom scenarios).
  • Peered virtual networks need to be configured to use the same DNS Zone for DNS resolution
  • Gateway clients (such as VPN clients), need to be configured to redirect DNS resolutions to Azure DNS. This can be done in many ways.

This configuration is similar to the one found on-premises: The database server will be completely private.

References

You should avoid SQL Standard security

Although the SQL Standard authentication evolved a lot over the years, it’s still a simple login/password authentication. Recently the Azure SQL team included features to allow limiting the authentication to Azure AD Authentication, preventing the use of SQL Standard Security.

An image showing where to require Azure AD authentication only

Besides the configuration itself, you can use policies to control the use of SQL Standard authentication and identify which servers have this configuration disabled, identifying which servers are not compliant with the company rules on an enterprise level.

Here are some blogs I wrote about this subject:

RCSI configuration is ON by default

SQL Server has many isolation levels to control the integrity of the data.

However, in read-heavy applications, many developers have the terrible habit of using NOLOCK on all statements to avoid the contention of creating lock records on the server. The developers ignore the risk of incorrect results.

Over the years, Microsoft created a solution for SQL Server: Two new isolation levels, RCSI (Read Committed Snapshot Isolation) and Snapshot Isolation; both also called optimistic isolation levels.

RCSI is considered a special isolation level. It’s different from the other isolation levels because RCSI is configured as a database property. There is no need to change the code. Every transaction that arrives on the server using Read Committed isolation (the default) is converted to Snapshot Isolation. I’m using quotes here because it’s not exactly Snapshot Isolation. RCSI has some differences from Snapshot Isolation, and that’s why they are considered two different isolation levels.

The point is: Azure SQL uses RCSI by default. This is a big change for all existing applications. Any use of NOLOCK that you have in existing applications becomes useless and a problem for the application because it brings the usual issues of NOLOCK with no benefit, since the use of RCSI replaces all the possible benefits of NOLOCK.

You can check this default on Azure SQL running the following query:

select database_id,name,is_read_committed_snapshot_on
from sys.databases

An image showing the results of checking is_read_committed_snapshot_on

Migrating applications to Azure SQL and using RCSI are great opportunities to eliminate all NOLOCKs still found in your SQL code.

References

Summary

It’s very easy to start developing applications using Azure SQL. After the initial development, as this article illustrated, Azure SQL has some secrets to help you improve performance and security.

Developers may need the assistance of Solution Architects for the most complex steps, such as virtual networks, DNS, VPN, and Private Endpoint configuration. This highlights how the cloud requires all roles working together, as it was in the past, with on-premises environments.

The post Eight Azure SQL configurations you may have missed appeared first on Simple Talk.



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

Friday, February 4, 2022

Sentiment Analysis with Python

The series so far:

  1. Text Mining and Sentiment Analysis: Introduction
  2. Text Mining and Sentiment Analysis: Power BI Visualizations
  3. Text Mining and Sentiment Analysis: Analysis with R
  4. Text Mining and Sentiment Analysis: Oracle Text
  5. Text Mining and Sentiment Analysis: Data Visualization in Tableau
  6. Sentiment Analysis with Python

Previous articles in this series have focused on platforms like Azure Cognitive Services and Oracle Text features to perform the core tasks of Natural Language Processing (NLP) and Sentiment Analysis. These easy-to-use platforms allow users to quickly analyze their text data with easy-to-use pre-built models. Potential drawbacks of this approach include lack of flexibility to customize models, data locality & security concerns, subscription fees, and service availability of the cloud platform. Programming languages like Python and R are convenient when you need to build your models for Natural Language Processing and keep your code as well as data contained within your data centers. This article explains how to do sentiment analysis using Python.

Python is a versatile and modern general-purpose programming language that is powerful, fast, and easy to learn. Python runs on interpreters, making it compatible with multiple platforms, and is widely used in applications for web platforms, graphical interfaces, data science, and machine learning. Python is increasingly gaining popularity in data analysis and is one of the most widely used languages for data science. You can learn more about Python from the official Python Software Foundation website.

Initial setup

This article makes use of Anaconda open-source Individual Edition distribution for demos. It is one of the easiest ways for individual practitioners to work on data science and machine learning with Python. It comes with an easy-to-use interface, and the toolkit enables you to work with thousands of open-source packages and libraries. This section walks through the steps of setting up Anaconda and launching a jupyter notebook.

  • Follow this link to the Anaconda website and download the Anaconda Individual Edition that works with your operating system. This demo is built on a Windows 10 machine.

An image showing where to download Anaconda Individual Edition for Windows

Figure 1. Download Anaconda Individual Edition

  • After the download completes, launch the installer and follow prompts to run through the guided installation steps

An images showing the welcome screen of the Anaconda set up wizard

Figure 2. Anaconda Setup guide for installation

  • On the Advanced Options screen of this Setup guide, check the box for Add Anaconda3 to my PATH environment variable. While the setup guide doesn’t recommend it for Windows, you may find it useful sometimes to run Anaconda commands from the command line.

The Advanced Installation Options screen. Check Add Anaconda3 to my PATH environment variable

Figure 3. Anaconda setup advanced options

  • The installation process takes a few minutes to run. Upon successful completion, you should see the following screen.

An images showing the Complete screen of the Anaconda installation wizard

Figure 4. Installation complete

  • If Anaconda Navigator doesn’t start automatically at this point, then Go to Windows start menu > Anaconda3 > Anaconda Navigator

An image showing the Anaconda Navigaor

Figure 5. Launch jupyter from Anaconda Navigator

The Anaconda Navigator window presents you with several practical applications. Applications like Spyder and PyCharm are development environments for Python, VS Code is an extensible general-purpose code editor. Jupyter Notebook is an open-source web-based interactive computing notebook environment that allows users to create and share human-readable documents with live code, visualizations, and comments. JupyterLab is Jupyter’s next-generation notebook interface that is flexible and supports a wide range of workflows in data science, machine learning, and scientific computing. This article uses Jupyter Notebook for demos.

  • From the Anaconda Navigator window, launch Jupyter Notebook, which opens the root folder in your machine’s default browser
  • On the top right side of this screen, click New > Notebook: Python 3

An image showing the Jupyter home page

Figure 6. Create a new Python notebook

  • The new notebook (file name untitled.ipynb) will open in the same web browser

An image showing a new Jupyter notebook with one empty cell

Figure 7. New notebook

  • Use this link to download the demo data file from my Github Repository and save it at a convenient location on your machine (this demo data file was used in previous articles of this series)
  • If you are new to Jupyter notebooks, I recommend taking a few minutes to familiarize yourself with the interface. Readers may also follow the Beginner’s tutorial to Jupyter Notebook linked in the References section.

Import modules for sentiment analysis

This section introduces readers to Python modules used for sentiment analysis

  • The sys module is always available and provides access to variables and functions that interact with the interpreter.
  • The re module provides operations for regular expression matching, useful for pattern and string search.
  • pandas is one of the most widely used open-source tools for data manipulation and analysis. Developed in 2008, pandas provides an incredibly fast and efficient object with integrated indexing, called DataFrame. It comes with tools for reading and writing data from and to files and SQL databases. It can manipulate, reshape, filter, aggregate, merge, join and pivot large datasets and is highly optimized for performance.
  • matplotlib is an easy-to-use, popular and comprehensive library in Python for creating visualizations. It supports basic plots (like line, bar, scatter, etc.), plots of arrays & fields, statistical plots (like histogram, boxplot, violin, etc.), and plots with unstructured coordinates.
  • The Natural Language Toolkit, commonly known as NLTK, is a comprehensive open-source platform for building applications to process human language data. It comes with powerful text processing libraries for typical Natural Language Processing (NLP) tasks like cleaning, parsing, stemming, tagging, tokenization, classification, semantic reasoning, etc. NLTK has user-friendly interfaces to several popular corpora and lexical resources Word2Vec, WordNet, VADER Sentiment Lexicon, etc.
  • This article uses the VADER lexicon with NLTK’s SentimentIntensityAnalyzer class to assign a sentiment score to each comment in the demo dataset. Valence Aware Dictionary and Sentiment Reasoner (VADER) is a lexicon and rule-based sentiment analysis toolset with a focus on sentiments contained in general text applications like online comments, social media posts, and survey responses. Please follow this link to learn more VADER and SentimentIntensityAnalyzer modules of NLTK.

The Code snippet below will load the necessary modules and download the ‘vader_lexicon’ for sentiment analysis. This code also creates a short alias pd for referencing pandas and plt for referencing matplotlib modules later in the code. Copy this code snippet into the first cell of your new jupyter notebook and run it.

import re
import pandas as pd
import matplotlib.pyplot as plt
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
nltk.download('vader_lexicon')

An image showing the import statements and return message saying the package vader_lexicon is up to date

Figure 8. Import relevant modules and download VADER lexicon

Import demo data file and pre-process text

This step uses the read_excel method from pandas to load the demo input datafile into a panda dataframe.

Add a new field row_id to this dataframe by incrementing the in-built index field. This row_id field serves as the unique key for this dataset to uniquely identify a row and will be used later in the code for merging two dataframes.

The code snippet below performs these two tasks and prints the top ten rows of the resulting dataframe. Copy this code snippet into the next cell of your jupyter notebook and run that cell.

#df = pd.read_excel (r'Path where the Excel file is stored\File name.xlsx')
df = pd.read_excel (r'C:\Users\mhatres\Documents\RedGateDemos\SentimentAnalysis\TeamHealthRawDataForDemo.xlsx')
# adding an row_id field to the dataframe, which will be useful for joining later
df["row_id"] = df.index + 1
#print first 10 rows 
print (df.head(10))

An image showing the data import and print statements. The results of the import statement.

Figure 9. import file into pandas dataframe

The next step will subset row_id and Response fields into a new dataframe, which is the input format required for by the SentimentIntensityAnalyzer class. This step also cleans up the text data by removing all non-alphabet characters and converting all text to lower case.

The code snippet below performs these two tasks and prints the top ten rows of the resulting dataframe. Copy this code snippet into the next cell of your jupyter notebook and run that cell.

#create a new data frame with "id" and "comment" fields
df_subset = df[['row_id', 'Response']].copy()
#data clean-up
#remove all non-aphabet characters
df_subset['Response'] = df_subset['Response'].str.replace("[^a-zA-Z#]", " ")
#covert to lower-case
df_subset['Response'] = df_subset['Response'].str.casefold()
print (df_subset.head(10))

An image showing the code to clean up the data

Figure 10. pre-process and format text

Generate sentiment polarity scores

The SentimentIntensityAnalyzer class uses the Valence Aware Dictionary and sEntiment Reasoner (VADER) in NLTK. The sentiment lexicon in VADER is a list of lexical features like words and phrases labeled as positive or negative according to their semantic orientation. Its rule-based approach is especially good at detecting sentiments in common applications like social media posts, product or service reviews, and survey responses.

VADER also generates a numeric score in the range of negative one (-1) to positive one (+1) to indicate the intensity of how negative or positive the sentiment is. This is called the polarity score and is implemented by the polarity_score method of the SentimentIntensityAnalyzer class.

  • Polarity score in the range of -1 to -0.5 typically indicates negative sentiment
  • Polarity score greater than -0.5 and less than +0.5 typically indicates neutral sentiment
  • Polarity score in the range of +0.5 to 1 typically indicates positive sentiment

Run the following code snippet in next cell of your jupyter notebook to create a dataframe for staging the output of the SentimentIntensityAnalyzer.polarity_scores method.

# set up empty dataframe for staging output
df1=pd.DataFrame()
df1['row_id']=['99999999999']
df1['sentiment_type']='NA999NA'
df1['sentiment_score']=0

The next few steps involve instantiating an object of the class SentimentIntensityAnalyzer and running a for-loop to iterate the polarity_scores method over each row of input text dataframe df_subset. Another for loop is embedded with the earlier loop to write the sentiment polarity score for each sentiment type to an intermediate dataframe. The three sentiment type values are.

  • neg for negative sentiment
  • neu for neutral sentiment
  • pos for positive sentiment
  • compound for an overall score that combines negative, positive, and neutral sentiments into a single score.

At the end of the for loop, clean the output dataframe by:

  • Deleting the dummy row from the output dataframe
  • Removing any duplicate rows that could potentially creep into the output dataframe
  • Filtering the output dataframe to only keep rows for sentiment type of compound

The code snippet below performs these tasks and prints the top ten rows of the resulting dataframe. Copy this code snippet into the next cell of your jupyter notebook and run that cell. Depending on the size of your input dataset and machine resources, this step may need a few minutes to complete.

print('Processing sentiment analysis...')
sid = SentimentIntensityAnalyzer()
t_df = df1
for index, row in df_subset.iterrows():
    scores = sid.polarity_scores(row[1])
    for key, value in scores.items():
        temp = [key,value,row[0]]
        df1['row_id']=row[0]
        df1['sentiment_type']=key
        df1['sentiment_score']=value
        t_df=t_df.append(df1)
#remove dummy row with row_id = 99999999999
t_df_cleaned = t_df[t_df.row_id != '99999999999']
#remove duplicates if any exist
t_df_cleaned = t_df_cleaned.drop_duplicates()
# only keep rows where sentiment_type = compound
t_df_cleaned = t_df[t_df.sentiment_type == 'compound']
print(t_df_cleaned.head(10))

 

An image showing additional cleanup

Figure 11. generate sentiment polarity scores and clean the output dataframe

Merge this output dataframe t_df_cleaned with the input dataframe df using the field row_id. This dataframe merge operation in Python is conceptually similar to performing a join on two database tables in SQL. The merged dataframe will have the following fields and one row per survey response.

  • Period
  • Manager
  • Team
  • Response
  • Row_id
  • Sentiment_type
  • Sentiment_score

The code snippet below performs this merge operation and prints the top ten rows of the resulting dataframe. Copy this code snippet into the next cell of your jupyter notebook and run that cell.

#merge dataframes
df_output = pd.merge(df, t_df_cleaned, on='row_id', how='inner')
print(df_output.head(10))

An image showing the merge dataframes

Figure 12. Merge dataframes

Follow this link to learn more about the merge operation in pandas.

Visualize sentiment analysis output

This section will demonstrate how to analyze, visualize, and interpret the sentiment scores generated by the previous steps.

Use the describe method in pandas to generate summary statics of values in the Sentiment_score field. These summary statistics reveal the numerical insights of this dataset using aggregate metrics like count, min, max, median, etc.

The code snippet below generates summary statistics of sentiment_score field of df_output dataframe.

df_output[["sentiment_score"]].describe()

An image showing the summary statistics

Figure 13. Summary statistics

A quick review of these summary statistics reveals the following insights.

  • The min value is -0.895700, which indicates the polarity or intensity of the most negative response is strongly negative (range of sentiment polarity score is -1 to +1)
  • The max value is +0.988300, which indicates the polarity or intensity of the most positive response is highly positive (range of sentiment polarity score is -1 to +1)
  • The mean value is +0.594633 which indicates the average polarity or intensity of sentiment across all responses is in the positive territory.

The next step uses matplotlib to create various charts to analyze the sentiment scores by the available attributes of Period, Team, and Manager.

The responses in this dataset span across four quarters. Identifying how the mean of sentiment score trends over this time period would reveal deeper insights. The following code snippet demonstrates how to plot the mean sentiment score for each quarter (Period on x-axis and mean sentiment score for each period on y-axis). Copy this code snippet into the next cell of your jupyter notebook and run that cell.

#generate mean of sentiment_score by period
dfg = df_output.groupby(['Period'])['sentiment_score'].mean()
#create a bar plot
dfg.plot(kind='bar', title='Sentiment Score', ylabel='Mean Sentiment Score',
         xlabel='Period', figsize=(6, 5))

An image showing the code for a chart, period X mean sentiment score.

Figure 14. plot mean of sentiment score by period

This bar plot shows the mean sentiment score across all teams

  • remained relatively unchanged from 2018-Q3 to 2018-Q4
  • improved marginally from 2018-Q4 to 2019-Q1
  • decreased in 2019-Q2

This decrease in the last quarter could indicate some employees felt less positive about their team’s health in that quarter. While a decrease in one quarter is certainly not alarming, it could be a Key Performance Indicator (KPI) for managers to watch in future quarters, in case the downward trend continues and needs further investigation.

This dataset includes responses from nine teams. Studying the mean of sentiment scores for each team might reveal interesting insights about how these teams compare against each other. The following code snippet plots the mean sentiment score for each team (Team on x-axis and mean of sentiment score for each team on y-axis). Copy this code snippet into the next cell your jupyter notebook and run that cell.

dfg = df_output.groupby(['Team'])['sentiment_score'].mean()
dfg.plot(kind='bar', title='sentiment_score', ylabel='Mean Sentiment Score',
         xlabel='Team', figsize=(6, 5))

 

An image showing a chart with Team X mean sentiment score

Figure 15. plot mean of sentiment score by Team

This bar plot reveals.

  • Team 9 has the highest mean sentiment score, indicating this team seems most healthy over all four quarters, across all nine teams
  • Management might want to understand what makes members of Team 9 feel highly positive about their team’s health. These insights might be applicable to other teams to help improve their scores
  • Team 5 has the lowest mean sentiment score, indicating this team seems least healthy over all four quarters, across all nine teams
  • This insight might encourage the manager of Team 5 to investigate the reasons behind their team’s lower scores and potentially take steps to improve their team’s health.

While the previous two bar charts help uncover interesting insights using the mean sentiment score, averages can sometimes hide nuances in the data. For example, figure 15 shows Team 5 has an average sentiment score of 0.5, which can be interpreted as “neutral”. Is it in the “neutral” range because all team members feel neutral about their team’s health, and there is consensus within this team? Or is it neutral because about half of the team feel strongly positive about their team’s health, and the other half feel strongly negative and the approach of using averages is masking this polarization within the team?

A boxplot, also known as a box and whiskers plot is a great way to learn such insights by studying the center and spread of numerical data. A box plot is a method of graphically depicting groups of numerical data through their quartiles. Box plots may also have lines extending from the boxes (whiskers), indicating variability outside the upper and lower quartiles, hence the terms box-and-whisker plot. It is commonly used in descriptive statistics and is an efficient way of visually displaying data distribution through their quartiles. They take up less space and are very useful when comparing data distribution between groups.

This section uses seaborn to create the boxplot. Seaborn is a popular statistical data visualization library in Python. It’s based on matplotlib and provides easy to use high-level interfaces for creating engaging and information statistical charts. Seaborn is pre-installed in the Anaconda environment used in this demo and available to simply import into the jupyter notebook.

The following code snippet imports the seaborn library and creates the boxplot with these parameters.

  • Data set to build the boxplot is specified using parameter data=df_output
  • Column for x-axis is specified using parameter x=’Team’
  • Column for x-axis is specified using parameter y=’sentiment_score’
  • notch = True parameter creates a visual indicator (notch) to quicky identify median values
  • Outliers are hidden using the parameter showfliers=False
  • Title of the chart is set using set(title='Sentiment Score by Team')
  • Labels for X and Y axis are set using plt.xlable() and plt.ylable() methods
  • plt.xticks(rotation=90) orients the Team names vertically along x-axis

 

Copy this code snippet into the next cell of your jupyter notebook and run that cell.

import seaborn as sns
#create seaborn boxplots by group
sns.boxplot(x='Team', y='sentiment_score', notch = True,
            data=df_output, showfliers=False).set(title='Sentiment Score by Team')
#modify axis labels
plt.xlabel('Team')
plt.ylabel('Sentiment Score')
plt.xticks(rotation=90)

 

An image showing the boxplot chart

Figure 16. Boxplot

This boxplot reveals interesting insights about how members within each team feel about their team’s health.

  • The box for Team 5 is the tallest box, which indicates a wider spread in the sentiment scores of responses from this team. This spread is a sign of polarization within the team, which means some team members feel strongly positive about their team’s health while others feel strongly negative. The manager of Team 5 might be able to use this deep-dive insight, along with their knowledge of each team member’s workload and professional context, to identify and possibly address any concerns impacting their team’s health.
  • The box for Team 9 is shortest, indicating a narrow spread of sentiment scores, which means most members of Team 9 feel the same way about their team’s health. The notch indicates a median value of sentiment scores for this team is around 0.8, which is strongly positive.

Conclusion

This article

  • Demonstrated Anaconda setup and how to run python scripts with Jupyter notebooks
  • Gave an overview of libraries used for the sentiment analysis
  • Walked through data loading and clean-up steps
  • Described a methodical approach to generate and use sentiment polarity scores
  • Created visualizations in python and used them to gain valuable insights

References

 

The post Sentiment Analysis with Python appeared first on Simple Talk.



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

Tuesday, February 1, 2022

Getting started with MySQL

MySQL is a popular relational database management system developed and distributed by the Oracle Corporation. It provides a multi-user, multithreaded platform that can support a wide range of mission-critical workloads. As with other relational database management systems, such as SQL Server and PostgreSQL, MySQL is based on the Structured Query Language (SQL), a standardized programming language used to create database objects such as tables and views as well as build queries for accessing data through those objects. This article explains geting started with MySQL.

First released in 1995, MySQL has its roots in the open-source community and continues to operate as an open-source project, despite now being owned by Oracle, which took over MySQL as part of its acquisition of Sun Microsystems in 2010. At the heart of the MySQL platform is MySQL Server, which provides the core database capabilities. You can access and download the source code for MySQL Server through GitHub.

However, you don’t need the source code to get started with MySQL. Oracle offers the MySQL Community edition as a free download available under the GNU General Public License (GPL). Oracle also offers commercial editions that include additional features, but they require licensing and are not free to use. Fortunately, the Community edition is all you need to learn about MySQL.

In this article, I demonstrate how to set up the MySQL Community edition on a Windows computer and how to use MySQL Workbench to access the MySQL environment. I also show how to create a database, add a table to the database, insert data into the table, and then query that data. The examples I provide are fairly straightforward and should be easy to try out for yourself, even if you’re relatively new to relational databases. That said, you should still have a basic understanding of how relational databases work and how they use SQL before you dive into MySQL.

Installing MySQL on Windows

You can install MySQL on many operating systems, including Windows, macOS, Oracle Solaris, and Linux distributions such as Ubuntu, Debian, Fedora, SUSE Linux Enterprise Server, and Red Hat Enterprise Linux.

MySQL comes in several editions: Community, Standard, Enterprise, and Cluster Carrier Grade Edition. Because the Community edition is free and available under the GPL license, it’s a great choice for learning about MySQL and creating test databases. For this article, I installed the MySQL Community edition on Windows 10 Pro, but you might choose to install it on one of the other supported platforms.

The approach you take to installing MySQL will depend on the operating system and your preferences. The easiest way to install MySQL on Windows is to use MySQL Installer, a downloadable tool that walks you through the steps of installing and setting up a MySQL instance. I also installed MySQL on macOS to test it out. For this, I used Homebrew and the Bash command shell, which made it relatively straightforward to set up MySQL Community Server and start running SQL commands.

To install the MySQL Community edition on Windows, take the following steps:

  1. Download MySQL Installer’s .msi file from the MySQL site. (At the time of this article, the most recent installer file was mysql-installer-community-8.0.27.1.msi.)
  2. Once downloaded, double-click the .msi file and follow the prompts to set up the installer.
  3. Launch the installer and follow the wizard’s prompts as it steps you through the process of installing and configuring MySQL Server and any other components you want to install.

When you run MySQL Installer, you’ll need to choose which products to install. For this article, I selected the most recent version of each of the following:

  • MySQL Server. The primary MySQL Community instance.
  • MySQL Workbench. A user interface for connecting to and working with a MySQL Server instance. Workbench is similar to using SQL Server Management Studio to access SQL Server.
  • MySQL Documentation. A set of local help files that can be accessed locally through MySQL Workbench.

You can install other components, but the three listed here are all you need to follow along with the examples in this article.

When installing MySQL Server, you’re also given the option to configure the server environment. When I configured the server on my instance, I used the following settings:

  • Type and Networking. I selected Development Computer from the Config Type drop-down list and left all other settings with their default values.
  • Authentication Method. I selected the Use Strong Password Encryption for Authentication option.
  • Accounts and Roles. I provided a password for the root account but defined no other accounts at this time. However, you can create additional accounts as needed and assign them the necessary roles, depending on the environment in which you work and your specific needs.
  • Windows Service. I selected the Configure MySQL Server as a Windows Service option and kept the default service name, MySQL80. I also stuck with the default settings for all other options.

When you’re finished installing and configuring MySQL, the installer will display the products you installed, as shown in Figure 1. You can then close the installer and start working with MySQL. However, you can relaunch the installer at any time to add, upgrade, or remove products, as well as modify product components and reconfigure MySQL Server.

An image showing the MySQL installer.

Figure 1. Using MySQL Installer to set up the server and tools

After completing your installation, you can launch MySQL Workbench, which provides a graphical tool for working with MySQL servers and databases. You can use Workbench for SQL development, data modeling and design, server administration, and data migration. If you’re running the MySQL Enterprise edition, you can also use Workbench to manage advanced features such as MySQL Enterprise Backup, MySQL Firewall, and MySQL Audit.

When you launch MySQL Workbench, it opens to the home page, displaying the Welcome tab. From this page, you can also access the Models tab and the Migration wizard, which we’ll cover later in this series.

The Welcome tab should include a link to the local MySQL Server instance that you just created. On my system, the MySQL Connections section includes a link to Local instance MySQL80, as shown in Figure 2.

An image showing the MySQL Workbench welcome page.

Figure 2. Launching MySQL Workbench

When you click the connection, Workbench opens a connection tab that displays information about the server instance. The tab also includes its own query tab, which you can use to issue SQL commands directly against the MySQL Server instance. Figure 3 shows the connection tab, which is labeled Local instance MySQL80, and the embedded query tab, which is labeled Query 1. Additional query tabs are numbered incrementally.

An image showing the MySQL workbench with the management tab open. There is also a query tab showing.

Figure 3. Connecting to a MySQL instance

The connection tab contains three smaller panels that surround the query tab:

  • The left panel provides access to management, instance, and performance information, as well as to schema, object, and session information.
  • The right panel displays context help when building SQL statements. Nothing is currently displayed because no SQL elements are selected on the query tab. The panel also provides a mechanism for working with code snippets.
  • The bottom panel displays the message output when running SQL statements.

You can open or close any of these panels by clicking the toggles near the top right corner of the connection tab.

There is much more to MySQL Workbench than I can cover here, and I recommend that you review the Workbench documentation to get a better sense of the tool’s capabilities and the many features it provides. In addition, MySQL Workbench, like MySQL Community Server, has a wide user base and is supported by an active community, so you can also find information on community forums.

Creating a MySQL database

Once you get MySQL Server and MySQL Workbench up and running, you’ll likely do much of your work on the query tab, where you can run SQL statements against the target MySQL instance. Because MySQL is based on the SQL standard, most of the statements you run will be similar to those used for other relational database systems.

For example, you can create a database by issuing a CREATE DATABASE statement that specifies the name of the new database, as shown in the following example:

CREATE DATABASE IF NOT EXISTS travel;

In this case, I’m creating a database named travel. I also included an IF NOT EXISTS clause to ensure that the statement runs only if the database does not already exist.

After you create an SQL statement, you can then execute it against the target instance. The query tab toolbar includes two execute buttons (lightning bolts) for running SQL statements:

  • The first execute button (the one on the left) runs the portion of the script that you’ve selected. If no script is selected, Workbench executes all script on the query tab.
  • The second execute button runs only the statement where the cursor is located. You have to be careful with this option because it will also execute the statement that directly precedes the cursor, even if the cursor is on an empty line.

Because the query tab includes only one statement, you can click either of the two buttons. Figure 4 shows the CREATE DATABASE statement after I ran it in Workbench. The bottom panel displays a message about the statement’s execution. The white-on-green checkmark to the left of the message indicates that the statement ran successfully. If the statement had instead generated an error, the bottom pane would display the error message, along with a white-on-red X.

An image showing a create database statement.

Figure 4. Creating a database in MySQL

You might have noticed that the right panel displayed information about the CREATE DATABASE statement as you started to write that statement. When your cursor is positioned over certain SQL keywords, such as CREATE DATABASE, Workbench automatically provides information about that language element, along with a link to additional information.

After you create the database, you can view it on the Schemas tab in the left panel. You might have to click the refresh button near the top of the panel to get the new database to display. Workbench automatically adds four nodes to the database listing: Tables, Views, Stored Procedures, and Functions. However, because you have not created any of these types of objects, no objects will be listed under these nodes.

It might seem odd that Workbench lists the travel database as a schema rather than a database. This is because MySQL, for all practical purposes, treats databases and schemas as one and the same, which is much different from other relational database systems. In fact, the MySQL documentation states that “CREATE SCHEMA is a synonym for CREATE DATABASE.”

Adding a table to a MySQL database

After you create a database, you can issue a USE statement to select the new database and then add a table to the database. For example, the following code switches to the travel database and then uses a CREATE TABLE statement to define the airplanes table:

USE travel;
CREATE TABLE IF NOT EXISTS airplanes (
  plane_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  manufacturer VARCHAR(50) NOT NULL,
  model VARCHAR(50) NOT NULL,
  engine_type VARCHAR(50) NOT NULL,
  engine_count TINYINT NOT NULL,
  wingspan DECIMAL(5,2) NOT NULL,
  plane_length DECIMAL(5,2) NOT NULL,
  max_weight MEDIUMINT UNSIGNED NOT NULL,
  icao_code CHAR(4) NOT NULL,
  create_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  last_update timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP 
    ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (plane_id) ) 
ENGINE=InnoDB AUTO_INCREMENT=101;

If you’re already familiar with SQL, much of this script will look familiar to you, although some of the elements might be new. For example, MySQL lets you specify whether an integer data type is signed or unsigned. If signed, a column’s values can include negative numbers. If unsigned, the values cannot include negative numbers. Integer data types are signed by default.

We’ll be discussing the CREATE TABLE statement in more depth later in the series.

An image showing the create table statement.

Figure 5. Adding a table to a MySQL database

The Schemas tab in the left panel now shows the airplanes table. Because the table is selected on that tab, the Object Info tab at the bottom of the left panel displays information about the table.

Inserting data into a MySQL table

After you create a table, you can use the INSERT statement to add data to that table. As you’ve seen with other database products, you need only specify the target columns and their values, as shown in the following example:

INSERT INTO airplanes 
  (manufacturer, model, engine_type, engine_count, 
    wingspan, plane_length, max_weight, icao_code)
VALUES 
  ('Airbus', 'A380-800', 'jet', '4', 261.65, 238.62, 1267658, 'A388');

The statement’s format should be familiar to anyone who’s worked with SQL, regardless of the database system. After the INSERT clause, the statement lists the target columns in parentheses. The statement then includes a VALUES clause, which lists the values to be inserted into the new row, also in parentheses.

Retrieving data is also much the same as other relational databases. For instance, the following SELECT statement returns all of the table’s data:

SELECT * FROM airplanes;

In this case, the SELECT clause uses the asterisk (*) wildcard to indicate that all columns should be returned. Of course, you would not want to do this within a production environment, but for

Figure 6 shows the INSERT and SELECT statements, along with the results returned by the SELECT statement. I closed the right and lower panels to reduce the clutter.

Graphical user interface, application Description automatically generated

Figure 6. Inserting data into a MySQL table

When you return all columns in a table, Workbench adds a row to the results that show a null value for each column. You can use this row to add data directly to the table, as long as the values conform to the configured data types. In addition, Workbench lets you edit the values in the returned results. We’ll be covering the result grid in more detail in a later article in this series.

As with other database systems, you can also use a single INSERT statement to add multiple rows, as shown in the following example:

INSERT INTO airplanes 
  (manufacturer, model, engine_type, engine_count, 
    wingspan, plane_length, max_weight, icao_code)
VALUES 
  ('Piper', 'J-3 Cub', 'piston', '1', 38.00, 22.42, 1220, 'J3'),
  ('Beechcraft', '1900C', 'turboprop', '2', 54.50, 57.83, 16600, 'B190');

To add multiple rows, you need only separate the value sets with a comma. You can then run the same SELECT statement to return all the rows and columns:

SELECT * FROM airplanes;

Figure 7 shows the INSERT and SELECT statements, along with the query results.

An image showing the insert and select statements. The insert is inserting multiple rows.

Figure 7. Inserting multiple rows into a MySQL table

As you can see, the table includes all three rows, along with a row of null values for adding more data. You can, of course, be more specific in your queries, as in the following SELECT statement, which limits the columns and rows:

SELECT model, engine_type, engine_count
FROM Airplanes
WHERE manufacturer = 'Airbus';

In this case, the SELECT clause specifies only three columns (model, engine_type, and engine_count) rather than all columns. In addition, the statement includes a WHERE clause that limits the results to rows with a manufacturer value of Airbus. Figure 8 shows the SELECT statement and its results, which include only one row with three columns.

An image showing a query window with the INSERT and SELECT statements. The results of a query with a comma delimited list and filter.

Figure 8. Retrieving data from a MySQL table

There should be no surprises here. The main thing to note is that the result grid no longer includes a row of nulls for inserting new data, which is to be expected because you’re viewing only a subset of the table’s columns.

Getting started with MySQL

Once you know how to install MySQL and use MySQL Workbench, you can experiment with various features, create different types of database objects, and start building SQL queries. MySQL is a versatile database system that can accommodate a wide range of workloads. The better you understand how it works, the greater your ability to take advantage of its capabilities. Even if you’re new to relational databases, MySQL Installer makes it easy to set up your environment, and Workbench makes it easy to interface with that environment and work with MySQL and its data. You can then build on this foundation to become more proficient at creating databases and querying the data so you can better support your data-driven applications.

 

The post Getting started with MySQL appeared first on Simple Talk.



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