Wednesday, February 1, 2023

Optimizing Queries in MySQL: Optimizing Reads

In this blog, we’re going to walk you through how to solve the issues posed by that concern. At the end of the article, we’ll also walk you through some DDL operations to load test data.

SELECT Queries in MySQL

In my introduction blog, I noted: Queries are processes composed of tasks – their performance depends directly on the performance of those tasks.

To address problems posed by SELECT queries, the first thing we need to understand is what happens when a SELECT queries are executed. Here’s what MySQL does in the background when we execute a SELECT query:

  1. Our SQL client sends the query to the server to be executed.
  2. A specific query execution plan is followed.
  3. The result is returned.

Understanding these steps is no less vital than diving deeper into the query execution plan, and the output provided by an EXPLAIN statement execution – a query execution plan will provide us information in regards to what time MySQL takes to go through each step necessary to complete a query. The EXPLAIN statement will provide us more details in how MySQL executes the query itself.

For the purposes of this blog, we’re going to use the following table with three columns (it’s not necessary to specify the storage engine – MySQL will create the table based on the InnoDB storage engine by default if it’s not specified. In this specific scenario, the indexing part is not necessary, but if it’s specified, MySQL will create an index named “email” (indexes can have any names) on a column named “email.”) Also note the sizes of the email and username columns – in this case, emails shouldn’t be longer than 35 characters in length, and usernames shouldn’t be longer than 20.

It’s also worth noting that for the columns with the type of an integer the length of the column is deprecated starting from MySQL 8. So you might as well want to consider leaving the columns with an integer type intact without specifying a length attribute:

CREATE TABLE demo_table (
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  email VARCHAR(35) NOT NULL,
  username VARCHAR(20) NOT NULL DEFAULT '',
  INDEX email(email)
) ENGINE = InnoDB;

To insert data into the table, use INSERT or LOAD DATA INFILE – INSERT is an excellent choice if you’re dealing with smaller data sets (less than 100 million rows), while LOAD DATA INFILE can be very useful to work with big data sets. For INSERT, the syntax looks like so:

--A few rows for demos. At the end of the article is 
--a method to load more rows.
INSERT INTO demo_table (email,username) 
VALUES ('demo@demo.com', 'Demo'), 
('demo2@demo.com', 'Demo'), 
('Another@Email.com'), 
('AnotherDemo');

For LOAD DATA INFILE, the syntax looks like this – the FIELDS TERMINATED BY. Part of the query can be used to specify the character that terminates fields from one another (one can also specify what columns to load the data into by specifying them at the end of the query if we wish):

LOAD DATA INFILE '/path/to/file.txt' 
  INTO TABLE demo_table [FIELDS TERMINATED BY '|'];

The Query Execution Plan

To dive deeper into the query execution plan, we can use the MySQL query profiler or dig into the richer performance schema by following the steps outlined in the MySQL documentation. For many, though, using the query schema is more difficult than going through the simpler query, so I will use the profiler:

  1. Select a database, then issue a SET profiling = 1 query to enable profiling.
  2. Run your query, then issue a SHOW PROFILES query to investigate all of the profiles of all queries.
  3. Select the ID of the query you just ran (identify the query from the list provided by the profiler), then execute a SHOW PROFILE FOR QUERY [id] query.

Note: Query profiling with SET profiling = 1 has been deprecated since MySQL 5.6.7 and people are advised to follow the performance schema instead – the documentation will walk you through all of the necessary steps, just note that getting started with it is a little more complex than using the optimizer.

D:\Redgate\Blogs\October 2022\Optimiziation Series\The Basics of Query Optimization\Images\Query Profiling - 1.png

Image 1 – Profiling a Query. Initializing

D:\Redgate\Blogs\October 2022\Optimiziation Series\The Basics of Query Optimization\Images\Query Profiling - 2.png

Image 2 – Profiling a Query. Results

The query execution plan is displayed above. Now we need to properly understand what’s it all about, We will start from the top and move toward the bottom (for newer versions of MySQL, the results will look a little different – there may be more items such as “Executing hook on transaction” and “waiting for handler commit”, but the core premise is the same):

  1. Starting – The process of initializing the query.
  2. Checking permissions – Refers to the process of MySQL checking whether the user has sufficient permissions to run the query. If permissions are not present or they are not sufficient, the process terminates here.
  3. Opening tables – The process of MySQL opening all tables for operations. Once the tables are opened or if the tables are already open, MySQL proceeds to step #4.
  4. Init – MySQL performs initialization processes – for example, the InnoDB log and the binary log are being flushed.
  5. System lock – Once MySQL reaches this phase, it’s waiting for a system lock on the table to be released if it’s in place. In this phase, the query is making use of a function called mysql_lock_tables() and is waiting for its completion – more information can be found in the documentation, in the “System lock” paragraph.
  6. Optimizing – Internal processes performed by MySQL to determine how to execute the query in the quickest way. Think of math equations – if you multiply 2 by 0, you can realize the answer is 0 in a couple of ways: by solving the equation, or by realizing that multiplying anything by 0 yields 0. That’s what MySQL does here.
  7. Statistics – Calculating statistics-related data to further develop the query execution plan.
  8. Preparing is pretty much self-explanatory: MySQL is preparing to run the query.
  9. Executing – Once the server reaches the execution phase, the query is being executed to start producing rows for output.
  10. Sending data – MySQL is doing internal work to execute the query and return the results of that query.
  11. End – The end of the query before the cleanup process.
  12. Query end – refers to the end of query processing.
  13. Closing tables – The tables that were opened and impacted by the query are being closed.
  14. Freeing items – Means that MySQL is freeing items from the thread used to execute a query.
  15. Cleaning up – Finally, this stage refers to the cleaning up of items in the memory and resetting certain necessary internal variables.

For those who use the profiler, the results will be a little different, but the result will be pretty much the same. To employ the profiler, employ the following:

  1. Tell MySQL to enable monitoring for the user that runs the query by running two queries – the first one will ensure that monitoring is off for everyone, and the second one will enable monitoring for your specific account (replace “root” with your account name):

UPDATE performance_schema.setup_actors SET ENABLED = 'NO', HISTORY = 'NO' WHERE HOST = '%' AND USER = '%';
INSERT INTO performance_schema.setup_actors (HOST,USER,ROLE,ENABLED,HISTORY) VALUES('localhost','root','%','YES','YES')
;

  1. Enable two things – logs for statements and statement stages by running these queries:

UPDATE performance_schema.setup_consumers SET ENABLED = 'YES' WHERE NAME LIKE '%events_statements_%';

UPDATE performance_schema.setup_consumers SET ENABLED = 'YES' WHERE NAME LIKE '%events_stages_%';

  1. Update the setup_instruments table with these queries (there are no matches for me because the values are already updated):
    UPDATE performance_schema.setup_instruments SET ENABLED = 'YES', TIMED = 'YES' WHERE NAME LIKE '%statement/%';
    UPDATE performance_schema.setup_instruments SET ENABLED = 'YES', TIMED = 'YES' WHERE NAME LIKE '%stage/%';

  1. Finally, you can execute your query:
    SELECT * FROM demo WHERE email = 'demo@demo.com';

  2. Now identify the query by querying the query history – run this query (replace YOUR QUERY HERE with your actual query):
    SELECT EVENT_ID, TRUNCATE(TIMER_WAIT/1000000000000,6) as Duration, SQL_TEXT FROM performance_schema.events_statements_history_long WHERE SQL_TEXT like '%YOUR QUERY HERE%';
  3. Then to see the query duration and stage information, query the query history table like so (replace Query_ID with the actual query ID):
    SELECT event_name AS Stage,
    TRUNCATE(TIMER_WAIT/1000000000000,6) AS Duration
    FROM performance_schema.events_stages_history_long
    WHERE NESTING_EVENT_ID = QUERY_ID;

As you can see, the results don’t differ very much, and once we are aware of what the tasks in the query execution plan mean in the context of MySQL, we can start optimizing them.

Optimizing Tasks – the EXPLAIN Query

To optimize the tasks that comprise a SELECT query and make the query faster as a result, we need to take a look at the output of an EXPLAIN query that explains what the query is making use of internally. Profiling will tell us how long each query phase takes while explaining queries will tell us how the query is actually executing. Issue a SELECT query like you normally would, just add EXPLAIN at the start. We will use an example query specified below:

EXPLAIN SELECT * 
FROM demo_table 
WHERE email = 'jfriesen@example.net';

The output of the EXPLAIN query will tell us a number of things:

  • The type column depicts how the row was accessed (for more information on the various methods of query access, refer to the docs. SIMPLE in this case refers to the fact it doesn’t use a UNION or subquery)
  • The table column will tell you what table the SELECT query is running on. For some, it may be self-explanatory, but if you run a lot of SELECT statements, such a feature is useful. The documentation has more information on its functionality.
  • The partitions column will tell you whether partitions are used, and if so, what their names are.
  • The possible_keys column describes the indexes MySQL could have chosen. The key column provides us with the chosen index, and the key_len column depicts the length of the index on that column. Do note that the key length is the index length – not the length of data (it will not be the same as defined in the data type.) In this case, the length of the index (the key length) is also calculated internally by MySQL, thus the value of “142.” More information on possible indexes can be found here, and indexes are covered here.
  • The ref column tells us what columns were working with the index in question to select data. In other words, MySQL is searching for columns that are working with the index as described in the docs.
  • The rows column depicts the number of rows in the table. Bear in mind that for InnoDB, this number is likely to be an estimate rather than the actual value because InnoDB doesn’t store the row count internally as MyISAM does – more information can be found in the documentation over here.
  • The filtered column shows an estimate of how many rows are going to be filtered out (i.e. not included in the result set.) The percentage given in this column is only an estimate, so don’t be surprised if you see “100.00” like in the example above. More information on this value can be found here.
  • There are also other possible values, like the select_type value: the select_type value outlines the type of SELECT that was used (if the SELECT used a UNION clause, etc.)

To better understand the results of profiling and the EXPLAIN query, keep in mind the following:

  1. A SELECT query will be blazing fast if it scans through as few rows as possible. Hence, we should avoid selecting all columns for a result set – only selecting necessary columns will be enough.
  2. The main thing that optimizes the performance of a SELECT query is indexes (also called keys.) Look closely at the output of the EXPLAIN query – the “possible_keys” column depicts the indexes that MySQL can use, and the “key” column depicts what index was actually chosen. Indexes make SELECT queries faster because when an index is used, MySQL doesn’t read through all data to find a column value (refer to point #1.)

    Indexes have multiple types (we will tell you what they are in a second), and indexes do really deserve a book in and of themselves, so for those who are interested in how they work on a deeper level, we suggest you read about everything surrounding them in the documentation of MySQL or read Relational Database Index Design and the Optimizers by Tapio Lahdenmaki and Mike Leach.

  3. SELECT query performance can be significantly improved by using partitions too. Partitions essentially split tables into multiple different tables internally. Since those tables are still treated as one table by the storage engine layer, it’s usually used to store only data that begins with, say, only a specific character or number. A query then uses the data in the partition and makes the SELECT query faster because we adhere to the point #1.

Indexes and partitions are two things that are used the most frequently when optimizing SELECT queries – each of them has multiple types unique to themselves.

Both indexes and partitions help optimize SELECT query performance because indexes let MySQL find rows with specific column values in a quick fashion, and partitions act as tables within tables – MySQL can turn to them when a search query begins with a specific character to only read through the table of rows beginning with that character. As a result, SELECT statements are faster in both cases.

Types of Indexes

Indexes can be split into a couple of types – we can have B-Tree, R-Tree (spatial), and hash indexes. All indexes except spatial indexes and hash indexes are B-Tree indexes whereas spatial indexes are R-Tree indexes. There are also hash indexes, which are only supported by the MEMORY storage engine:

  1. B-Tree: such indexes are the most frequently used type of index and it’s easy to understand why – they improve the performance of queries that search for exact matches of data, use the less than (“<”), more than (“>”) operators, or operators with an equal sign (“>=”, etc.): they are also used when wildcards are in use (not in all cases, though – we’ll get into that in a moment.)
    B-Tree indexes are sorted tree structures that are suited for databases that deal with a lot of data due to its ability to traverse a tree from top to bottom in a recursive fashion. Due to the fact that B-Tree indexes are sorted, exact searches (searches with the “=” operator) are made blazing fast.
  2. R-Tree, or spatial, indexes are used when DBAs are running operations on geographical data.
  3. Hash indexes are used for exact matches of data (i.e. only queries that use either the “=” or the “<=>” operators.) but only within the MEMORY storage engine

Index Properties

Indexes also have multiple properties that need to be discussed:

  1. Covering indexes cover all of the columns required for a query to execute and when they are in use, MySQL can read them instead of reading the data. Since reading the index is significantly faster than reading the data, queries also finish quickly.
    Such indexes are pretty self-explanatory: include all of the columns used by the query in the index, and you have a covering index. Woohoo!
  2. Composite indexes are sometimes confused with covering indexes, but they’re not the same; composite indexes cover multiple columns, but these columns may not necessarily be the columns that a specific query might be using.
  3. Prefix indexes index a prefix (a part) of a column. Such types of indexes are frequently used when developers need to save storage space, but need the upsides of an index too. For example, should we want to index the first 5 characters existing in an email column, we can do that like so:
    CREATE INDEX prefix_idx ON demo_table(email(5));
    Once such an index is created, we should observe the table structure within phpMyAdmin – we will see a row saying “column (characters)” in it indicating that only a specific amount of characters are indexed – according to MySQL, for more characters than defined the index is used to exclude rows that don’t match the query, and the remaining rows are scanned through for possible use cases with the index (see example below.) (In the following image, you can see that we have a PRIMARY KEY on the id column two other indexes.):
  4. Clustered indexes – these indexes are unique in a couple of aspects firstly because only one clustered index can exist on a table at a time. A clustered index is also an index with the exact order of rows in the index as in the table. In MySQL, such indexes are often used at the PRIMARY KEY constraints index structure, though that’s not always the case – refer to the documentation for more information.

Indexes Examples

Now for the examples. Not that when observing the EXPLAIN statement output, the cardinality column doesn’t define the number of rows in a column, but rather the number of unique values in it.

  1. B-Tree indexes are usually defined like so (email_idx is the name of the index, and email is the name of the column):
    ALTER TABLE `demo_table` ADD INDEX email_idx(email);
    If we don’t want to use ALTER, we can also create indexes like so (email_idx is the name of the key – keys are different names for indexes):
    CREATE INDEX email_idx ON demo_table (email, another_column_if_you_like, ...);


  2. R-Tree, or spatial, indexes can only be defined on geographical data – that is, columns having the GEOMETRY data type. R-Tree indexes are suited for indexing geographical data due to its nature: the data structure is suited for geographical coordinates, but bear in mind that LIKE queries may not always use indexes as you can see below:
    ALTER TABLE 'demo_table' ADD SPATIAL INDEX(column);
    For more detail on R-Tree structures, see this Wikipedia article.
  3. For an index to be a covering index for a query, it must include all of the columns in a table that a specific query is using. So, for example, if our query looks like SELECT * FROM demo_table WHERE c1 = 'A' AND c2 = 'B';, our covering index would look like so (phpMyAdmin will also show the cardinality of both index key columns towards the right):
    ALTER TABLE `demo_table` ADD INDEX covering_idx (email,username);


    In this case, MySQL has elected to use the covering index – the index is of 224 characters in size.
    Covering indexes cover all of the fields required for a query to execute (see example below.) A covering index covers all of the columns required for a query to execute, but not necessarily in a specific manner, meaning that if we would switch the order of columns, the index would still be covering. If our query looks like this, we would most likely benefit from an index on the columns c1, c2, and c3:
    SELECT * FROM demo_table WHERE c1 = ‘Demo’ AND c2 = 'Demo' AND c3 = 'demo@demo.com';
  4. Composite indexes include multiple columns, but will not necessarily cover all of the columns for any given query. If we have three columns – c1, c2, and c3, a composite index would be any index that covers multiple columns. Such an index may cover columns c1 and c2, it may index the columns c3 and c1, it may have other combinations – but if the index does not cover all of the columns required for a query to execute, it’s not a covering index. Composite indexes are simply indexes that include multiple columns inside of them and they don’t have anything unique to themselves, other than the fact that key columns need to be ordered first, so the most important columns are scanned first.
    In this case, we cover the username and id columns with a query like so:
    ALTER TABLE 'demo_table' ADD INDEX covering_idx(username,id);

  5. Indexing a prefix of a column might be a necessity to save storage space – the golden rule here is that the fewer characters that are in the prefix, the better for storage, but worse for performance because of the additional scan of rows that partially match that is necessitated. If you don’t have much storage space but still want increased performance, prefix indexes are for you. Define prefix indexes like so (in this example, we assume that your column is called c1 and we index the first 5 characters of the column):
    ALTER TABLE 'demo_table' ADD INDEX idx_name(c1(5));
    When such indexes are in use, we could still search for exact matches as we do below (we only indexed the first 5 characters, but the query was still using index):
  6. PRIMARY KEY indexes are usually defined when creating a table, and they must be set to increment automatically:
    CREATE TABLE demo_table (
    'id' INT(255)
    PRIMARY KEY AUTO_INCREMENT,
    `column_1` VARCHAR(255),
    ...
    );


    As you can see from the query below, the id column has incremented by 1 since one row was inserted into the table:

As far as PRIMARY KEY constraint indexes are concerned, keep in mind that the type of the column that has a primary key doesn’t have to be an integer. For MySQL, PRIMARY KEY constraints have the following requirements:

  • The column that has a primary key constraint on it cannot be null, nor should it be empty.
  • The column that has a primary key constraint on it must only contain unique values.
  • A table can only contain one primary key constraint.
  • The length of the column that has a primary key constraint cannot be longer than 767 bytes.

Also, keep in mind that primary key constraints can consist of multiple columns – for many, such an approach looks like the following (notice the constraint on line 6):

D:\Redgate\Blogs\November 2022\Optimiziation Series\Optimizing SELECT Queries\Images\Primary Key.png

Indexes affect queries in various ways: the aim of B-Tree indexes is to help the database find rows matching a specific WHERE clause quickly enough. How much the performance is improved can depends on how our instances are configured. Some indexes are typically added when creating a table or with an ALTER TABLE query defined above.

There are also fulltext type indexes for those who would like to run more queries that behave more like search engine, for example when searching through long text columns, Fulltext indexes are defined by adding the FULLTEXT keyword in the ALTER TABLE or CREATE TABLE queries, or when creating tables, they can be defined like so:

CREATE TABLE demo_table (
  id INT(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  email VARCHAR(35) NOT NULL,
  username VARCHAR(20) NOT NULL DEFAULT '',
  FULLTEXT KEY(email)
) ENGINE = InnoDB;

There is also a type of index that’s a fit for the MEMORY storage engine – hash indexes can be defined like so (in this case, demo_table_memory is based upon the MEMORY storage engine instead of InnoDB. Make sure your table is based upon the MEMORY storage engine before running this query):
ALTER TABLE `demo_table_memory` ADD INDEX idx_name(column); USING HASH;
Hash indexes are only supported when the MEMORY storage engine is in use, and they only support exact matches of data (only queries with the “=” operator.) Also, note that you should bear in mind the amount of memory available on the server to not face the “The table is full” error (the name of the table will be weird because it’s in memory):

Partitioning MySQL

Now for partitions. They also have multiple types – aside from the fact that tables can be either partitioned horizontally or vertically, there are six partitioning types that are available. Also, mind the fact that since some storage engines don’t provide support for partitioning, partitions are recommended to use on InnoDB or XtraDB storage engines.

MySQL has six partitioning types (as of the time of writing, MySQL supports horizontal partitioning, but not vertical):

  1. Partitioning by RANGE – such a partitioning type is used to partition data that falls within a given range. For example, if we have a large data set and we search for values beginning with numbers, we might benefit from partitions beginning with 0, 1, 2, and other numbers.
  2. Partitioning by LIST – such a partitioning type is used to partition data that falls within one category in one partition, another category in another, etc. Think about geographical data falling in East, West, North, or East – such a partitioning type would be useful when 4 partitions are in use and values of rows could fall in one or more of defined lists.
  3. Partitioning by COLUMNS can let people partition data by columns – i.e. such a partitioning type lets you use multiple columns as partitioning keys.
  4. Partitioning by HASH is frequently used when partitioning id columns. Partitioning by HASH lets people split the data into a specified number of partitions with an equal amount of rows in them.
  5. Partitioning by KEY is similar to partitioning by HASH, except that MySQL chooses the way of partitioning data. If users don’t want to, columns don’t have to be defined – simply specifying the number of partitions is enough.

The list below will tell you when certain partitioning types should be used:

  • Partitioning by RANGE is frequently used by search engines that deal with a lot of data and need quick SELECT response times.
  • Partitioning by LIST is used when we need a couple of lists falling within a category.
  • Partitioning by COLUMNS is used by MySQL to determine which partitions are to be checked for matching rows or for the purpose of placing rows into partitions.
  • Partitioning by HASH ensures even distribution of data across partitions.
  • Partitioning by KEY is similar to partitioning by HASH, just that it takes a hashing function provided to it by MySQL.

There is also a concept known as subpartitioning which is relatively self-explanatory: it refers to partitions within partitions.

Partitions are usually defined when creating tables, and they can be defined like so (in this example, we use partitioning by KEY, but other partitioning types can be defined in a similar fashion – refer to the documentation for explanation, and before deciding on any one specific partitioning type, make sure to experiment):

CREATE TABLE demo_table (
id INT NOT NULL PRIMARY KEY,
email VARCHAR(35) NOT NULL,
username VARCHAR(20) NOT NULL DEFAULT ‘’
) PARTITION BY KEY() PARTITIONS 5;

In newer versions of MySQL (MySQL 8.0 and above – at the time of writing, MySQL 8.0.31 was the most recent stable release), partitioning is only supported in InnoDB and NDB storage engines – if older versions of MySQL are in use, users can also elect to partition data in the MyISAM storage engine. For more details of how partitioning impacts SELECT operations, refer to the MySQL documentation.

Tips & Tricks for Optimizing Read Operations

The optimization of SELECT operations using indexes is not a completely worry-free operation where you add a bunch of indexes and it all just works. Problems are an inevitable part of optimization operations, so we’ve also prepared a quick cheat sheet of tips & tricks that you can glance at and solve if not all, at least the majority of the problems you’re facing:

  • Use normalization wherever possible – a properly normalized database is typically great for SELECT queries. This is because the lack of redundant data means less to be read. This has its limits based on instance capacity, number of rows, and how many tables are needed to answer queries, but it is almost always better to have a well normalized database.
  • After creating an index, make sure that your queries use the indexes you have created for the queries that read data. Use EXPLAIN to allow MySQL to tell you what indexes are used and why (see examples we gave earlier on.) and adjust where necessary.
  • Make use of the LIMIT clause where necessary and avoid using the “SELECT *” operator if possible – the less data you select, the faster your queries will become (the default limit of rows that are returned by MySQL is 200.)
  • If possible, avoid overcomplicating your SELECT statements. Sometimes using too many OR expressions can mean that MySQL needs to use an index more than one time. It can be valuable to consider splitting a query into two queries, returning less results (use LIMIT), or selecting fewer columns to return (instead of using SELECT * use SELECT columnname, columnname2, etc.)
  • If you find yourself using wildcards with the LIKE expression (a wildcard is the '%' operator), make sure to employ them only at the end of the search string. Using '%' at the start of your expression will return all data to be scanned, which typically makes the search operation slower.

SELECT Queries: DDL and the Data

As we’ve mentioned in the beginning of the article, now we’ll provide you with a couple of DDL operations to help you get started.

First off, we have to create the tables (the names of the tables and their contents can be any – also note that the tables should use the InnoDB or XtraDB storage engines for the best results in the optimization realm):

CREATE TABLE demo_table (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(35) NOT NULL,
username VARCHAR(20) NOT NULL DEFAULT ‘’
)  ENGINE = InnoDB;
  1. Now, we have to fill the table up with data – One method is to use the FillDB dummy data generator for that task – paste your database schema (you might need to rename some of your tables – the data generator saves all of the previously used table names), then generate data for columns:
  2. Finally, specify the number of rows to be generated (we recommend to generate no more than 100,000 rows at once to not overwhelm your browser), then move on:
  3. Your data should be now ready to go – you will be able to view the data that the tool has generated:
  4. The only thing left for you to do is to import the data into your own database instance. Export the file from the dummy data generator by clicking the cyan button towards the right (it should say “Export tablename.”)

Now, import the data into MySQL via the CLI or the Import functionality within phpMyAdmin, and have fun optimizing your queries!

The Downsides of Optimizing SELECT statements

At the end of the day, almost everything we need to do to optimize a SELECT query comes down to the fact that we need to make MySQL able to access as little data as possible. If that doesn’t help, we need to look into the configuration of our MySQL instances.

However, one of the most significant nuances in this space is that when SELECT queries are being optimized, we need to compromise on storage and the performance of other queries.

That’s because indexes and partitions speed up read operations, but slow down the speed of INSERT, UPDATE, and DELETE queries. This is because when data is modified data also needs to be inserted, updated, or deleted together with it, and data may need to be shuffled around internally as well. It is rare that you have so many indexes that it noticeably harms performance, but it can happen, especially for high-throughput database applications.

Also keep in mind that the usefulness of indexes depends a lot on how frequently our queries are being executed. If a query is executed daily and saves 10 seconds on the runtime, is it worth it for all the maintenance it requires? Before making use of any advice mentioned in this article in a production environment, make sure to experiment and play around with the advice given in this article, and you should be good to go!

Summary

In this blog, we’ve walked you through numerous ways that help both novices and experienced DBAs optimize their SELECT query performance in MySQL. We’ve told you what query profiling has to do with their performance, walked you through the query execution plan provided by EXPLAIN queries, types of indexes, and partitioning.

We hope that some of the information provided in this blog has helped you optimize your SELECT query performance – tell us if the advice given in this blog has helped empower your applications in the comment section down below, come back to the blog to read up on how to optimize the performance of other types of queries, and until next time!

 

The post Optimizing Queries in MySQL: Optimizing Reads appeared first on Simple Talk.



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

Wednesday, January 25, 2023

AWS Lambdas with C#

Serverless computing is pushing C# to evolve to the next level. This is exciting because you pay-per-use and only incur charges when the code is running. This means that .NET 6 must spin up fast, do its job, then die quickly. This mantra of birth and rebirth pushes developers and the underlying tech to think of innovative ways to meet this demand. Luckily, the AWS (Azure Web Services) serverless cloud has excellent support for .NET 6.

In this article, I will take you through the development process of building an API on the serverless cloud with C#. This API will be built to serve pizzas, with two endpoints, one for making pizza and the other for tasting fresh pizzas. I expect some general familiarity with AWS and serverless computing. Any previous experience with building APIs in .NET will also come in handy.

Feel free to follow along because I will guide you through this step-by-step. If you get lost, the full sample code can be found on GitHub.

Getting the AWS CLI Tool

First, you will need the following tools:

  • AWS CLI tool
  • .NET 6 SDK
  • Rider, Visual Studio 2022, Vim, or an editor of choice

The AWS CLI tool can be obtained from the AWS documentation. You will need to create an account then set up the CLI tool with your credentials. The goal is to configure the credentials file under the AWS folder and set an access key. You will also need to set the region depending on your physical location. Because this is not an exhaustive guide on getting started, I will leave the rest up to you the reader.

Create a New Project

I will pick the .NET 6 CLI tool because it is the most accessible to everyone. You can open a console via Windows Terminal or the CMD tool. Before you begin, verify that you have the correct version installed on your machine.

> dotnet --version

This outputs version 6.0.42 on my machine. Next, you will need the AWS dotnet templates:

> dotnet new -i Amazon.Lambda.Templates
> dotnet tool install -g Amazon.Lambda.Tools

If you have already installed these templates, simply check that you have the latest available:

> dotnet tool update -g Amazon.Lambda.Tools

Then, create a new project and a test project with a region.

> dotnet new serverless.AspNetCoreMinimalAPI -n Pizza.Api \
    --profile default --region us-east-1

> dotnet new xunit -n Pizza.Api.Tests

Be sure to set the correct region, one that matches your profile in the AWS CLI tool.

The dotnet CLI generates a bunch of files and puts them all over the place. I recommend doing a bit of manual clean up and follow the folder structure below in Figure 1.

Graphical user interface, text, application Description automatically generated

Figure 1. Folder structure

You may also create the solution file Pizza.Api.sln via:

> dotnet new sln -n Pizza.Api
> dotnet sln add src\Pizza.Api\Pizza.Api.csproj
> dotnet sln add test\Pizza.Api.Tests\Pizza.Api.Tests.csproj

This allows you to open the entire solution in Rider, for example, to make the coding experience much richer.

The template generated nonsense like a Controllers folder and HTTPS redirect. Simply delete the Controllers folder in the Pizza.Api folder and delete the UnitTest1.cs file that is in the Pizza.Api.Tests folder.

In the Program.cs file delete the following lines of code.

builder.Services.AddControllers();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

The HTTPS redirect is a pesky feature that only applies to local to make life harder for developers. On the AWS cloud, the AWS Gateway handles traffic before it calls into your lambda function. Gutting dependencies also helps with cold starts. Trimming middleware like Controllers and Authorization keeps the request pipeline efficient because you get billed while the code is running. One technique to keep costs low, for example, is to use Cognito instead of doing auth inside the lambda function.

Run Your Lambda on Local

Luckily, .NET 6 makes this process somewhat familiar to .NET developers who are used to working with on-prem solutions. Be sure to have (or create) the following launchSettings.json under a Properties folder in the project:

{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "profiles": {
    "Pizza.Api": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": false,
      "applicationUrl": "http://localhost:5095",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

Now, go back to the console and run the app under the ..\Pizza.Api\src\Pizza.Api folder:

> dotnet watch

There should be an output telling you it is now running under the port number 5095.

This watcher tool automatically hot reloads, which is a nice feature from Microsoft, this is to keep up with code changes on the fly without restarting the app. This is mostly there for convenience, so I recommend keeping an eye out to make sure the latest code is actually running.

Then, use CURL to test your lambda function on local, make sure the -i flag remains lowercase or try –include:

> curl -X GET -i -H "Accept: application/json" http://localhost:5095

With the AWS tools, developers who are familiar with .NET should start to feel more at home. This is one of the niceties of the ecosystem, because the tools remain identical on the surface.

The one radical departure so far is using the minimal API to host an endpoint and I will explore this topic next.

Make a Pizza

To make a pizza, first, you will need to install the DynamoDB NuGet package in the project. (If you are not acquainted with Amazon DynamoDB, you can get more information here)

In the same Pizza.Api folder, install the dependency:

> dotnet add package AWSSDK.DynamoDBv2

Also, this project requires a Slugify dependency. This will convert a string, like a pizza name, into a unique identifier we can put in the URL to find the pizza resource in the API.

To install the slugify dependency:

> dotnet add package Slugify.Core

With lambda functions, one goal is to keep dependencies down to a minimum. You may find it necessary to copy-paste code instead of adding yet another dependency to keep the bundle size small. In this case, I opted to add more dependencies to make writing this article easier for me.

Create a Usings.cs file in the Pizza.Api directory in src and put these global usings in:

global using Amazon;
global using Amazon.DynamoDBv2;
global using Amazon.DynamoDBv2.DataModel;
global using Pizza.Api;
global using Slugify;

Now, in the Program.cs file wire up dependencies through the IoC container:

builder.Services.AddSingleton<IAmazonDynamoDB>( _ =>
  new AmazonDynamoDBClient(RegionEndpoint.USEast1));
builder.Services.AddSingleton<IDynamoDBContext>(p =>
  new DynamoDBContext(p.GetService<IAmazonDynamoDB>()));
builder.Services.AddScoped<ISlugHelper, SlugHelper>();
builder.Services.AddScoped<PizzaHandler>();

Note your region can differ from mine. I opted to use the DynamoDB object persistence model via the Amazon.DynamoDBv2.DataModel namespace to keep the code minimal. This decision dings cold starts a bit, but only a little. Here though, I am paying the cost of latency to gain developer convenience.

The DynamoDB object persistence model requires a pizza model with annotations so it can do the mapping between your C# code and the database table.

Create a PizzaModel.cs file, and put this code in:

namespace Pizza.Api;

[DynamoDBTable("pizzas")]
public class PizzaModel
{
  [DynamoDBHashKey]
  [DynamoDBProperty("url")]
  public string Url { get; set; } = string.Empty;

  [DynamoDBProperty("name")]
  public string Name { get; set; } = string.Empty;

  [DynamoDBProperty("ingredients")]
  public List<string> Ingredients { get; set; } = new();

  public override string ToString() =>
    $"{Name}: {string.Join(',', Ingredients)}";
}

Given the table definition above, create the DynamoDB table via the AWS CLI tool:

> aws dynamodb create-table --table-name pizzas \
      --attribute-definitions AttributeName=url,AttributeType=S \
      --key-schema AttributeName=url,KeyType=HASH \
      --provisioned-throughput ReadCapacityUnits=1,WriteCapacityUnits=1 \
     --region us-east-1 --query TableDescription.TableArn --output text

The url field is the hash which uniquely identifies the pizza entry. This is also the key used to find pizzas in the database table.

Next, create the PizzaHandler.cs file, and put in a basic scaffold:

namespace Pizza.Api;

public class PizzaHandler
{
  private readonly ISlugHelper _slugHelper;
  private readonly IDynamoDBContext _context;
  private readonly ILogger<PizzaHandler> _logger;

  public PizzaHandler(
    IDynamoDBContext context,
    ISlugHelper slugHelper,
    ILogger<PizzaHandler> logger)
  {
    _context = context;
    _slugHelper = slugHelper;
    _logger = logger;
  }

  public async Task<IResult> MakePizza(PizzaModel pizza)
  {
    throw new NotImplementedException();
  }

  public async Task<IResult> TastePizza(string url)
  {
    throw new NotImplementedException();
  }
}

This is the main file that will serve pizzas. The focus right now is the MakePizza method.

Before continuing, create the PizzaHandlerTests.cs file under the test project:

namespace Pizza.Api.Tests;

public class PizzaHandlerTests
{
  private readonly Mock<IDynamoDBContext> _context;
  private readonly PizzaHandler _handler;

  public PizzaHandlerTests()
  {
    var slugHelper = new Mock<ISlugHelper>();
    _context = new Mock<IDynamoDBContext>();
    var logger = new Mock<ILogger<PizzaHandler>>();

    _handler = new PizzaHandler(
      _context.Object,
      slugHelper.Object,
      logger.Object);
  }
}

The test project should have its own Usings.cs file, add these global entries:

global using Moq;
global using Amazon.DynamoDBv2.DataModel;
global using Microsoft.Extensions.Logging;
global using Slugify;

Also, install the Moq dependency under the Pizza.Api.Tests project:

> dotnet add package Moq

You will also need the Slugify and Amazon.DynamoDBv2 packages seen in the Pizza.Api project as well. First, I like to unit test my code to check that my reasoning behind the code is sound. This is a technique that I picked up from my eight-grade teacher: “test early and test often”. The faster the feedback loop is between code you just wrote and a reasonable test, the more effective you can be in getting the job done.

Inside the PizzaHandlerTests class, create a unit test method:

[Fact]
public async Task MakePizzaCreated()
{
  // arrange
  var pizza = new PizzaModel
  {
    Name = "Name",
    Ingredients = new List<string> {"toppings"}
  };

  // act
  var result = await _handler.MakePizza(pizza);

  // assert
  Assert.Equal("CreatedResult", result.GetType().Name);
}

There is a little quirkiness here because the Results class in minimal API is actually hidden behind private classes. The only way to get to the result type is via reflection, which is unfortunate because the unit test is not able to validate the strongly typed class. Hopefully in future LTS (Long Term Support) releases the team will fix this odd behaviour.

Now, write the MakePizza method in the PizzaHandler to pass the unit test:

public async Task<IResult> MakePizza(PizzaModel pizza)
{
  if (string.IsNullOrWhiteSpace(pizza.Name)
    || pizza.Ingredients.Count == 0)
  {
    return Results.ValidationProblem(new Dictionary<string, string[]>
    {
      {nameof(pizza), new [] 
                {"To make a pizza include name and ingredients"}}
    });
  }

  pizza.Url = _slugHelper.GenerateSlug(pizza.Name);

  await _context.SaveAsync(pizza);
  _logger.LogInformation($"Pizza made! {pizza}");

  return Results.Created($"/pizzas/{pizza.Url}", pizza);
}

With minimal API, you simply return an IResult. The Results class supports all the same behaviour you are already familiar with from the BaseController class. The one key difference is there is a lot less bloat here which is ideal for a lambda function that runs on the AWS cloud.

Finally, go back to the Program.cs file and add new endpoints right before the app.Run.

using (var serviceScope = app.Services.CreateScope())
{
  var services = serviceScope.ServiceProvider;
  var pizzaApi = services.GetRequiredService<PizzaHandler>();

  app.MapPost("/pizzas", pizzaApi.MakePizza);
  app.MapGet("/pizzas/{url}", pizzaApi.TastePizza);
}

One nicety from minimal API is how well this integrates with the existing IoC container. You can map requests to a method, and the model binder does the rest. Those of you familiar with Controllers should see code that reads identical in the PizzaHandler.

Then, make sure the dotnet watcher CLI tool is running the latest code and test your endpoint via CURL:

> curl -X POST -i -H "Accept: application/json" ^
    -H "Content-Type: application/json" ^
    -d "{\"name\":\"Pepperoni Pizza\",\"ingredients\":[\"tomato sauce\",\"cheese\",\"pepperoni\"]}" http://localhost:5095/pizzas

Feel free to play with this endpoint on local. Notice how the endpoint is strongly typed, if you pass in a list of ingredients as raw numbers then validation fails the request. If there is data missing, validation once again kicks the unmade pizza back with a failed request.

You may be wondering how the app running on local is able to talk to DynamoDB. This is because the SDK picks up the same credentials used by the AWS CLI tool. If you can access resources on AWS, then you are also able to point to DynamoDB using your own personal account with C#.

Taste a Pizza

With a fresh pizza made, time to taste the fruits of your labor.

In the PizzaHandlerTests class, add this unit test:

[Fact]
public async Task TastePizzaOk()
{
  // arrange
  _context
    .Setup(m => m.LoadAsync<PizzaModel?>("url", default))
    .ReturnsAsync(new PizzaModel());

  // act
  var result = await _handler.TastePizza("url");

  // assert
  Assert.Equal("OkObjectResult", result.GetType().Name);
}

This only checks the happy path; you can add more tests to check for failure scenarios and increase code coverage. I’ll leave this as an exercise to you the reader, if you need help, please check out the GitHub repo.

To pass the test, put in place the TastePizza method inside the PizzaHandler:

public async Task<IResult> TastePizza(string url)
{
  var pizza = await _context.LoadAsync<PizzaModel?>(url);

  return pizza == null
    ? Results.NotFound()
    : Results.Ok(pizza);
}

Then, test this endpoint via CURL:

> curl -X GET -i -H "Accept: application/json" http://localhost:5095/pizzas/pepperoni-pizza

Onto the Cloud!

With a belly full of pizza, I hope nobody feels hungry, deploying this to the AWS cloud feels seamless. The good news is that the template already does a lot of the hard work for you so you can focus on a few key items.

First, tweak the serverless.template file and set the memory and CPU allocation. Do this in the JSON file:

{
  "Properties": {
    "MemorySize": 2600,
    "Architectures": ["x86_64"]
  }
}

This sets a memory allocation of 2.5GB, with a x86 processor. These allocations are not final because you really should do monitoring and tweaking to figure out an optimal allocation for your lambda function. Increasing the memory blindly does not guarantee best results, luckily there is a nice guide from AWS that is very helpful.

Before you can deploy, you’ll need to create an S3 bucket which is where the deploy bundle will go. Note that you may need to provide your own name for the S3 bucket:

> aws s3api create-bucket --acl private --bucket pizza-api-upload \
    --region us-east-1 --object-ownership BucketOwnerEnforced
> aws s3api put-public-access-block --bucket pizza-api-upload \
    --public-access-block-configuration "BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true"

Then, deploy your app to the AWS cloud via the dotnet AWS tool:

> dotnet lambda deploy-serverless --stack-name pizza-api --s3-bucket pizza-api-upload

Unfortunately, the dotnet lambda deploy tool does not handle role policies for DynamoDB automatically. Login into AWS, go to IAM, click on roles, then click on the role the tool created for your lambda function. It should be under a logical name like pizza-api-AspNetCoreFunctionRole-818HE2VECU1J.

Then, copy this role name, and create a file dynamodb.json with the access rules:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "dynamodb:DescribeTable",
        "dynamodb:GetItem",
        "dynamodb:PutItem",
        "dynamodb:UpdateItem"
      ],
      "Effect": "Allow",
      "Resource": "*"
    }
  ]
}

Now, from the Pizza.Api project folder, grant role access to DynamoDB via this command:

> aws iam put-role-policy --role-name pizza-api-AspNetCoreFunctionRole-818HE2VECU1J \
      --policy-name PizzaApiDynamoDB --policy-document file://./dynamodb.json

Be sure to specify the correct role name for your lambda function.

Finally, taste a pre-made pizza via CURL. Note that the dotnet lambda deploy tool should have responded with a URL for your lambda function. Make sure the correct GATEWAY_ID and REGION go in the URL.:

> curl -X GET -i ^
  -H "Accept: application/json" https://GATEWAY_ID.execute-api.REGION.amazonaws.com/Prod/pizzas/pepperoni-pizza

I recommend poking around in AWS to get more familiar with lambda functions.

The API Gateway runs the lambda function via a reverse proxy. This routes all HTTPS traffic directly to the kestrel host, which is the same code that runs on local. This is a bit more costly because the lambda function routes all traffic, but the developer experience is greatly enhanced by this. Go to S3 and find your pizza-api-upload bucket, notice the bundle size remains small, around 2MB. The dotnet AWS tool might be doing some trimming to keep cold starts low. Also, look at CloudWatch and check the logs for your lambda function. You will find cold starts in general are below .5 sec, this is great news! In .NET 6, the AWS team has been able to make vast improvements which I believe will continue in future LTS releases. Lastly, note the VM that executes the lambda runs on Linux, this is another area of improvement that is also possible in .NET 6.

Conclusion

AWS lambda functions with C# are now production ready. The teams from both Microsoft and AWS have made significant progress in .NET 6 to make this dream a reality.

 

The post AWS Lambdas with C# appeared first on Simple Talk.



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

Tuesday, January 24, 2023

Testing before coding: shifting farther left

Times have changed so much; when I wrote my first book on database design, I didn’t mention testing. In some respects, I thought it was obvious that everyone would gather requirements and test to make sure what they were building did what they expected. Let’s say I was younger then and considerably more naïve.

The Story

As a data architect, I typically found most of my problems in life just happened to occur less because of coding bugs and more because what I had designed didn’t match what the customer actually wanted. One of my first significant design mistakes came when designing a chemical plant QA system. Our analysts gathered requirements, gave them to the development team, and we implemented them. We did system testing and quality testing with the customer. There were poor time estimates, and cost overruns, but the software worked and worked, and our team believed it worked quite well.

Then we went live. There were lots of typical minor bugs, but everything was working great. Until the day the system would not let them do something that was out of the ordinary. One of the key requirements we were given was not to allow shipments if the material didn’t meet a certain quality. Eradicating previous quality issues was the central goal of this new system. What was not discussed was what happens if their customer wants to override that quality setting and take shipment anyhow? The team spent considerable time making sure that our system could not ship sub-standard product because that is what the requirements said.

The problem came down to the fact that we didn’t understand what the customer wanted in a way that cost them money. Delayed shipments and manual processing were required because the system wouldn’t allow them to do something that was apparently commonplace.

Test Very Early, Test Very Often

To fix this, I have always tried to test early, earlier, and earliest. Start before coding has started with the requirements. Find a way, in the customer’s language to verify that the requirements you have stated are accurate. Challenge requirements that are too specific. “We only see patients 18 years and younger” often means “We rarely see patients 18 years old and younger unless we decide to. In this case, there is a process that needs to be a part of the system, or it will be a horrible failure, but at least you will have a story to write about someday”.

It means getting representatives from the user community (not just upper-level management) to interact with the requirements that have been agreed upon and make sure they make sense. Challenge them to give you the odd (and very odd) along with typical cases. Some significant concerns happen once a year.

The farther you are left in the timeline, the easier it is to make changes. If it is still a document, just hit backspace and type the new requirement. If the business analyst had identified the override, or our team had asked the question “really, you can’t sell substandard materials to anyone?” money would have been saved.

The Process

Once we get to the “really sure” level of confidence that the requirements are correct, you can design more confidently. As a data professional, data models have a few natural checkpoints built into the process that can be very helpful. Start with a conceptual model that is just table names and projected relationships (the tables are concepts, hence the name conceptual model). Then test to make sure you can meet the requirements.

Take each requirement and just ask, “can I?” Can I store customer information? Can I represent an order? Can I represent an order of 10 products? 100 products? 10 orders in a minute? Not just the normal data you know of, but as many possibilities that could happen. Once you can meet that level of comfort with your model, you are getting close to a design that will only be decorated with attributes, not torn apart, and restarted over and over.

As you flesh out attributes, then start creating tables, constraints, etc., unit testing, integration testing, and then user acceptance testing are done hand in hand with the entire process. Every step of the way, verifying that what you have built meets the requirements you tested for veracity with the user community in the beginning.

Whether you are working in short sprints or long waterfall projects, the main difference is the amount of work you are doing. Continue this process of verification all the way through until you finish and start to work on the next thing.

Nothing is Ever Easy as It Sounds

The entire development process can be pretty easy except for the first step. Gathering requirements that meet what the customer wants a system to do is one of the most challenging jobs in existence that doesn’t require a Ph.D. in Mathematics. Why? Because most users are clueless as to how to tell you what they want most of the time. And the worst offenders think they know what they want without discussion.

Once you have requirements, designing and implementing software to meet well-written requirements is not necessarily trivial, but it is relatively straightforward. Luckily there is lots of software out there to help you with those tasks.

 

The post Testing before coding: shifting farther left appeared first on Simple Talk.



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

Monday, January 23, 2023

Azure Functions and Managed Identity: More Secrets

I wrote about Managed Identity Secrets a few weeks ago, but since that article was published I made new interesting discoveries to add more to these secrets.

The combination of possibilities is considerable, and I faced two new situations I hadn’t faced before. Let’s discover the new secrets.

 

Storage Accounts and Triggers

The storage account triggers depend on configurations in the Function/App to stablish the connection.

This configuration is intended to contain a connection string built with a storage account key or SAS key.

When we want to use Managed Identities, the configuration needs to be different. The name we use in the trigger code becomes only the prefix for the configuration.

We need different configuration entries for the blob service and the queue service, each one containing the full address of the service. In this way, the trigger understands we intend to use Managed Identity authentication, instead of key/SAS authentication.

These are the names you should use for the configuration values:

<CONNECTION_NAME_PREFIX>__blobServiceUri

<CONNECTION_NAME_PREFIX>__queueServiceUri

Aplicativo Descrição gerada automaticamente com confiança baixa

Reference: https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-blob-trigger?tabs=in-process%2Cextensionv5&pivots=programming-language-csharp

Blobs Requires Queues

When you use keys, usually the connection string has the endpoint for all the services, blobs and queues.

When using managed identities, as explained above, the endpoint is in two different configurations. This brings up another secret: When connecting to a blob using the blob trigger, the queue connection is required as well.

The blob trigger handles failures using a queue, for this reason, when using the blob trigger the queue endpoint needs to be specified as well.

 

Azure SQL and User Managed Identities

The connection string for System Managed Identities is simple, as explained on the first article.

When using User Assigned Managed Identity, on the other hand, we need an additional parameter on the connection string. We need to specify the Client Id of the User Assigned Managed Identity we intend to use.

The Client Id is specified as the User Id. The connection string will be like this:

Server=DBServer.database.windows.net; Authentication=Active Directory Managed Identity; Initial Catalog=adventure;User Id=19fad297-5cf8-4fb9-9601-26d38d7854aa

Interface gráfica do usuário, Texto Descrição gerada automaticamente com confiança média

This also applies to SQL Server 2022, which supports Azure AD Authentication.

 

Bonus: Using configurations to customize trigger parameters

Some trigger parameters are not so obviously configurable. For example, the queue name when connecting to a storage queue.

You wouldn’t like to have this kind of value tied in your code. The flexibility to change the queue name, for example, is very welcome. We can use different queue names for development, UAT and production environment, for example.

The solution is simple: you can use the ‘%’ symbol to retrieve a configuration value as a trigger parameter.

For example, a queue trigger would become like this:

[QueueTrigger(“%queuenameconfig%”, Connection = “inputStorage”)]

The connection parameter is retrieved from the configuration naturally, with the additional details explained above about managed identities. The queue name, on the other hand, will only the retrieved from configuration if transformed in a variable using the ‘%’ symbol.

 

Conclusion

Using Managed Identities on PAAS services can be full of tricks. Don’t assume a service doesn’t support it, you may be missing a configuration.

 

The post Azure Functions and Managed Identity: More Secrets appeared first on Simple Talk.



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

Friday, January 20, 2023

PostgreSQL Basics: Roles and Privileges

Authentication

Authorization
Verify that the user is who they claim to be. This can be through password, trust, or some other federated login (like Kerberos) As an authenticated user, what am I permitted to do within the system?

Before we get started, lets establish a few terms:

  • Roles: There is only one type of authentication principal in PostgreSQL, a ROLE, which exists at the cluster level. By convention, a ROLE that allows login is considered a user, while a role that is not allowed to login is a group. Please note, while the CREATE USER and CREATE GROUP commands still exist, they are simply aliases for CREATE ROLE.
  • Database Objects: Anything that can be created or accessed in the PostgreSQL cluster is referred to as an object. Databases, schema, tables, views, procedures, functions, and more can each have different privileges applied to them for any role.
  • Privileges: The types of access that can be granted to a role for a database object. Often these will be applied at a database or schema level, but the ability to apply specific access to individual objects is always available. Privileges assigned to one role can be granted to other roles. This is typically done by granting group roles (those that cannot login) to user roles (those that can login) to assist with privilege management.

Depending on your previous experience with information security (within a database, operating system, or application), the way that these components work together in PostgreSQL may be different than you would expect.

Throughout this article you will see references to a PostgreSQL cluster. If you are new to PostgreSQL, this term may really confuse you. This is the way that PostgreSQL refers to the individual server/instance that’s running and hosting (a cluster of) databases. It does not mean that multiple servers are setup in a multi-node environment.

Principle of Least Privilege

One other key idea to discuss is the Principle of Least Privilege (PoLP), an information security methodology that states users should only be granted access to the least amount of information needed to do their job or task. Any access beyond files or data that they own must be specifically granted to them.

Although not stated specifically in documentation, many of the nuances of PostgreSQL security and how roles and privileges work together, feel like they are implemented with PoLP in mind.

For instance, only the owner of a database object (schema, table, function, etc.) can use or alter it unless specific access has been granted to other roles. For example, most users would probably expect that two roles with the same database or schema privileges (eg. SELECT) should be able to select from any table by default. That’s not how it works in PostgreSQL without some intervention.

Instead, objects are always owned by a role (and only one role) which must set privileges for other roles in most cases. This behavior can be modified so that new objects a role creates automatically grants specific privileges to other roles, but out of the box, object ownership is a key concept to understand when creating roles and other objects in a PostgreSQL database.

We’ll look at this more in a follow-up article on object ownership and privileges.

Superusers

One last thing to discuss before diving into role creation and granting privileges is the concept of a superuser. In PostgreSQL, a superuser is a role that is allowed to do anything in the system and is analogous to the root user in Linux or the sa account in SQL Server.

When a user has been granted superuser, no permission checks are performed when they execute SQL code (DDL/DML) or administer the cluster. The only check that is performed is whether they are allowed to login and connect to the cluster. Being designated as a superuser bypasses all other checks, including things like Row Level Security (RLS). This behavior is different than some other database systems.

To function properly, every PostgreSQL cluster needs to have at least one superuser to perform some administration tasks. Initially these tasks might be creating databases and additional roles, but there are a few tasks as of PostgreSQL 15 (installing some extensions, modifying some server parameters) that still require a superuser.

In PostgreSQL this initial superuser account is called postgres by default, which typically matches the system username that is running the PostgreSQL cluster process. This initial superuser can be changed using the initdb command to instantiate your own PostgreSQL cluster. That discussion is beyond the scope of this article but is generally not recommended without more experience.

One final note. If your PostgreSQL database is hosted with a service such as AWS RDS or Azure Postgres, you will probably not have access to a superuser role. Instead, the initial role that is created for you has most privileges needed to administer users and create databases and objects. Even if you host your own PostgreSQL cluster and have access to a superuser role, the recommendation (and documented best practice) is to create at least one role that has CREATE USER and CREATE DATABASE permissions but is not a superuser. With these role-specific attributes, a role can create new users (or another database), but not bypass other security checks like selecting data from tables that they don’t have permission to. This will allow you to do almost all administrative tasks without the ability to bypass all privilege checks while working in the database or cluster.

PostgreSQL Roles

Recall that in PostgreSQL both users and groups are technically roles. These are always created at the cluster level and granted privileges to databases and other objects therein. Depending on your database background it may surprise you that roles aren’t created as a principal inside of each database. For now, just remember that roles (users and groups) are created as a cluster principal that (may) own objects in a database, and owning an object provides additional privileges, something we’ll explore later in the article.

For the purposes of this article, all example user roles will be created with password authentication. Other authentication methods are available, including GSSPI, SSPI, Kerberos, Certificate, and others. However, setting up these alternative methods is beyond what we need to discuss object ownership and privileges.

Create a User Role

To create a user role in PostgreSQL, execute the following DDL as a user that has the `CREATEROLE` privilege. As discussed above, this is typically the postgresql superuser or an administrative user provided by your hosting solution.

CREATE ROLE dev1 WITH LOGIN PASSWORD ‘supersecretpw’;

Alternatively, PostgreSQL still supports the older CREATE USER command, but it’s just an alias for CREATE ROLE. In theory it will be deprecated at some point, so users should tend towards CREATE ROLE.

-- This still works as of PostgreSQL 15. Same as above, 
-- but implicitly adds LOGIN
CREATE USER dev1 WITH PASSWORD ‘supersecretpw’;

At the most basic level, this is all that’s required to create a role that can login to the cluster. What they can do after authenticating depends on the privileges that you grant to them (which we’ll discuss in later in the article.)

Maintaining unique privileges among many user roles can be cumbersome and error prone. Therefore, it’s desirable to create roles that function as groups so that users can inherit group privileges as needed. For example, consider the following diagram:

Graphical user interface Description automatically generated with low confidence

If a role is a member of the reader role, they have SELECT privileges on the public.table_name object. If they are in the creator role, then INSERT privileges, too, because each of those roles was explicitly granted privileges to a resource. Role reader_and_creator, which has not explicitly been granted any privileges outside of the public role, does have SELECT and INSERT privileges on public.table_name because it has been granted membership in both reader and creator. By crafting roles in a very deliberate manner, you can manage user roles through inheritance rather than granting individual privileges to each user. This is very important because user roles will change in different environments (people who can modify DEV may not even have access to login to the PROD cluster, for example.)Create a Group Role<

To create a group role in PostgreSQL, create a role that is not allowed to login. As mentioned earlier, this is simply a convention that denotes the role as a group.

CREATE ROLE devgrp WITH NOLOGIN;

Like user roles, PostgreSQL still supports the older CREATE GROUP command, although it is a direct alias for CREATE ROLE because all roles are created with NOLOGIN by default, which as we’ve discussed, means the role is used as a group. There is no advantage of using CREATE GROUP and it may be deprecated at some point.

There are numerous other role attributes that can be applied at the time of creation or through ALTER ROLE. Let me highlight a few additional role attributes and their default values.

Role Attribute Options (Default Bold)

Description

SUPERUSER/NOSUPERUSER

Is this role also a superuser? Superuser roles are required to effectively run a PostgreSQL cluster but should be rare and limited in use. All other privileges and role attributes checks are bypassed for a superuser. (ie. Superusers can do anything in the system!)

Only a superuser can create another superuser.

CREATEDB/NOCREATEDB

Can this role create databases on the given PostgreSQL cluster?

CREATEROLE/NOCREATEROLE

Is this role allowed to create additional roles (users or groups) on the PostgreSQL cluster?

INHERIT/NOINHERIT

Roles can be granted membership into other roles. If a role can inherit from another role, then they can automatically use privileges without having to switch roles, similar to how privileges work in operating and file systems.

If the user does not INHERIT privileges of the “parent” group, then they must switch to that role (SET ROLE) in order to utilize specific privileges of the group.

LOGIN/NOLOGIN

Can this role authenticate and login to the cluster? LOGIN must be specifically specified to allow a new role to authenticate.

See the documentation for all possible attributes and more detailed more information. Also, any of these role attributes (including superuser) can be modified at any time with the ALTER ROLE command.

Now that we have roles, one of which can login (our user) and one that can’t (our group), we need to dive into how privileges are assigned and applied.

The PUBLIC Role

Every PostgreSQL cluster has another implicit role called PUBLIC which cannot be deleted. All other roles are always granted membership in PUBLIC by default and inherit whatever privileges are currently assigned to it. Unless otherwise modified, the privileges granted to the PUBLIC role are as follows.

PostgreSQL 14 and below

PostgreSQL 15 and above

  • CONNECT
  • CREATE
  • TEMPORARY
  • EXECUTE (functions and procedures)
  • USAGE (domains, languages, and types)
  • CONNECT
  • TEMPORARY
  • EXECUTE (functions and procedures)
  • USAGE (domains, languages, and types)

The main thing to notice here is that the PUBLIC role always has the CONNECT privilege granted by default, which conveniently allows all roles to connect to a newly created database. Without the privilege to connect to a database, none of our newly created roles would be able to do much.

Connections to a PostgreSQL database cluster are always opened to a specific database, not just the cluster. Remember that we started this article talking about authentication and authorization. To open a connection to a PostgreSQL cluster, a user first needs to authenticate (provide credentials for a role WITH LOGIN) and then have authorization to connect to a database. Because every role is granted membership in the PUBLIC role and that role has the privilege to CONNECT by default, all roles that can authenticate are allowed to CONNECT to the database as well.

Many of these defaults can be modified. As a database administrator you could REVOKE the ability for the PUBLIC role to CONNECT and then grant it to each role individually, but the complexity of managing that is rarely worth the effort.

To be clear, this privilege only allows the user to connect and see high-level objects in the public schema (tables, for instance). However, they cannot select or modify anything from tables without further permission. We’ll talk about this in a bit.

There is one last thing I’d like to point out in the table above that lists default permissions for the PUBLIC role.

Notice that default privileges changed slightly in PostgreSQL 15 and above. Previously, the PUBLIC role was also allowed to CREATE objects in the public schema of a database, and every database has a public schema by default. This permission was granted to the public role many years ago for backwards compatibility with very old versions of PostgreSQL, but also presented a security vulnerability. With the rise of DBaaS services, the potential for a new role to create tables, triggers, and functions in the public schema meant that they could potentially execute code that would later result in the elevation of their privilege (or worse).

Therefore, starting with PostgreSQL 15, the public role can no longer create anything by default, regardless of the schema. While it means a bit more work for administrators, revoking the CREATE privilege has been a recommended best practice for a long time.

Testing The New Role

With the new user role we created, dev1, we can login to the PostgreSQL cluster with a tool like psql using the following command. In the following examples the PostgreSQL cluster is hosted locally on my laptop using Docker with the default port of 5432. Your connection details, including the database name, may be different and should be adjusted as necessary.

-- Using flags, you will be prompted for a password as 
-- there is no specific “password” flag
psql -h localhost -U dev1 -d postgres

-- Alternate using PostgreSQL connection URI
psql postgres://dev1:supersecretpw@localhost:5432/postgres

This will cause a prompt for a password (if you didn’t provide it through the URI) and will connect the user to the postgres database. It works because the dev1 role is automatically granted membership in the PUBLIC role, which in turn has permission to connect to the postgres database.

With password authentication and one DDL statement, we created a role and logged into the PostgreSQL instance. Not too difficult, right?

So now, let’s get to work developing a new feature as the newly created dev1 account!

Creating Objects With the New User

As a developer user my first order of business is to get to work creating the table required to support the new feature I’m working on. The feature requires a table to store social accounts for each user. I’m not sure how many social account handles we plan to support, so I’ll just start with a basic table that stores each handle in a separate column.

Depending on which version of PostgreSQL you’re connected to, this may or may not be as easy. Remember, PostgreSQL 14 and below allowed the PUBLIC role (which `dev1` is a member of) to CREATE in the public schema by default. PostgreSQL 15 and above, however, does not.

After logging in as `dev1`, we attempt to create the following table.

CREATE TABLE user_social (
   user_id INT NOT NULL,
   twitter_handle TEXT NULL,
   facebook_handle TEXT NULL );

In PostgreSQL 14 and below, this probably succeeds on most installations given the setup we’ve done so far. In PostgreSQL 15 and above, however, our dev1 user most likely receives the following error.

ERROR: permission denied for schema public
LINE 1: CREATE TABLE user_social (

Let me reiterate, this only works in PostgreSQL 14 and below because the PUBLIC role is granted the ability to CREATE objects in the public schema by default. We would receive a similar error if we tried to do something like create a new schema in the database because PUBLIC has not been granted the CREATE privileges for the entire database, only the public schema.

For reference, the CREATE privilege can be applied to three areas in PostgreSQL (database, schema, and tablespaces) and allow creation of different objects depending on where you have permission to CREATE, as outlined on the privileges page in the documentation.

Whether we need to create a table or a new schema, how do we ensure that new developer roles can do that?

We must GRANT them privileges.

Granting privileges to Roles

PostgreSQL has a robust set of privileges built in, all of which are outlined in the documentation. For the following examples we’re going to focus on granting the CREATE privilege to the dev1 user in PostgreSQL 15.

-- As a superuser or role that can grant this 
-- privilege to others
GRANT CREATE ON SCHEMA public TO dev1;

Now that we’ve granted CREATE to dev1, we can attempt to create our table again in PostgreSQL 15. We could keep multiple sessions open (either in psql or your IDE of choice), but another option is to use SET ROLE. You can “switch” to another role if you are logged in as a superuser or that you are a member of. This is helpful for things like setting the correct object ownership at creation time and for testing permissions like we’re doing here.

-- temporarily set role in the current session to a different 
--role. Only superusers or members of the role can do this.
SET ROLE dev1;

-- Create the table as dev1 given the new permissions
CREATE TABLE user_social (
   user_id INT NOT NULL,
   twitter_handle TEXT NULL,
   facebook_handle TEXT NULL );

-- set the role back to the session initiated role
SET ROLE NONE;

Success! We’re a step closer to adding this new feature to our application.

Unfortunately, we quickly run into the another problem. To develop this feature, our developer needs to select data in the `user` table, but attempting to do so results in another error:

-- set our role back again if connected through 
-- another user session
SET ROLE dev1;

-- execute a select query against another table
SELECT * FROM “user” u
INNER JOIN user_social usoc USING(user_id);

This returns:

ERROR: permission denied for table user

As you probably guessed, the solution is to grant another privilege to the dev1 role. As a superuser or role that has the ability to grant these privileges:

-- In this example, grant SELECT on ALL tables in the schema. 
-- We could be more selective if needed
GRANT SELECT ON ALL TABLES IN SCHEMA public TO dev1;

If we know all the privileges that our developers need to do their work, we can add multiple privileges at one time. For example, if a developer needs to SELECT, INSERT, UPDATE, and DELETE data in tables of the public schema, we could do this in one statement.

GRANT SELECT, INSERT, UPDATE, DELETE 
     ON ALL TABLES IN SCHEMA public TO dev1;

Let’s be honest, though. Managing privileges one at a time for each role from database to database is going to be a maintenance headache. As soon as we create an account for the next developer on our team, dev2, we’ll have to start this entire process over.

Surely there’s a better way to manage this.

Granting Privileges Using Groups

PostgreSQL provides the ability to grant the privileges of one role to another role. Specifically, group roles (the ones that cannot login) are the perfect mechanism for applying sets of privileges to many users at once.

Earlier we created a group role called devgrp. It’s not allowed to log in and we haven’t granted it any privileges yet. We could instead grant this role the privileges we want to provide to all developers and then grant the devgrp role to each of them. Then any time we need to tweak developer privileges we only have to modify (GRANT or REVOKE) privileges from the devgrp role.

-- As a superuser or role that has the ability to grant 
-- this privilege to others
GRANT CREATE ON SCHEMA public TO devgrp;

GRANT SELECT, INSERT, UPDATE, DELETE 
            ON ALL TABLES IN SCHEMA public TO devgrp;

And now, any role that we grant membership to will inherit these permissions by default.

GRANT devgrp TO dev1;

At this point dev1 inherits all privileges that devgrp has. Any time a new developer joins the team and requires access to the database, we can create a role and grant them membership in the devgrp role. This can be done at any time using the GRANT statement above or during role creation time if the group role already exists.

-- This will create the role and automatically add it as 
-- a member of the devgrp role
CREATE ROLE dev2 WITH LOGIN PASSWORD ‘supersecretpw2’ 
                                            IN ROLE devgrp;

Conclusion

PostgreSQL has a comprehensive role and privilege system that allows a lot of flexibility for managing access to server objects and resources. In this article we learned about roles, how to use them effectively to manage users and groups, and how to grant some initial privileges to the new roles that we created.

We also discussed the importance of superuser roles and that most DBaaS services will not provide you with a superuser because it bypasses all privilege checks. Instead, the best practice is to create one or more administrative users with CREATEROLE and CREATEDB privileges for day-to-day administration. If you use a service like AWS or Azure, the administrative user they provide likely has these privileges rather than being a full superuser.

Once we had created new roles, we briefly discussed how to GRANT privileges to new roles individually and through inheritance so that our new roles could do the work needed to develop a new application feature.

In a follow-up article, we’ll dig deeper into object ownership and how it plays an important role (pun intended) in how you set up and maintain object ownership in your applications. Understanding how object ownership impacts the way that scripts are run, and backups are managed, will help you design secure applications that are easier to manage.

The post PostgreSQL Basics: Roles and Privileges appeared first on Simple Talk.



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