# DDL Execution

![`smart`](DDLExecution01_aa_005_20220512.png)

-----------------------------------------------------------
TiDB supports Online DDL, which means DDL operations do not lock tables, and DML statements are not blocked.

First, only one TiDB server is allowed to execute DDL operations at the same time for the entire TiDB. There is a `Worker` module in each TiDB server, which is responsible for handling DDL operations and will only be enabled when the current TiDB server's role is `Owner`. If there are multiple TiDB servers in your TiDB cluster, these TiDB servers will take turns (through election) to become the `Owner` role at a fixed time (which is called the `term`). When a TiDB server is the `Owner` role and in the `term`, its `Worker` module can handle DDL operations. The current `Owner` role information of the database is persisted to PD, and the `Worker` module can check whether the TiDB server where it is located is currently the `Owner` role. After the `term` of the `Owner` expires, PD will initiate an election to select a new `Owner`.

Secondly, besides the `Worker` module, there is also the `Load Schema` module, which is used to load the latest schema information after the current TiDB server becomes the `Owner` role, so that the current `Owner` role TiDB server can have the latest schema information.

Finally, the Start Job module is responsible for receiving DDL requests, assigning IDs for DDL operations, and here we call each DDL operation with an assigned ID a Job.

In summary, the first part of DDL operations can be summarized as:

1. DDL statements are sent from the client to the TiDB server, which parses and compiles them to generate an execution plan. This process is the same as for DML statements.

2. The Start Job module encapsulates the DDL operations and persists them to TiKV. Afterwards, Start Job will do another job, which is to notify the `Worker` module of the TiDB server it is on to execute the job in TiKV. Then the `Worker` first determines whether the TiDB server it is on is the `Owner` role, if it is, it will execute, if not, it will give up.

3. If the TiDB server where the Start Job is located is not the `Owner` role, then we can only wait for the TiDB server with the `Owner` role in the TiDB database to periodically check the tasks in the queue, and then the Job will be processed.
