0Pricing
Clojure Functional Programming & JVM Backend Development · 课时

数据库迁移与架构管理

了解在 Clojure 项目中管理数据库架构变更和迁移的工具与策略。

数据库迁移与架构管理 是 CoddyKit 上的免费 Clojure Functional Programming & JVM Backend Development 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Clojure Functional Programming & JVM Backend Development 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Clojure Functional Programming & JVM Backend Development 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Manage Database Schema?

What happens when your application changes? New features often need new places to store data, or changes to existing data structures. This is where managing your database schema comes in.

A database schema is like a blueprint for your database. It defines the tables, columns, relationships, and constraints that structure your data.

As your application evolves, so must its schema. Manual changes can be risky and inconsistent across environments.

Database Migrations Explained

Database migrations are version control for your database schema. Think of them like code commits, but for your database structure.

Each migration is a set of instructions (usually SQL) that describes how to change the database from one version to the next. They are typically timestamped and applied in order.

  • `up` script: Applies a change (e.g., add a table).
  • `down` script: Reverts a change (e.g., drop a table).

Why Use Migrations?

Using database migrations offers several key advantages for development teams:

  • Consistency: Ensures all developers and deployment environments have the same database schema.
  • Collaboration: Makes it easy for multiple developers to contribute schema changes without conflicts.
  • Rollback Capability: Allows you to easily revert to a previous schema state if something goes wrong.
  • Automation: Integrates smoothly into your CI/CD pipeline for automated deployments.

Clojure's Migratus Library

In the Clojure ecosystem, a popular and robust library for managing database migrations is Migratus.

Migratus is flexible, supporting SQL and even Clojure-based migrations. It keeps track of applied migrations in your database, ensuring they are only run once and in the correct order.

It's designed to be simple to configure and use, fitting well with Clojure's functional approach.

Setting Up Migratus

To use Migratus, you first add it as a dependency and configure it. Here's a typical setup using deps.edn and a configuration map:

First, add the dependency to your deps.edn:

{:deps {org.clojure/clojure {:mvn/version "1.11.1"}
        migratus/migratus {:mvn/version "1.0.10"}
        org.postgresql/postgresql {:mvn/version "42.6.0"}}}

Then, create a migratus-config.edn file (or similar) to define your database connection:

{:store :database
 :migration-dir "resources/migrations"
 :db {:classname   "org.postgresql.Driver"
      :subprotocol "postgresql"
      :subname     "//localhost:5432/myapp_db"
      :user        "dbuser"
      :password    "dbpass"}}

Structure of a Migration

Migrations are usually SQL files placed in a designated directory (e.g., resources/migrations as configured earlier). Each migration consists of an "up" and a "down" script.

Migratus expects files named like YYYYMMDDHHMMSS-migration-name.up.sql and YYYYMMDDHHMMSS-migration-name.down.sql.

The timestamp ensures a unique order. You can generate these using a command-line tool, typically migratus create <name>.

`up.sql` Example

The .up.sql file contains SQL commands to apply the schema change. This example creates a new users table.

-- resources/migrations/20231027100000-create-users-table.up.sql

CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  username VARCHAR(255) NOT NULL UNIQUE,
  email VARCHAR(255) NOT NULL,
  created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

This script defines the initial structure for our users.

`down.sql` Example

The .down.sql file contains SQL commands to revert the schema change made by its corresponding .up.sql. This example drops the users table.

-- resources/migrations/20231027100000-create-users-table.down.sql

DROP TABLE IF EXISTS users;

It's crucial that the `down` script precisely undoes the `up` script, allowing for safe rollbacks.

Applying Migrations

Once your migration files are ready and `migratus` is configured, you can apply your migrations.

Typically, you'd use a command-line tool like Leiningen or clj with an alias configured for `migratus`.

To apply all pending migrations:

lein migratus migrate

or if using clj with a migratus alias:

clj -M:migratus migrate

Migratus will run all `up` scripts that haven't been applied yet, in order.

Undoing Changes

Sometimes you need to undo a migration, perhaps due to an error or a change in requirements. Migratus makes this easy.

To roll back the last applied migration:

lein migratus rollback

This command will execute the `down` script of the most recently applied migration. You can call it multiple times to roll back further.

Always ensure your `down` scripts are safe and idempotent!

Migration Concepts

Understanding the purpose of up and down scripts is key to effective schema management.

Recap: Schema Management

We've explored the critical role of database migrations in managing schema changes in Clojure projects. You learned:

  • What database schemas and migrations are.
  • The benefits of version-controlled schema changes.
  • How to use `Migratus` to define and apply migrations using `up` and `down` SQL scripts.
  • Commands to apply and roll back migrations.

With migrations, your database schema can evolve alongside your application code in a controlled and reliable way!

常见问题解答

「数据库迁移与架构管理」课时是免费的吗?

是的 — 「数据库迁移与架构管理」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Clojure Functional Programming & JVM Backend Development 课程的其余内容,请升级到 CoddyKit PRO。 Clojure Functional Programming & JVM Backend Development 课程共包含 4 节课。

「数据库迁移与架构管理」这节课中我会学到什么?

了解在 Clojure 项目中管理数据库架构变更和迁移的工具与策略。 你通过在浏览器中直接运行的动手代码来练习 Clojure Functional Programming & JVM Backend Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Clojure Functional Programming & JVM Backend Development 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Clojure Functional Programming & JVM Backend Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「数据库迁移与架构管理」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Clojure Functional Programming & JVM Backend Development 课中编写并运行代码吗?

能。每节 Clojure Functional Programming & JVM Backend Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 next.jdbc 连接数据库
  2. 执行 CRUD 操作
  3. 数据库迁移与架构管理
  4. 连接池与事务
← 返回 Clojure Functional Programming & JVM Backend Development