Thursday, April 20, 2023

One use case for NOT using schema prefixes

I’ve long been a huge advocate for always referencing objects with a schema prefix in SQL Server.

In spite of what may be a controversial title to many of my regular blog readers, I don’t really want you to stop that practice in most of your T-SQL code, because the schema prefix is important and useful most of the time. At Stack Overflow, though, there is a very specific pattern we use where not specifying the schema is beneficial.

Background

The Stack Exchange Network is comprised of many web sites with the same question & answer model, and you’ve almost certainly heard of “the big three” – Stack Overflow, Server Fault, and Super User (all with spaces!). There are many other sites, covering everything from cooking and physics to science fiction and woodworking.

The way the public network sites work is that each web site has a domain name and a connection string to an individual database. Every database is basically identical in structure – each site has a Posts table, a Users table, and all the usual suspects.[ * ]

How sites interact with tables in the Stack Exchange Network

Our Stack Overflow for Teams offering is a private version of the public network – you create your own team, and you get your own private Q & A web site, where you can share information within your organization or even just among your immediate teammates.

The database structure works slightly differently here; in most tiers, each team does not have its own database, but rather the security boundary is by schema, as explained in this security overview. There are multiple reasons for that, and they pre-date my tenure here. But certainly, as a reliability engineer, I do not want to have to manage thousands and thousands of databases, especially since even at 100 databases, we bump up into both enforced limits (e.g. Managed Instance) and practical limits (see our well-documented and oft-lamented performance problem around AG failovers).

But each team still has its own connection string. And each team’s schema still has a Posts table, a Users table, and all the usual suspects.[ * ]

How teams interact with tables in Stack Overflow for Teams

The structure is the same because large portions of the codebase are shared across all of the applications and services, and they issue all kinds of queries – often dynamically and conditionally constructed within Dapper or the bowels of C#. The problem is clear: we can’t obey the pattern of always specifying the schema without complicating every single query and injecting either dbo. in the case of public network or Schema00xxx. in the case of Teams. So the code is full of queries that simply don’t reference any schema at all, to make them the most portable and compatible with all flavors of the software:

SELECT {columns} FROM Posts WHERE ...

For Teams, we take advantage of the fact that the connection string for any site specifies a user that owns that single schema, uses it as their default, and can’t access any others. The potential trade-off there is something I mentioned in my earlier rant: every time a user from a different schema executes any specific version of a query, another entry is added to the plan cache (even though the query text and all other attributes are identical).

This isn’t a problem in the public network side because there are only dbo versions of the tables, and no app users or service accounts have anything else as their default schema. And it’s actually not the huge problem you might assume in Teams, either, because teams come in all shapes and sizes. It can actually be beneficial for each team to generate their own unique plan, with estimates based on their specific table cardinalities. But it is worth mentioning because it can come as a surprise.

Other Challenges

This solution is not without its challenges aside from “plan cache stuff.”

  • Balance: It takes time and experimentation to balance the right number of schemas across the right number of databases. If you have to create a million tenants, what’s best? Ten databases with 100,000 schemas each? 100,000 databases with 10 schemas each? Somewhere in the middle? Considerations include how many are supported (I mentioned the 100-database limits above) and, even where there is no explicit limit, there are other questions like, “how long am I willing to wait for Object Explorer to render 10,000 schemas?” And how many backups are you taking vs. how big are your backups vs. how long does it take you to recover a single tenant (or many tenants). We started with 10,000 schemas per database, and have since adjusted that to 1,000.
  • Server-level logins: If your SQL Server is domain-joined, you will find there is a practical upper bound where creating the next login (even a SQL Authentication login!) will take longer and longer and, eventually, will effectively grind to a halt. One adjustment we made – which had zero impact on the behavior of the application, APIs, or supporting services – is to switch from matching server-level logins and database-level users to just a single set of contained database users. As the documentation suggests, this also makes it easier to move a database with a noisy neighbor to a different server, though we haven’t done that yet.
  • Muscle memory: It has been very hard to get into the habit of not doing something I’ve been training myself to always do for about two decades now, and have been influencing others to always do through writing, speaking, peer review, and answers. I have submitted several PRs that were very quickly rejected because an errant dbo. snuck in there out of habit.

Conclusion

This solution works great for our specific use case because the application codebase is very large and managing at the schema level is the lesser of several possible evils. In a multi-tenant solution, you will always have trade-offs – not just between performance and management overhead, but also between where performance is most important and where management overhead hurts the most.

For Stack Overflow, I’m convinced we’ve made the right compromise, and happy that the architecture is built in such a way that we can easily tweak configuration like “number of schemas per database.”

This is not to suggest, necessarily, that you should use this model in your environment. There are many other factors involved, including where you want more or less complexity, and how you want to scale tenancy. Those criteria are much more important than whether you are following or ignoring what some old-timer rants about in his blog posts and presentations, and I just thought it would be useful to have a counter-example where I admit that almost every rule has justifiable exceptions.

* Further Reading

To learn more about the Stack Overflow schema, and the tables I lump into “the usual suspects,” see Erik Darling’s gentle introduction. If you’re a more hands-on person, you can snoop around a rough subset of the schema in the Stack Exchange Data Explorer, or download the data dump from archive.org.

The post One use case for NOT using schema prefixes appeared first on Simple Talk.



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

Monday, April 17, 2023

Is Artificial Intelligence another way to spread misinformation?

I use Chat-GPT occasionally, instead of Google, to get answers to technical questions. The trouble is that it currently uses authoritative sources with the same eagerness as blog posts written by newly-trained wannabe database devs who seek to get their names known, and I have to keep pointing out errors: ‘No, you can’t run JDBC from PowerShell that way’, ‘Github doesn’t support that way of accessing its REST API’ and so on. When noted, it does express remorse and is fulsome in its apologies. however, I regard Chat-GPT as an indiscriminate conveyor of existing information, not artificial intelligence.

To work quickly, I need information that is correct.

I am intrigued, however. One of my hobbies has been in using a computer to generate what we used to call Gobbledygook; wordy and generally unintelligible jargon based on someone else’s work. Now Computer Science does this for you. Unless you are wary, you can mistake this for intelligence: it isn’t. It is, rather, a mashup of other sources of knowledge and insight, providing plagiarism on an industrial scale. To rephrase someone else’s intellectual property uncredited, as if it were your own, isn’t intelligence but merely theft. To make it worse Chat-GPT cannot, in its present state, distinguish bad data.

Psychologists who are assessing neurological problems have a colloquial term for this, ‘Cocktail-party Syndrome’, where a person whose mental faculties aren’t up to demand will produce very plausible sentences that seem to reflect an intelligent and ordered mind. The brain can, almost effortlessly, pull in trains of thought and reconfigure them into a plausible ‘Word Salad’. It is a good technique, much used by ‘content-providers’, conspiracy theorists, and managers. Never mind the quality, feel the width. It is easy to bluff the listener into believing that there is deep thought behind the blather. No. it is an artificial language model for which we have few natural defenses. Even I found myself apologising when I pointed out Chat GPT’s errors.

Chat GPT is currently like the keen schoolchild in the front of the class who is eager to answer every question with uncrushable confidence, but rather shaky knowledge. Some of the proudest and most valuable signs of real human intelligence is to realise and admit when you have no knowledge or expertise in a topic, because there is nothing more damaging than transmitting incorrect information.

There was once a culture where what appeared in print was edited and checked. It was published by an organisation that was obliged to stand by what they published. Now we have insufficient attribution to give us confidence that information comes from a reliable source, has been tested against reality, and peer reviewed. At this point, any database developer will get a nagging doubt. Is this a possible vector for bad data, a strain of the worst ailment that can ever overtake a data system? We’re all ill-equipped to judge information that is presented slickly with apparent confidence. That’s how wars start.

The post Is Artificial Intelligence another way to spread misinformation? appeared first on Simple Talk.



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

Thursday, April 13, 2023

How to secure legacy ASP.NET MVC against Cross-Site (CSRF) Attacks

Cross-Site Request Forgery (CSRF) attacks are widespread, and even some BigTech companies suffer from them.

  • Netflix suffered in 2006 with CSRF vulnerabilities. Attackers could change login credentials, change the shipping address and send DVDs to a newly set address.
  • YouTube suffered from CSRF attacks where an attacker could perform actions of any user
  • ING Direct Banking has lost money to CSRF attackers who used their web application to do illicit money transfers
  • McAfee Secure’s vulnerability allowed attackers to change their company system.

How were the attackers able to do this? What were some of the techniques they used? To understand this, we need to understand CSRF in detail.

What is a Cross-Site Request Forgery (CSRF) attack?

CSRF is when an attacker submits unauthorized commands to a website user already logged in. In layman’s terms, When you click on a malicious hyperlink, it triggers scripts that perform actions on your behalf to your logged-in bank website. Viola, the attackers, have your money.

The malicious link would look like these.

  • “You are a winner.”
  • “You placed order # 648722.”

Why are CSRF vulnerabilities a must-fix in the ASP.NET MVC world?

ASP.NET MVC and ASP.NET Core are traditionally some of the most used platforms to build financial web applications, such as banks and hedge funds. From a statistical standpoint, these platforms are trusted more than their counterparts, such as Express or NodeJS, for financial web applications. In addition, it is easier to fix CSRF issues in ASP.NET Core than in ASP.NET MVC because of the better tools and support available. We will investigate techniques to fix CSRF issues in ASP.NET MVC.

How to attack an ASP.NET MVC website using a CSRF attack vector

Before we understand how to fix CSRF issues, we need to know how they happen in the first place. For example, suppose you log into your bank website at onlinebank.com. And you are visiting a malicious website on another tab, which looks like this. (This is an actual screenshot of a spam email I received.).

The “Get Started” button could be hiding a script and Html form like this.

<h1>Affordable Medicare Plans are available. Hurry now!</h1>
<form action="http://onlinebank.com/transfer?account=76543865&amount=15000" method="post">
  <input type="submit" value="Get Started"/>
</form>

When you click the “Get Started” button, you can see the network traffic originating from it using the developer console built into your browser by pressing the F12 key on most any browser (Developer console is essential for web development and almost any engineers who work on front end browser code should know about it.(

If you are already logged into the onlinebank.com website, this traffic would include the session cookies. Now the attacker has all the pieces needed to solve the puzzle:

  1. a logged-in user
  2. users’ session cookies
  3. a URL that steals the victims’ money.

No wonder CSRF attacks are also called session-riding and one-click attacks.

There are other ways the attack can also happen, using img tags.

Now that we have seen how the attack can happen let’s discuss our prevention strategies.

Enter Anti-Forgery Tokens. Drum roll, please 🥁🥁🥁!

The suggested way to prevent CSRF attacks is to use tokens that you would only know. Your ASP.NET MVC web app generates the tokens, and we verify these tokens on relevant requests to the server. Since GET requests are not supposed to alter the persisted information, it is ideal to use and verify this token on POST, PUT, PATCH, and DELETE requests.

Let’s outline the steps needed.

  • User visits a page
  • On page request, ASP.NET MVC generates two tokens. A cookie token and a hidden form field token. The server embeds both tokens in response.
  • When the user does an action that alters data, such as a form submission, the request should contain both of these tokens.
  • Server verifies if the action request has both tokens; if not, the server says ‘no’ to the request.

In short, think of this as accessing a bank locker, but you can only do it in the presence of a bank manager(anti-forgery tokens) sent by the bank(server) even though you have the key to the locker(session cookie).

Enough talk, Show me the code for ASP.NET MVC.

You would add `@Html.AntiForgeryToken()` to your Html forms.

@using (Html.BeginForm("Transfer", "Account", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    <input type="submit" value="Submit Form" /></td>
}

It would translate to:

<form action="Account/Transfer" method="post">
  <input name="__RequestVerificationToken" type="hidden" value="CfDJles20ilG0VXAiNm3Fl5Lyu_JGpQDA......"/>    
  <input type="submit" value="Submit Form" />
</form>

As you can see, ASP.NET MVC has added `__RequestVerificationToken` to this form token as a hidden field. This token is generated at the server.

Now, when this form is submitted, this form token will be submitted along with form data, and the cookie token will make it to the server as part of the request as well.

Now we have only one job left; verify both tokens at the server.

To do that, a method like `AntiForgery.Validate(cookieToken, formToken); ` will do the job. But for ASP.NET MVC, there is a built-in attribute that would do this job for you – `ValidateAntiForgeryToken`.

using System.Web.Mvc;
namespace Online.Bank.App.Controllers
{
    public class AccountController : Controller
    {
        [HttpPost]
        [ValidateAntiForgeryToken] // This attribute will do the Anti-Forgery token validation for you.
        public ActionResult Transfer()
        {
            return Json(true); // This line is added for brevity. You would be doing good stuff here.
        }
    }
}

What about AJAX and jQuery?

AJAX primarily uses JSON data instead of HTML form data. It poses a problem for us. The above code won’t work. How do we solve this?

Let’s assume we need to call an endpoint Account/Manage using AJAX.

As the first step, using razor syntax, we can ask the server to generate the tokens and give them to us like this.

<script>
    @functions{
        public string GetAntiForgeryTokens()
        {
            string cookieToken, formToken;
            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            return cookieToken + ":" + formToken;
        }
    }
</script>

And then send the tokens to the server using AJAX.

<input type="button" onclick="manageAccount()" value="Manage Account" />
<script>
    function manageAccount() {
        $.ajax("<baseurl>/Account/Manage", {
            type: "post",
            contentType: "application/json",
            data: {  }, // JSON data
            dataType: "json",
            headers: {
                '__RequestVerificationToken': '@GetAntiForgeryTokens()'
            },
            success: function (data) {
                console.log(`Account updated: ${data}`);
            }
        });
    }
</script>

Finally, verify these tokens on the server side. The `Manage` action would be similar to this.

using System;
using System.Linq;
using System.Web.Helpers;
using System.Web.Mvc;
namespace Online.Bank.App.Controllers
{
    public class AccountController : Controller
    {
        [HttpPost]
        public ActionResult Manage()
        {
            string cookieToken = "";
            string formToken = "";
            var tokenHeaders = Request.Headers.GetValues("__RequestVerificationToken");
            string[] tokens = tokenHeaders?.First()?.Split(':');
            if (tokens.Length == 2)
            {
                cookieToken = tokens[0].Trim();
                formToken = tokens[1].Trim();
            }
            try
            {
                AntiForgery.Validate(cookieToken, formToken);
            }
            catch (Exception ex)
            {
                // Alert folks that someone is trying to attack this method.
            }
            return Json(true); // This line is added for brevity. You would be doing good stuff here.
        }
    }
}

That’s it. Now our Account/Manage endpoint is protected.

But do you see a problem? Do we have to repeat this in every action method? How to avoid that?

Custom Anti-Forgery Attribute to the rescue!

What if we create a custom ASP.NET MVC attribute with the above code? Then we can decorate action methods or controllers with that attribute, right?

using System;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
namespace Online.Bank.App.Attributes
{
  [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
  public sealed class ValidateHeaderAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
  {
    // Bonus method
    private void TellEveryoneWeBlockedAttacker(HttpContextBase httpContext, Exception ex)
    {
      string controllerName = httpContext?.Request?.RequestContext?.RouteData?.Values["controller"]?.ToString();
      string actionName = httpContext?.Request?.RequestContext?.RouteData?.Values["action"]?.ToString();
      ex.Data.Add("ControllerName", controllerName);
      ex.Data.Add("ActionName", actionName);
      // Use the exception we created to notify the logging or error reporting system.
      // You may alternatively send an email message or slack message here.
    }
    public void OnAuthorization(AuthorizationContext filterContext)
    {
      if (filterContext == null)
      {
        throw new ArgumentNullException("filterContext");
      }
      var httpContext = filterContext.HttpContext;
      var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName];
      try
      {
        AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request.Headers["__RequestVerificationToken"]);
      }
      catch (Exception ex)
      {
        TellEveryoneWeBlockedAttacker(httpContext, ex);
      }
    }
  }
}

And decorate the action method with the ValidateHeaderAntiForgeryToken attribute.

using System.Web.Mvc;
using Online.Bank.App.Attributes;
namespace Online.Bank.App.Controllers
{
    public class AccountController : Controller
    {
        [HttpPost]
        [ValidateHeaderAntiForgeryToken] // This is where we put the Anti-Forgery attribute we just created
        public ActionResult Manage()
        {
            return Json(true); // This line is added for brevity. You would be doing good stuff here.
        }
    }
}

See how clean the code got. Now we can use this attribute across the entire ASP.NET MVC web application to decorate action methods and controllers. The beauty of attributes, isn’t it.

Can we optimize the client-side code as well?

ASP.NET MVC generally has a _Layout.cshtml file. We can get the Anti-Forgery tokens there using JavaScript and @Html.AntiForgeryToken(). Though _Layout.cshtml would be the ideal spot, it can be done anywhere in your razor files.

<script>
        function getAntiForgeryToken() {
          let token = '@Html.AntiForgeryToken()';
          token = $(token).val();
      return token;
        }
</script>
Usage
<input type="button" onclick="manageAccount()" value="Manage Account" />
<script>
    function manageAccount() {
        $.ajax("<baseurl>/Account/Manage", {
            type: "post",
            contentType: "application/json",
            data: {  }, // JSON data
            dataType: "json",
            headers: {
                '__RequestVerificationToken': getAntiForgeryToken()
            },
            success: function (data) {
                alert(`Account Updated: ${data}`);
            }
        });
    }
</script>

That’s good. What if we have a lot of AJAX calls, and we want the Anti-Forgery token to be present in every request?

You can set up jQuery requests to have the tokens added to the request header by default using $.ajaxSetup().

Usage is like this.

$.ajaxSetup({
    headers: {
      '__RequestVerificationToken': getAntiForgeryToken()
    }
});

That’s it. We made the life of the attacker a bit more complicated. Isn’t that a good thing?

Wrap up

Cross-Site Request Forgery (CSRF) vulnerabilities are not easily detectable without security scans. Implementing a technique presented here (or any technique for that matter) would save numerous heads, pain, and suffering. When it comes to application performance, reactive will do just fine. But in application security, proactive is always better than reactive! CSRF is just one attack vector; there are others like XSS, SQL Injections, and many others. More on that later! In the meantime, feel free to check out this example project demonstrating the code and concepts described above.

The post How to secure legacy ASP.NET MVC against Cross-Site (CSRF) Attacks appeared first on Simple Talk.



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

Monday, April 10, 2023

PostgreSQL Schema: Learning PostgreSQL with Grant

An important aspect of building and managing a database is organizing the objects within your database. You may have tables that support different functions, for example, a schema for warehousing operations and another for sales. Some logins may need access to some tables, but not others. You might want to isolate one set of objects within a database from other sets of objects. All of this, and more, can be accomplished using schemas within a database and PostgreSQL supports the use of schema for just these types of functions.

In the sample database I’ve created as a part of this ongoing series, I created a couple of schemas and organized my tables within them. You can see the database here in the CreateDatabase.sql script. The rest of the code in this article is in the folder 08_Schema.

Managing Schema

A schema is used first and foremost as an organizing mechanism on your database. From there, you can get into using schema to help design security, manage access, and generally control what users can see and do within your database. When you create a blank database, it comes with a default schema, public.

When you create an object, like a table, it will automatically go into your default schema unless you specify otherwise. By default, all logins to the database have access to the public schema (PostgreSQL 15 has changed this default, so now users do not have rights to create objects in the public schema). Other than these default behaviors, the public schema is just another schema in the database and most of the functions and rules we’ll discuss in the rest of the article apply.

To get stated creating your own schemas, the syntax is very straightforward:

CREATE SCHEMA mytestschema;

This creates a schema called mytestschema. To create a table within that schema, you simply use a two part name (schema_name.table_name) for the table within the CREATE TABLE command like this:

create table mytestschema.testtable
(id int,
somevalue varchar(50));

It’s the same with any queries too:

select id from mytestschema.testtable;

You can think of the schema as the owner of the table (the owner of the schema is technically the owner of the table). Defining the owner in all your code helps ensure that accidents don’t happen. Because, when you start using schema, you can define the same object names if they’re in different schemas. Keeping object names distinct is a good practice, but sometimes the same name is the best name in different schemas):

create schema secondschema;

create table secondschema.testtable
(insertdate date,
someothervalue varchar(20));

This is perfectly valid. If I were to write, what I consider poor code, like this:

select * from testtable;

This likely results in the following error:

ERROR: relation "testtable" does not exist

LINE 2: select * from testtable;

Initially, is seems like it’s an error because PostgreSQL can’t figure out which of the two testtable tables to pull from. Rather, it’s because logins have a default schema. When I run a query like the one immediately preceding, without a schema identifying where the table lives, PostgreSQL looks in my default search path. If it’s not there, well, that table doesn’t exist. This is true even though, I’ve got two with that name. PostgreSQL doesn’t check other schemas “just in case.”

Later in the article, I will discuss how to manage the schema defaults.

If the schema is empty, you can drop it:

drop table if exists secondschema.testtable;

drop schema if exists secondschema;

If I do not drop the table first, an error will occur:

SQL Error [2BP01]: ERROR: cannot drop schema mytestschema because other objects depend on it

Detail: table mytestschema.testtable depends on schema mytestschema

Hint: Use DROP ... CASCADE to drop the dependent objects too.

In the error message, there is a hint for how to get around this. I could rewrite my query like this:

drop schema if exists mytestschema cascade;

The beauty of this is that it will remove all tables, views, etc., within the given schema. That is also the horror of this syntax, that it’s going to remove all the tables, views, etc., without consulting with you in any way.

There is a default schema in every database that gets created, public. However, it is just the default and like most defaults, it can be changed. In fact, you can even drop the public schema if you so choose. I started this section detailing how to create your own schema because, I think it’s a good practice to organize your data storage into a defined schema that you directly control, as opposed to just accepting the defaults.

Controlling the Default Search Path

In addition to helping you organize your database objects; schema helps you control access to those objects. I haven’t delved into security yet in this series, and it’s likely a little way off still. However, I will talk some about how schema helps you manage security on your database. (My teammate Ryan Booz did recently publish an article on the subject, “PostgreSQL Basics: Roles and Privileges”.)

In this section I want to detail some of the ways you can manage the default schema.

In the last example of the section above, I showed how you can have duplicate table names between schema, but, that you must reference the schema name to access those tables. However, this isn’t the whole story.

There’s actually a defined search list for schema that you can see using this query:

show search_path;

If you haven’t changed anything in your server, the default results are:

"$user",public

Each user has a schema of their own, like SQL Server. That’s the $user schema you see above. However, if you don’t specify the schema, it’ll default to the first one in the search list, public in this case. We can add schema to the search list for the current connection:

SET search_path TO radio,public;

That will not only add the radio schema to the the search_path, it will rearrange the order on the search_path so that the radio schema is searched before the public schema. If you disconnect and come back to the connection, you will have to reset the path when using the SET command.

If you want to make the changes to the path the default, you can use the ALTER ROLE to set any role to have a specific search path. For example:

ALTER ROLE scaryDba SET search_path = 'radio,public,$user';

If you want to set the default for the server\cluster\database, you can modify the search_path in the postgressql.cnf file, or you can use:

ALTER ROLE ALL SET search_path = '$user';

This will not override the individual path’s set but will make every login that does not override the search path need to specify the schema name with referencing any object. (Which as noted, is a best practice.)

Ownership and Basic Privileges

When you create a schema, you can define a schema owner as other than the login that is running the command:

CREATE SCHEMA secureschema AUTHORIZATION radio_admin;

A schema I haven’t created yet, secureschema, would be created with the owner being the radio_admin login role (also not yet defined because I am not digging into security yet). That will ensure that only that the radio_admin login, and any accounts defined as superuser, of course, can work within that schema.

You can also control behaviors on schema. For example, since I have set up independent schema in this database and intend to use it in that manner, I can revoke access for all logins to create objects on the public schema (This is only necessary in Postgres 14 and earlier, in 15 create is not granted by default.):

REVOKE CREATE ON SCHEMA public FROM PUBLIC;

This is using two different meanings of the word “public”. In the first, ‘public’, we’re referring to the schema of that name. In the second, ‘PUBLIC’, we’re talking about the role that contains all users within the database. This is a shorthand mechanism to make sure no one accidentally puts things into the public schema. I’d say it’s a good practice to follow if you’re going to use other schemas, especially if you’re using them to help properly secure your database.

You can grant various privileges between schema and users such that a given user can read data from tables within a schema, but not modify the data contained in the tables (read only access). In this way, you can combine multiple types of data within one database but isolate them from each other as needed. This is a principal reason for using schema in your database.

If you’re not isolating storage and access between schema, it may make less sense to use a schema other than public in the first place. However, most applications have varying levels of access they would like to manage, and schema will lend themselves to appropriately implementing that type of security. If security isn’t a concern, using schema names instead of putting all objects in the public schema can be advantageous for documentation as well.

Conclusion

Schemas are containers that allow you to segment objects and security at a lower level than a database. Using schemas other than public has good benefits. In PostgreSQL there are several methods of setting the default schema if your users are averse to using two-part names.

If you are familiar with schemas from SQL Server, the core functionality of schema is roughly the same as in SQL Server. However, there is added functionality like the ability to control a search list changes the types of behaviors you can control within PostgreSQL.

 

The post PostgreSQL Schema: Learning PostgreSQL with Grant appeared first on Simple Talk.



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

A Beginners Guide To MySQL Replication Part 2: Configuring Source and Replica Servers

A Beginners Guide To MySQL Replication Part 2: Configuring Source and Replica Servers

In the first part of this series, we spoke about MySQL Replication, the different types, replication formats, benefits, and downsides, as well as a brief introduction to the requirements needed for setting up MySQL Replication. To ensure we stay on track with our intended topic, it’s important to have certain prerequisites in place before we begin. While I won’t be able to provide an in-depth explanation, I recommend conducting research and preparing these environments beforehand.

1. Setup two computers, ideally virtual machines, one for the source server, and the other for the replica server.

2. Install MySQL server software on the virtual machines and make sure they are both running the same version of the operating system and MySQL software.

3. Ensure there is a network connectivity available. This is to help the source and replica servers communicate with each other.

Once these three prerequisites are set, then we can finally dive into setting up our replication servers.

Configure the source server

We would be configuring our source server using the binary log file position based replication. This is essential for the replica servers to receive updates to the database, if binary logging isn’t setup, replication becomes unfeasible. In order to set up binary logging in MySQL replication, we need to modify the MySQL configuration file (my.cnf or my.ini) on the source server to enable binary logging. Here’s what we need to do:

  • Locate the MySQL configuration file: The location of the configuration file varies depending on the operating system you’re using. On Linux systems, it is typically located in /etc/my.cnf or /etc/mysql/my.cnf. On Windows systems, it is typically located in the MySQL installation directory under the subdirectory named “my.ini”.
  • Modify the ini file: Add the following lines to the [mysqld] section of the configuration file:
server-id=1

log-bin=mysql-bin

To identify servers within a replication topology, a server ID is assigned. MySQL 8.0 assigns a default server-id value of 1, however this value can be changed dynamically and must be a positive integer ranging from 1 to (232)−1. You can modify the server-id value easily using the following query:

SET GLOBAL server_id = your-prefered-integer-value;

In this article, I will be using the default server-id value of 1. The `server-id` value should be unique for each server in the replication setup. Also, the `log-bin` value sets the name of the binary log file that will be created on the source server. According to the official documentation, it is important to note that the following has an effect on the source:

To achieve the highest level of durability and consistency in a replication configuration that uses InnoDB with transactions, it is recommended to set the following values in the source’s my.cnf file:

innodb_flush_log_at_trx_commit=1

And:

sync_binlog=1

Verify that the skip_networking system variable is disabled on the source. If this variable is enabled, communication between the replica and the source will be impossible, resulting in a replication failure.

For the changes to take effect, restart the MySQL service.

Configure the replication server

Remember that in order for our replication to work, each server must have a unique server-id value. For example, if you have two servers, one source(or primary) and one replica, you can set `server-id` to 1 on the source and 2 on the replica. It is worthy to note that each replica server must be configured with a unique server-id that is greater than the source’s server-id to which it is connected to. It is possible to also have multiple replica servers, this isn’t a problem as long as you choose a server-id value that does not conflict with existing replicas.

  • Stop the MySQL service on the replica server.
  • Create a backup of the MySQL data directory (my.ini) on the replica server. This is to ensure that you can recover the database if something goes wrong during the replication process.
  • Edit the MySQL configuration file (my.cnf or my.ini) to enable replication and set a unique server-id. This can be done by adding the following lines to the configuration file:
[mysqld]
server-id= unique_integer_value

Or by using the MySQL command:

SET GLOBAL server_id=unique_integer_value;

Make sure that the `unique_integer_value` is a unique integer that is different from the server ID of the master server and any other slave servers.

  • Start the MySQL service on the replica server.

Create a MySQL user with replication privileges on the replica server

To establish a connection between the source and its replicas, each replica requires a unique MySQL username and password. Hence, it is necessary to create a corresponding user account on the source. You can create a new user account by employing the CREATE USER command.

CREATE USER 'replication_user'@'localhost' 
                     IDENTIFIED BY 'password';

Replace `replication_user` with the desired username and `password` with the desired (far stronger) password for the new user.

Additionally, to authorize this account for replication purposes, use the GRANT statement to confer the requisite privileges.

GRANT REPLICATION SLAVE ON *.* TO 'replication_user'@'%'

Note that in this example, the privilege is granted to a user named `replication_user` from any host (represented by `%`)

Get Binary Log Coordinates

In order for the replica to start the replication process at the accurate time, it is important to get the source’s current coordinates within its binary log. This is to ensure that the source server’s data is synchronized with the replication servers. To do this, set the ‘Flush tables’ option with a read lock and stop executing any commands on the source server.

mysql> FLUSH TABLES WITH READ LOCK;

Note: If you intend to export data without locking your tables, please skip this step.

To determine the current binary log file name and position, use the SHOW MASTER STATUS statement on a separate session of the source.

mysql> SHOW MASTER STATUS

Then, record the current binary log coordinates (file name) for the source server and position, as they will be necessary when configuring the replication settings later.

Create snapshots of existing data in the source server

We are going to copy the existing data from the source server into the replica server. This can be easily done using the mysqldump tool, which is used to create a dump of all the databases we want to replicate. It is the most preferred method when using the InnoDB

mysqldump --all-databases --master-data > dbdump.db

This dumps all databases to a file named dbdump, and locks the table which might result to a downtime. To avoid this, you can use this command like this:

mysqldump --skip-lock-tables --single-transaction --flush-logs 
--hex-blob --master-data=2 -A -uroot -p > C:\dump.sql

The –master-data statement starts the replication process on the replica server. If you do not want to start the replication process yet, then start the replica with `--skip-slave-start`

Use the `CHANGE MASTER TO` statement to configure the replica.

This statement helps us configure the replica in order to connect to the source server by specifying some information. It includes information such as the source server’s hostname or IP address, the replication username and password, and the binary log file and position from which replication should start.

For example, the `CHANGE MASTER TO` statement might look like this:

CHANGE MASTER TO
      MASTER_HOST='master_hostname',
      MASTER_USER='replication_user',
      MASTER_PASSWORD='password',
      MASTER_LOG_FILE='mysql-bin.000001',
      MASTER_LOG_POS=12345;

Make sure to replace `master_hostname`, `replication_user`, `password`, `mysql-bin.000001`, and `12345` with the appropriate values for your setup.

Lastly, start the replication process by executing the `START SLAVE` statement on the slave server.

mysql> START SLAVE;

Test MySQL Replication

You can test that your MySQL replication is working by executing the following steps:

1. Login to the MySQL on your source server, create a database and insert some data into a table.

mysql -u root -p

Then:

mysql> CREATE DATABASE testdb;

Exit from the source server using the EXIT statement:

mysql> EXIT;

2. Login to the replica server and verify the the replication status using the following command:

mysql> SHOW SLAVE STATUS\G

Look for the `Slave_IO_Running` and `Slave_SQL_Running` fields in the output to ensure that replication is running without errors.

3. Check for all existing databases in the replica server using the following statement:

mysql> SHOW DATABASES;

The newly created testdb should have been replicated and exists on the replica server. If the data is not replicated, check the replication status on the slave server for any error messages or warnings.

Yayy! You just learnt how to replicate servers using MySQL Replication techniques.

 

The post A Beginners Guide To MySQL Replication Part 2: Configuring Source and Replica Servers appeared first on Simple Talk.



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

Friday, April 7, 2023

Ordered Columnstore Indexes in SQL Server 2022

One of the more challenging technical details of columnstore indexes that regularly gets attention is the need for data to be ordered to allow for segment elimination. In a non-clustered columnstore index, data order is automatically applied based on the order of the underlying rowstore data. In a clustered columnstore index, though, data order is not enforced by any SQL Server process. This leaves managing data order to us, which may or may not be an easy task.

To assist with this challenge, SQL Server 2022 has added the ability to specify an ORDER clause when creating or rebuilding an index. This feature allows data to be automatically sorted by SQL Server as part of those insert or rebuild processes. This article dives into this feature, exploring both its usage and its limitations.

Speedy Review of Data Order

To fully appreciate the impact of data order on a columnstore index, a quick demo will be presented to show its impact on segment elimination and the resulting effect on performance.

The following T-SQL creates a table with a columnstore index and inserts ~7.1 million rows into it (this script uses the WideWorldImportersDW database. You can download this database here):

CREATE TABLE dbo.fact_order_BIG_CCI (
     [Order Key] [bigint] NOT NULL,
     [City Key] [int] NOT NULL,
     [Customer Key] [int] NOT NULL,
     [Stock Item Key] [int] NOT NULL,
     [Order Date Key] [date] NOT NULL,
     [Picked Date Key] [date] NULL,
     [Salesperson Key] [int] NOT NULL,
     [Picker Key] [int] NULL,
     [WWI Order ID] [int] NOT NULL,
     [WWI Backorder ID] [int] NULL,
     [Description] [nvarchar](100) NOT NULL,
     [Package] [nvarchar](50) NOT NULL,
     [Quantity] [int] NOT NULL,
     [Unit Price] [decimal](18, 2) NOT NULL,
     [Tax Rate] [decimal](18, 3) NOT NULL,
     [Total Excluding Tax] [decimal](18, 2) NOT NULL,
     [Tax Amount] [decimal](18, 2) NOT NULL,
     [Total Including Tax] [decimal](18, 2) NOT NULL,
     [Lineage Key] [int] NOT NULL);

-- Generate 7,173,772 rows in a heap
INSERT INTO dbo.fact_order_BIG_CCI
SELECT
     [Order Key] + (250000 * ([Day Number] + 
             ([Calendar Month Number] * 31))) AS [Order Key]
    ,[City Key]
    ,[Customer Key]
    ,[Stock Item Key]
    ,[Order Date Key]
    ,[Picked Date Key]
    ,[Salesperson Key]
    ,[Picker Key]
    ,[WWI Order ID]
    ,[WWI Backorder ID]
    ,[Description]
    ,[Package]
    ,[Quantity]
    ,[Unit Price]
    ,[Tax Rate]
    ,[Total Excluding Tax]
    ,[Tax Amount]
    ,[Total Including Tax]
    ,[Lineage Key]
FROM Fact.[Order]
CROSS JOIN
Dimension.Date
WHERE Date.Date <= '2013-01-31';

-- Create a columnstore index on the table.
CREATE CLUSTERED COLUMNSTORE INDEX CCI_fact_order_BIG_CCI 
                                         ON dbo.fact_order_BIG_CCI;

No optimizations are made or consideration taken regarding data order. It’s a columnstore index sitting on top of a pile of data as-is. An assumption will be made here that this data will be searched most frequently based on date. If so, the ideal data order would be by the Order Date Key column. To verify the order of rows with respect to Order Date Key, the following query can be used to show the minimum and maximum values for that column within each rowgroup:

SELECT
     tables.name AS table_name,
     indexes.name AS index_name,
     columns.name AS column_name,
     partitions.partition_number,
     column_store_segments.segment_id,
     column_store_segments.min_data_id,
     column_store_segments.max_data_id,
     column_store_segments.row_count
FROM sys.column_store_segments
INNER JOIN sys.partitions
ON column_store_segments.hobt_id = partitions.hobt_id
INNER JOIN sys.indexes
ON indexes.index_id = partitions.index_id
AND indexes.object_id = partitions.object_id
INNER JOIN sys.tables
ON tables.object_id = indexes.object_id
INNER JOIN sys.columns
ON tables.object_id = columns.object_id
AND column_store_segments.column_id = columns.column_id
WHERE tables.name = 'fact_order_BIG_CCI'
AND columns.name = 'Order Date Key'
ORDER BY tables.name, columns.name, column_store_segments.segment_id;

The results are as follows (Your results should be similar, but likely differ a little bit, this is normal. In some executions I had an additional partition created):

Each row is a single rowgroup within the columnstore index. Note that for each rowgroup, the min_data_id and max_data_id are the same. This indicates that the data is unordered, and the same set of disparate values is scattered across all rowgroups. The effect of this can be illustrated by running a simple analytic query.:

SET STATISTICS IO ON; --Output the IO that was needed to execute the query

SELECT SUM([Total Excluding Tax]) AS [Total Excluding Tax]
FROM dbo.fact_order_BIG_CCI
WHERE [Order Date Key] = '2014-12-04';

This query returns a sum for only a single date value. When executed, the output of statistics IO shows the following:

Table 'fact_order_BIG_CCI'. Scan count 1, logical reads 0, physical reads 0, page server reads 0, read-ahead reads 0, page server read-ahead reads 0, lob logical reads 1540, lob physical reads 0, lob page server reads 0, lob read-ahead reads 0, lob page server read-ahead reads 0.

Table 'fact_order_BIG_CCI'. Segment reads 8, segment skipped 0.

Note that 8 segments were read and 0 were skipped. This indicates that data had to be read from all rowgroups in order to return information for a single date. The reads (1547) are suspiciously high for such a simple query as well.

The next step for this demonstration is to order this data and rerun the above queries again.

To do this, the columnstore index will be swapped out for a clustered rowstore index that is ordered by Order Date Key. The clustered rowstore index will then be swapped for a clustered columnstore index. MAXDOP of 1 ensures that parallelism does not inadvertently result in unordered data via multiple streams of ordered data being shuffled together into new rowgroups: (The clustered index I create first orders the data in the object before we create the clustered columnstore index.)

CREATE CLUSTERED INDEX CCI_fact_order_BIG_CCI 
       ON dbo.fact_order_BIG_CCI ([Order Date Key]) WITH (DROP_EXISTING = ON);

CREATE CLUSTERED COLUMNSTORE INDEX CCI_fact_order_BIG_CCI 
       ON dbo.fact_order_BIG_CCI WITH (DROP_EXISTING = ON, MAXDOP = 1);

Rerunning the rowgroup metadata query from earlier returns the following:

The minimum and maximum values for Order Date key are now nicely ordered from smallest to largest values. Running the simple analytic query from earlier produces the following statistics IO output:

Table 'fact_order_BIG_CCI'. Scan count 1, logical reads 0, physical reads 0, page server reads 0, read-ahead reads 0, page server read-ahead reads 0, lob logical reads 388, lob physical reads 0, lob page server reads 0, lob read-ahead reads 836, lob page server read-ahead reads 0.

Table 'fact_order_BIG_CCI'. Segment reads 1, segment skipped 6.

Only 1 segment was read whereas 6 were skipped. Note that the logical IO is significantly less than before, by about a factor of 10!

Filtering a large OLAP data set on ordered columnstore data will be significantly faster and more efficient than unordered data. But how is data ordered normally over the life span of a table? The most common solution is to:

  1. Structure an analytic table to only accept insert and delete operations
  2. Avoid updates at all costs.
  3. Insert new data at the end of the table for the most recent date dimension.

Alternatively, if a large table needs to be converted to a columnstore index, then trickery as demonstrated above is necessary, ordering with a rowstore index and then swapping in a columnstore index on top of the newly ordered table.

Introducing: Ordered Columnstore Indexes!

SQL Server 2022 adds the ORDER clause to the clustered columnstore index creation syntax. This column list specifies which columns to sort columnstore data by as part of the rebuild operation or as part of an INSERT operation.

To alter our existing columnstore index to use this feature, the following syntax can be used:

CREATE CLUSTERED COLUMNSTORE INDEX CCI_fact_order_BIG_CCI ON dbo.fact_order_BIG_CCI
ORDER ([Order Date Key])
 WITH (DROP_EXISTING = ON, MAXDOP = 1);

The result of this change formalizes the order of the columnstore index to default to using Order Date Key. When the ORDER keyword is included in a columnstore index create statement, SQL Server will sort the data in TempDB based on the column(s) specified. In addition, when new data is inserted into the columnstore index, it will be pre-sorted as well. When an ordered clustered columnstore index is the target of an index rebuild operation, the column order specified earlier will be honored.

This feature sounds like the perfect solution to enable segment elimination, but it is in no way free. As implied by the use of the word SORT, SQL Server needs to expend resources to sort the data. This not only requires TempDB resources, but it is an OFFLINE operation. Therefore, swapping a clustered columnstore index for one that is sorted will result in rebuild operations going from being online to offline operations. Note that in a partitioned table, then operation will only be offline for partitions affected by the rebuild operation. Typically, this will be a single current-data partition. Therefore, partitioning can help in improving availability for much of the data in ordered clustered columnstore indexes.

The sort operation can be visualized by checking the execution plan for both a standard and ordered columnstore index.

If you look at the query plan for creating thee indexes, you will see some interesting differences. The following plan is for creating the non-ordered columnstore index built earlier in this article:

No surprises here. I wait 30 seconds and a columnstore index is ready for use on the table. Using the new syntax above that includes the ORDER clause will produce the following execution plan:

A SORT operation appears in the plan. Without partitioning or any other aids available, SQL Server needs to sort the entire data set in order to create an index that is ordered on the column of my choosing.

The column(s) used in the ORDER clause can be validated anytime in the system view sys.index_columns, using a query similar to this:

SELECT
     tables.name AS table_name,
     indexes.name AS index_name,
     columns.name AS column_name,
     index_columns.column_store_order_ordinal
FROM sys.index_columns
INNER JOIN sys.indexes
ON indexes.index_id = index_columns.index_id
AND indexes.object_id = index_columns.object_id
INNER JOIN sys.columns
ON index_columns.object_id = columns.object_id
AND columns.column_id = index_columns.column_id
INNER JOIN sys.tables
ON tables.object_id = indexes.object_id
WHERE tables.name = 'fact_order_BIG_CCI';

The results list all of the columns in the table, along with their column store order, if applicable. A value of zero indicates that the column is not a part of the columnstore order:

The metadata shows that Order Date Key is the sole ORDER column for this columnstore index. Consider a new index ordered by Order Date Key and then by Order Key:

CREATE CLUSTERED COLUMNSTORE INDEX CCI_fact_order_BIG_CCI ON dbo.fact_order_BIG_CCI
ORDER ([Order Date Key], [Order Key])
WITH (DROP_EXISTING = ON, MAXDOP = 1);

For this index, the metadata results from above show the additional column as part of the columnstore order:

Note that Order Key is now shows as the second column in the columnstore order, after Order Date Key. For a large columnstore indexed table, ordering by an additional column may further assist queries that rely on multi-column filters.

Ordered Columnstore Index Notes and Considerations

It is worth repeating that only clustered columnstore indexes can be use the ORDER clause. Non-clustered columnstore indexes inherit data order from the underlying rowstore index structure during creation and will provide segment elimination as effectively as the underlying data allows.

Ordered columnstore indexes are a heavy-handed and somewhat imperfect way of improving data order and segment elimination for three reasons:

  1. Rebuilding an ordered columnstore index is an OFFLINE operation.
  2. Any data that is sorted must be sorted in TempDB.
  3. If a sort operation is so large that it would spill to disk, then the sort is aborted and data order may not be perfect.

There is value in exploring each of these issues to ensure that decisions made regarding ordered columnstore indexes are as optimal as possible:

Rebuilds on an Ordered Columnstore Index = OFFLINE Operation (Per Partition)

This is an availability concern that will not impact all users of columnstore indexes. If dedicated maintenance windows exist for index maintenance and OFFLINE is acceptable for rebuild operations, then there is no issue to be had here. Index reorganization is still an ONLINE operation and can be used as part of regular maintenance to reduce the need for rebuilds.

The amount of time that a given partition is unavailable will be equal to the amount of time needed to sort and rebuild the data in that partition. Therefore, if rebuilding a partition with 20 million rows in a clustered columnstore index typically takes 30 seconds, then the same operation would result in at least 30 seconds of offline/downtime for the same index if it were ordered. Presumably the sort operation will require some additional time, increasing the overall time needed to some number greater than 30 seconds.

It is possible to use partition switching to increase availability, though whether that level of added complexity is desired or not is wholly up to you to decide.

Ordered Columnstore Indexes Sort in TempDB

Data needs to be sorted, and in SQL Server, TempDB is where this happens. As a result, to ensure that data is properly sorted, it is important that TempDB has enough space allocated for it. If 500MB of data is to be inserted into an ordered columnstore index, then there needs to be an additional 500MB of TempDB space available.

Similarly, if a 500GB columnstore index is being rebuilt into an ordered columnstore index, then 500GB+ of TempDB space will be required. Depending on the organization and its hardware,

If there is insufficient TempDB space available to store the incoming columnstore data, then don’t use this feature. Ensuring there is enough space, though, becomes more important due to the next challenge:

Sort Operations Do Not Complete in Their Entirety

What happens when an ordered columnstore index is rebuilt or inserted into and not enough space is available in TempDB? Not what is expected! Typically, if a sort operator in an execution plan requires more TempDB space than is allocated or available, it spills to disk to allocate enough space to complete the operation.

That is NOT what happens with ordered columnstore indexes. If the data to be sorted into an ordered columnstore index exceeds the space allocated by the memory grant, then the sort operation simply completes and is flagged internally as a soft sort. A soft sort will sort as many rows as it can, but when space runs out, it will stop. While this behavior ensures that write operations are fast and do not spill to disk, they also pose a hazard as it is not immediately clear that this behavior occurred without further research.

To illustrate a soft sort, the test table earlier will be dropped, recreated, and populated with ~27.8 million rows. TempDB will also be reduced to a relatively small size to ensure that there is not enough space available to fully sort this data. The following code handles the table drop, creation, and population:

DROP TABLE dbo.fact_order_BIG_CCI;

CREATE TABLE dbo.fact_order_BIG_CCI (
     [Order Key] [bigint] NOT NULL,
     [City Key] [int] NOT NULL,
     [Customer Key] [int] NOT NULL,
     [Stock Item Key] [int] NOT NULL,
     [Order Date Key] [date] NOT NULL,
     [Picked Date Key] [date] NULL,
     [Salesperson Key] [int] NOT NULL,
     [Picker Key] [int] NULL,
     [WWI Order ID] [int] NOT NULL,
     [WWI Backorder ID] [int] NULL,
     [Description] [nvarchar](100) NOT NULL,
     [Package] [nvarchar](50) NOT NULL,
     [Quantity] [int] NOT NULL,
     [Unit Price] [decimal](18, 2) NOT NULL,
     [Tax Rate] [decimal](18, 3) NOT NULL,
     [Total Excluding Tax] [decimal](18, 2) NOT NULL,
     [Tax Amount] [decimal](18, 2) NOT NULL,
     [Total Including Tax] [decimal](18, 2) NOT NULL,
     [Lineage Key] [int] NOT NULL);

-- Generate 27769440 rows in a heap:
INSERT INTO dbo.fact_order_BIG_CCI
SELECT
     [Order Key] + (250000 * ([Day Number] +
            ([Calendar Month Number] * 31))) AS [Order Key]
    ,[City Key]
    ,[Customer Key]
    ,[Stock Item Key]
    ,[Order Date Key]
    ,[Picked Date Key]
    ,[Salesperson Key]
    ,[Picker Key]
    ,[WWI Order ID]
    ,[WWI Backorder ID]
    ,[Description]
    ,[Package]
    ,[Quantity]
    ,[Unit Price]
    ,[Tax Rate]
    ,[Total Excluding Tax]
    ,[Tax Amount]
    ,[Total Including Tax]
    ,[Lineage Key]
FROM Fact.[Order]
CROSS JOIN
Dimension.Date
WHERE Date.Date <= '2013-04-30';

With a heap of data waiting to be sorted, trace flag 8666 will be enabled:

DBCC TRACEON (8666);

This undocumented trace flag will provide additional query optimizer details that otherwise are not provided in execution plans (graphical or XML). If you experiment with this trace flag, be sure to do so in a test environment and disable it when your testing is complete!

With added optimizer detail available, let’s turn on the actual execution plan, so we can quickly visualize what is going on here:

Finally, it is time to build an ordered columnstore index on the larger table created above:

CREATE CLUSTERED COLUMNSTORE INDEX CCI_fact_order_BIG_CCI ON dbo.fact_order_BIG_CCI
ORDER ([Order Date Key], [Order Key])
WITH (MAXDOP = 1)

This takes a few minutes to complete on my local server. The execution plan now contains some added information that can be used to understand what happened when SQL Server sorted the incoming data:

Opening the properties for the Sort operator allows us to get some additional detail:

Within the internal debugger info is a flag that indicates if this was a soft sort or not. In this case, the answer is yes!

With that validated, the metadata query from earlier in this article will be run to show how well-ordered the rowgroups in the columnstore index are:

There are 27 rowgroups in total, but it is clear from the first 9 that this data is not actually ordered on Order Date Key effectively. While examining the values for min_data_id and max_data_id shows SOME ordering, it is clear that a query that should read 1-2 rowgroups will instead read many more as so many value ranges overlap.

To summarize: soft sorting is a hazard for building and maintaining ordered columnstore indexes and may be a reason to hold off on using them until the feature is further refined.

Conclusion

Prior to this feature, order was maintained manually. This sounds painful, but in reality, analytic data is often created based on date/time and naturally orders itself based on some key dimension(s), often date/time. For example, a table that loads new sales data daily will add a new day’s worth of data to the end of the columnstore index each day. So if updates are not performed on this table, then the data will naturally remain ordered as new data will also be the most recent. Even if 5% of the incoming data were old and out-of-order, overall segment elimination would still be relatively good.

Ordered columnstore indexes are an attempt to bring more focus on rowgroup elimination and its importance in speeding up analytic queries. If a columnstore index has 1 billion rows, then it will contain approximately 1,000 rowgroups. Reading 1000 segments to get data on a single column is far more expensive than reading 3 segments. Despite its promises, ordered columnstore indexes are not perfect and have limitations that make them a less-than-ideal solution, especially for tables where large amounts of data are inserted or rebuilt regularly.

This feature may work for you but be sure to test and ensure that insert operations and rebuilds do indeed sort the data correctly. If not, it may be worth reverting to the old-fashioned way of managing this data using natural ordering via manual processes.

Let’s hope for feature improvements! Columnstore indexes are a prime example of a feature that has improved steadily with every version of SQL Server since its inception. In the same way that columnstore indexes have matured to allow a wider variety of write operations, rowgroup elimination for more data types and predicates, and improved rowgroup consolidation/maintenance, it is likely that this feature will also get a much-needed upgrade soon.

 

The post Ordered Columnstore Indexes in SQL Server 2022 appeared first on Simple Talk.



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

Tuesday, April 4, 2023

Modifying MySQL data from within Python

In the previous article in this series, I introduced you to how to access MySQL data from within a Python script. The article described how to use the MySQL Connector to establish a connection with a database and then retrieve data through that connection. In this article, I continue the discussion by demonstrating how to insert, update, and delete data in a MySQL database, again working with Python and the MySQL Connector.

The process of modifying MySQL data from within Python is, in many respects, similar to querying data. You must define a connection object that links to the database and define a cursor object based on that connection. You can then use the cursor object to execute your SQL statement. If you are not familiar with these concepts, I recommend that you read my previous article before launching into this one.

Although I focus specifically on Python and the MySQL Connector in this article (and in the last one), the process of connecting to a MySQL database and querying data is similar in most object-oriented programming environments, at least in the broader sense.

Each combination of programming language and database connector is unique, and you must understand how they work in your specific environment to use them effectively. That said, seeing how to interface with MySQL from within Python can still provide you with a conceptual understanding of what database access looks like in a programming language.

Note: The examples in this article are based on a specific MySQL and Python setup. The last section of the article—“Appendix: Preparing your Python and MySQL environment”—provides information about how I set up my system and includes a SQL script for creating the database and tables on which the examples are based.

Adding data to a MySQL database from within Python

The steps you take to insert data in a MySQL database are similar to those you follow to update or delete data. In each case, you generally take the following steps:

  1. Import the mysql.connector module or specific its components.
  2. Define a connection object that establishes a connection to the target database.
  3. Use the connection object to invoke the cursor method and create a cursor object.
  4. Define a SQL statement and save it to a variable.
  5. Use the cursor object to invoke the execute method, passing in the variable as an argument.
  6. Commit your changes to the database.
  7. Close the cursor and the connection.

These steps are, of course, a simplification of the process, but they should provide you with an idea of what you’re trying to achieve. You can see these steps in the following Python script, which runs an INSERT statement against the manufacturers table in the travel database:

# import connect and Error modules
from mysql.connector import connect, Error

# define connection object
conn = connect(
  user='root',
  password='mysql_PW@327!xx',
  host='localhost',
  database='travel')

# open cursor
cursor = conn.cursor()

# try to run code block
try:
  # define INSERT statement
  add_manufacturer = ('INSERT INTO manufacturers '
    '(manufacturer_id, manufacturer) '
    'VALUES (101, \'Airbus\')')

  # run INSERT statement
  cursor.execute(add_manufacturer)

  # commit transaction
  conn.commit()

# catch exception, roll back transaction, print error message
except Error as err:
  conn.rollback()
  print('Error message: ' + err.msg)

# close cursor, close connection
finally:
  cursor.close()
  conn.close()

If you read the previous article, many of these elements should look familiar to you. The script starts by importing the connect and Error methods from the MySQL Connector module (mysql.connector). Next, the script instantiates a connection object and assigns it to the conn variable and then instantiates a cursor object and assigns it to the cursor variable. This is followed by a try block, where you define and run your SQL statement.

Note: I do want to remind you again that putting passwords, especially the root password, in a script that you store somewhere is not best security practice. A discussion of security is far beyond the scope of this article. It’s up to you to take the steps necessary to secure your application from the wide range of potential threats that can put your data at risk.

One thing you might notice that’s different in this script from the examples you saw in the previous article is that the connection and cursor objects are defined prior to the try block, rather than within it. This lets you access the objects outside of the try block, which I’ll explain shortly.

In the try block, I first defined the INSERT statement and assigned it to the add_manufacturer variable. I then used the cursor object to call the execute method, passing in the variable in as an argument. Because it contains the INSERT statement, the method will execute the statement when you run the script.

Next, I used the connection object to invoke the commit method. You must specially commit your changes to the database because by default, the MySQL Connector turns off MySQL’s autocommit feature, so your changes won’t be implemented until you commit them. (Note: you can control this with autocommit property on the connection object if you wish.)

I also used the connection object to invoke the rollback method, which I included in the except block. Because I defined the connection object outside of the try block, I can use the object in other blocks to invoke methods such as rollback. If a data-related error occurs, the transaction will be rolled back, undoing any changes that might have been made within the try block.

Something else I’ve included that wasn’t in the previous article is a finally block. A finally block is often used with a try block to run statements that should be executed whether or not an error occurs. In this way, you can ensure that the cursor and connection get closed even if there is a MySQL exception.

When you run the Python script the first time, it should insert the row in the manufacturers table with no problem. However, if you try to run the script a second time, MySQL will return a duplicate key error because the manufacturer_id value of 101 already exists. The manufacturer_id column is the table’s primary key, so a duplicate key error would be expected. In fact, this is an easy way to verify whether your script’s MySQL error handing is working as it should.

In the previous article, I also demonstrated how to use the %s marker as a placeholder within your SELECT statements. The marker makes it possible to create more dynamic SELECT statements based on user input. You can also use %s markers in your INSERT statements (as well as UPDATE and DELETE statements). The following Python script includes an INSERT statement that contains nine %s markers in the VALUES clause:

# import connect and Error modules
from mysql.connector import connect, Error

# define connection object
conn = connect(
  user='root',
  password='mysql_PW@327!xx',
  host='localhost',
  database='travel')

# open cursor
cursor = conn.cursor()

# try to run code block
try:
  # define INSERT statement
  add_airplane = ('INSERT INTO airplanes '
    '(plane_id, plane, manufacturer_id, engine_type, engine_count, '
      'wingspan, plane_length, max_weight, icao_code) '
    'VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)')

  # define plane values for INSERT in a tuple
  plane_values = (1001, 'A340-600', 101, 'Jet', 4, 208.17, 247.24, 837756, 'A346')

  # run INSERT statement
  cursor.execute(add_airplane, plane_values)

  # commit transaction
  conn.commit()

# catch exception, roll back transaction, print error message
except Error as err:
  conn.rollback()
  print('Error message: ' + err.msg)

# close cursor, close connection
finally:
  cursor.close()
  conn.close()

After defining the INSERT statement, I created a tuple that contains the values that will be assigned to the markers, in the order they need to be inserted. I then assigned the tuple to the plane_values variable. (A tuple is an immutable collection of objects.) In the real world, you’ll likely want to capture the marker values through user interaction or other means, rather than hard-coding them in this way, but this approach should be enough to demonstrate how the markers work.

After defining my SQL statement and marker values, I used the cursor object to call the execute method and run the INSERT statement. I also included a second argument that specifies the plane_values variable. As a result, the %s markers in the INSERT statement will be replaced with the tuple values during statement execution. When you run the script the first time, the row should be added to the airplanes table with no problem.

In some cases, you’ll want to add multiple rows to a table in a single operation. You can do this in Python by making a few adjustments to the code, as shown in the following script:

# import connect and Error modules
from mysql.connector import connect, Error

# define connection object
conn = connect(
  user='root',
  password='mysql_PW@327!xx',
  host='localhost',
  database='travel')

# open cursor
cursor = conn.cursor()

# try to run code block
try:
  # define INSERT statement
  add_airplanes = ('INSERT INTO airplanes '
    '(plane_id, plane, manufacturer_id, engine_type, engine_count, '
      'wingspan, plane_length, max_weight, icao_code) '
    'VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)')

  # define plane values for INSERT in an list of tuples
  plane_values = [
    (1002, 'A350-800 XWB', 101, 'Jet', 2, 212.42, 198.58, 546700, 'A358'),
    (1003, 'A350-900', 101, 'Jet', 2, 212.42, 219.16, 617295, 'A359'),
    (1004, 'A380-800', 101, 'Jet', 4, 261.65, 238.62, 1267658, 'A388'),
    (1005, 'A380-843F', 101, 'Jet', 4, 261.65, 238.62, 1300000, 'A38F')]

  # run INSERT statement
  cursor.executemany(add_airplanes, plane_values)

  # commit transaction
  conn.commit()

# catch exception, roll back transaction, print error message
except Error as err:
  conn.rollback()
  print('Error message: ' + err.msg)

# close cursor, close connection
finally:
  cursor.close()
  conn.close()

The INSERT statement in this script is the same one as in the previous example. However, the tuple assigned to the plane_values variable has been replaced by a list that includes four tuples containing the %s values for the INSERT statement. Each tuple corresponds to one row of data that will be inserted into the airplanes table.

Another difference in this example from the previous one is that the cursor object is now used to invoke the executemany method rather than the execute method. The executemany method makes it easy to use a single INSERT statement to add multiple rows to a table, while still taking advantage of the %s markers. When you run this Python script, it should now add the four rows to the airplanes table.

You can, of course, define an INSERT statement that includes all the rows, without using the %s markers, but then you lose the advantage of the markers and their potential for creating dynamic queries. Even so, it’s good to know that you can create a single statement if you want to go this route.

You can also define multiple SQL statements within your Python code. For example, the following Python script adds a row to the manufacturers table and then adds five rows to the airplanes table for that manufacturer:

# import connect and Error modules
from mysql.connector import connect, Error

# define connection object
conn = connect(
  user='root',
  password='mysql_PW@327!xx',
  host='localhost',
  database='travel')

# open cursor
cursor = conn.cursor()

# try to run code block
try:
  # define manufacturers INSERT statement
  add_manufacturer = ('INSERT INTO manufacturers '
    '(manufacturer_id, manufacturer) '
    'VALUES (%s, %s)')

  # define manufacturer values for INSERT
  manufacturer_values = (102, 'Beagle Aircraft Limited')

  # run manufacturers INSERT statement
  cursor.execute(add_manufacturer, manufacturer_values)

  # define airplanes INSERT statement
  add_airplanes = ('INSERT INTO airplanes '
    '(plane_id, plane, manufacturer_id, engine_type, engine_count, '
      'wingspan, plane_length, max_weight, icao_code) '
    'VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)')

  # define plane values for INSERT
  plane_values = [
    (1006, 'A.109 Airedale', 102, 'Piston', 1, 36.33, 26.33, 2750, 'AIRD'),
    (1007, 'A.61 Terrier', 102, 'Piston', 1, 36, 23.25, 2400, 'AUS6'),
    (1008, 'B.121 Pup', 102, 'Piston', 1, 31, 23.17, 1600, 'PUP'),
    (1009, 'B.206', 102, 'Piston', 2, 55, 33.67, 7500, 'BASS'),
    (1010, 'D.5-108 Husky', 102, 'Piston', 1, 36, 23.17, 2400, 'D5')]

  # run airplanes INSERT statement
  cursor.executemany(add_airplanes, plane_values)

  # commit transaction
  conn.commit()

# catch exception, roll back transaction, print error message
except Error as err:
  conn.rollback()
  print('Error message: ' + err.msg)

# close cursor, close connection
finally:
  cursor.close()
  conn.close()

The script first defines the INSERT statement for the manufacturers table, adds a tuple for the statement’s %s values, and then invokes the execute method to run the statement. Next, the script defines the INSERT statement for the airplanes table, adds a list of tuples for the %s values, and then invokes the executemany method to run the second statement. After running the two statements, the script commits the transaction.

Updating data in a MySQL database from within Python

The process of updating MySQL data from within Python works much the same as inserting data, except that you define an UPDATE statement instead of an INSERT statement. For example, the following Python script modifies a row in the airplanes table:

# import connect and Error modules
from mysql.connector import connect, Error

# define connection object
conn = connect(
  user='root',
  password='mysql_PW@327!xx',
  host='localhost',
  database='travel')

# open cursor
cursor = conn.cursor()

# try to run code block
try:
  # define UPDATE statement
  update_plane = ("UPDATE airplanes "
    "SET plane = 'D.5/108 Husky' WHERE plane_id = %s")

  # define plane_id value for UPDATE as a tuple
  id_value = (1010,)

  # run UPDATE statement
  cursor.execute(update_plane, id_value)

  # commit transaction
  conn.commit()

# catch exception, roll back transaction, print error message
except Error as err:
  conn.rollback()
  print('Error message: ' + err.msg)

# close cursor, close connection
finally:
  cursor.close()
  conn.close()

You should recognize most of the elements in this script. The UPDATE statement changes the plane value for the row that has a plane_id value of 1010. This in itself should be fairly straightforward, but take particular note of the id_value variable and its assignment.

The UPDATE statement includes only one %s marker, so you need to define only one value outside the statement. In this case, however, the assigned value, 1010, is followed by a comma and enclosed in parentheses. This is because the execute method will accept only a list, tuple, or dictionary for the second argument, not a simple string or integer. To accommodate this requirement, I created a tuple by adding the trailing comma and then enclosing the value and comma in parentheses. Now I can then use the id_value variable as the second argument of the execute method.

When modifying MySQL data, you can create more complex SQL statements than what I showed you in the previous script. For example, the following UPDATE statement includes a subquery in its WHERE clause:

# import connect and Error modules
from mysql.connector import connect, Error

# define connection object
conn = connect(
  user='root',
  password='mysql_PW@327!xx',
  host='localhost',
  database='travel')

# open cursor
cursor = conn.cursor()

# try to run code block
try:
  # define UPDATE statement
  update_planes = ("UPDATE airplanes "
    "SET wingspan = ROUND(wingspan), plane_length = ROUND(plane_length) "
    "WHERE manufacturer_id = "
      "(SELECT manufacturer_id FROM manufacturers "
      "WHERE manufacturer = %s)")

  # define plane_id value for UPDATE
  manufacturer = ('Beagle Aircraft Limited',)

  # run UPDATE statement
  cursor.execute(update_planes, manufacturer)

  # commit transaction
  conn.commit()

# catch exception, roll back transaction, print error message
except Error as err:
  conn.rollback()
  print('Error message: ' + err.msg)

# close cursor, close connection
finally:
  cursor.close()
  conn.close()

The subquery retrieves the manufacturer_id value for the manufacturer specified in the manufacturer variable. The manufacturer_id value is then used to determine which rows in the airplanes table to update. (I covered subqueries in an earlier article in this series, so refer to that if you have any questions about how they work.)

In the previous two examples, the UPDATE statements included only one %s marker, but you can include multiple markers in your statements, as in the following Python script:

# import connect and Error modules
from mysql.connector import connect, Error

# define connection object
conn = connect(
  user='root',
  password='mysql_PW@327!xx',
  host='localhost',
  database='travel')

# open cursor
cursor = conn.cursor()

# try to run code block
try:
  # define UPDATE statement
  update_plane = ("UPDATE airplanes "
    "SET wingspan = wingspan + %s, plane_length = plane_length + %s "
    "WHERE plane_id = %s")

  # define values for UPDATE in a tuple
  plane_values = (5, 8, 1005)

  # run UPDATE statement
  cursor.execute(update_plane, plane_values)

  # commit transaction
  conn.commit()

  # define SELECT statement
  select_query = (
    "SELECT plane_id, plane, wingspan, plane_length "
    "FROM airplanes WHERE plane_id = %s")

  # run SELECT statement
  cursor.execute(select_query, (plane_values[2],))
  results = cursor.fetchone()

  # print query results
  print('Rows updated:', cursor.rowcount)
  print('plane_id:', results[0])
  print('plane:', results[1])
  print('new wingspan:', results[2])
  print('new plane_length:', results[3])

# catch exception, roll back transaction, print error message
except Error as err:
  conn.rollback()
  print('Error message: ' + err.msg)

# close cursor, close connection
finally:
  cursor.close()
  conn.close()

The UPDATE statement contains two %s markers in the SET clause and one in the WHERE clause. The values for these markers are in a tuple that I assigned to the plane_values variable. You can use as many %s markers as needed in whatever clauses you deem necessary. Just remember to specify their values in the correct order so they match the statement.

After I ran the UPDATE statement and called the commit method, I defined a SELECT statement to retrieve the newly updated data from the airplanes table. I did this as a way to verify that the data had been correctly modified.

When I called the execute method to run the SELECT statement, I passed in the value from the plane_values tuple, specifying 2 as the value’s index number. (Tuples use a 0-based index.) I also added a comma after the index number and enclosed the entire value in parentheses so it would be treated as its own tuple, as required by the execute method.

I then used the cursor object to run the fetchone method, which retrieves the current row from the query results. Next, I saved the row of values—returned as a single tuple—to the results variable.

I followed this with a series of print statements that display information about the update. The first print statement calls the rowcount property on the cursor object. The property shows the number of rows that were affected by the UPDATE statement. This is followed by four more print statements, one for each value in the row returned by the SELECT statement. Each print statement uses the tuple’s index to specify which value to include. The returned information should look similar to the following:

Rows updated: 1
plane_id: 1005
plane: A380-843F
new wingspan: 266.65
new plane_length: 246.62

The original wingspan value was 261.65, and the original plane_length value was 238.62. When you add 5 and 8 to these values, respectively, you get the new totals returned by the script. You can also add logic to your script to capture the old values before updating them. In that way, you can return both the old and new values at the end of your script and pass those onto your application.

Deleting data in a MySQL database from within Python

The process of deleting MySQL data from within Python is much the same as inserting or updating it. For example, the following Python script deletes a row from the airplanes table:

# import connect and Error modules
from mysql.connector import connect, Error

# define connection object
conn = connect(
  user='root',
  password='mysql_PW@327!xx',
  host='localhost',
  database='travel')

# open cursor
cursor = conn.cursor()

# try to run code block
try:
  # define DELETE statement
  delete_plane = ("DELETE FROM airplanes "
    "WHERE plane_id = %s")

  # define plane_id value for DELETE in a tuple
  plane_id = (1010,)

  # run DELETE statement
  cursor.execute(delete_plane, plane_id)
  print('Number of rows deleted: ', cursor.rowcount)

  # commit transaction
  conn.commit()

# catch exception, roll back transaction, print error message
except Error as err:
  conn.rollback()
  print('Error message: ' + err.msg)

# close cursor, close connection
finally:
  cursor.close()
  conn.close()

At this point, you should be familiar with all the elements in this script. I defined a DELETE statement and assigned it to the delete_plane variable. I then assigned a value to the plane_id variable, which will be used for the %s marker. Next, I executed the statement, specifying the two variables, and added a print statement to display the number of rows that were deleted.

Overall, there’s nothing really new about this script except for the use of a DELETE statement rather than INSERT or UPDATE. I simply wanted to show you what deleting data might look like. You can make your DELETE statements as complex as necessary and use more %s markers where needed, as in the next example:

# import connect and Error modules
from mysql.connector import connect, Error

# define connection object
conn = connect(
  user='root',
  password='mysql_PW@327!xx',
  host='localhost',
  database='travel')

# open cursor
cursor = conn.cursor()

# try to run code block
try:
  # define DELETE statement
  delete_plane = ("DELETE FROM airplanes "
    "WHERE manufacturer_id = %(mfc_id)s AND max_weight < %(weight)s")

  # define values for DELETE in a tuple
  plane_values = {'mfc_id': 102, 'weight': 5000}

  # run DELETE statement
  cursor.execute(delete_plane, plane_values)
  print('Number of rows deleted: ', cursor.rowcount)

  # commit transaction
  conn.commit()

# catch exception, roll back transaction, print error message
except Error as err:
  conn.rollback()
  print('Error message: ' + err.msg)

# close cursor, close connection
finally:
  cursor.close()
  conn.close()

In this script, I’ve used a different form of the %s markers. When I defined the marker values, I created a dictionary rather than a tuple or list. A dictionary makes it possible to assign a label to each value. You can then reference that label within your SQL statement. To do so, insert the label name, enclosed in parentheses, between the % and the s, as in %(mfc_id)s. You can reference any value in the dictionary, without regard to their order.

Getting started with Python and MySQL data modifications

In this article and the previous one, I’ve tried to provide you with a foundation for using the MySQL Connector in your Python scripts. There is, of course, much more to the connector and MySQL that what I’ve shown you here. There’s also a lot more to writing data-driven scripts and applications. But the information I’ve provided should at least help you better understand how to connect to a MySQL database from within Python and manipulate the data. You might also find this information useful when working with other programming languages, at least from a conceptual vantage point. Data is at the heart of most applications, and the more insight you have into how the pieces fit together, the greater you’ll be able to appreciate what it takes to make these applications work.

Appendix: Preparing your MySQL and Python environment

For the examples in this article, I used a Mac computer that was set up with the following components:

  • MySQL 8.0
  • Python 3.10
  • PyCharm Community Edition IDE
  • MySQL Connector/Python 8.0 module

You can find information about installing the module in the MySQL documentation. On my system, I used pip to add the module. Pip is a package installer for Python that makes it very easy to deploy a module.

The Python examples in this article connect to the travel database on a local MySQL instance. The database contains the manufacturers table and airplanes table, which is defined with a foreign key that references the manufacturers table. This is the same database and tables you saw in previous articles in this series, except that you don’t need to insert any data.

If you plan to try out these examples, start by running the following script against your MySQL instance:

DROP DATABASE IF EXISTS travel;

CREATE DATABASE travel;

USE travel;

CREATE TABLE manufacturers (
  manufacturer_id INT UNSIGNED NOT NULL,
  manufacturer VARCHAR(50) NOT NULL,
  create_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  last_update TIMESTAMP NOT NULL 
    DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (manufacturer_id) );

CREATE TABLE airplanes (
  plane_id INT UNSIGNED NOT NULL,
  plane VARCHAR(50) NOT NULL,
  manufacturer_id INT UNSIGNED NOT NULL,
  engine_type VARCHAR(50) NOT NULL,
  engine_count TINYINT NOT NULL,
  max_weight MEDIUMINT UNSIGNED NOT NULL,
  wingspan DECIMAL(5,2) NOT NULL,
  plane_length DECIMAL(5,2) NOT NULL,
  parking_area INT GENERATED ALWAYS AS ((wingspan * plane_length)) STORED,
  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),
  CONSTRAINT fk_manufacturer_id FOREIGN KEY (manufacturer_id) 
    REFERENCES manufacturers (manufacturer_id) );

The script will create the travel database and add the manufacturers and airplanes tables in the proper order to accommodate the foreign key defined in the airplanes table. If you already created the database and tables for previous articles, I recommend that you re-create them now to ensure that your key values line up correctly with the examples.

 

The post Modifying MySQL data from within Python appeared first on Simple Talk.



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