sqlx_core/config/migrate.rs
1use std::collections::BTreeSet;
2
3/// Configuration for migrations when executed using `sqlx::migrate!()` or through `sqlx-cli`.
4///
5/// ### Note
6/// A manually constructed [`Migrator`][crate::migrate::Migrator] will not be aware of these
7/// configuration options. We recommend using `sqlx::migrate!()` instead.
8///
9/// ### Warning: Potential Data Loss or Corruption!
10/// Many of these options, if changed after migrations are set up,
11/// can result in data loss or corruption of a production database
12/// if the proper precautions are not taken.
13///
14/// Be sure you know what you are doing and that you read all relevant documentation _thoroughly_.
15#[derive(Debug, Default)]
16#[cfg_attr(
17 feature = "sqlx-toml",
18 derive(serde::Deserialize),
19 serde(default, rename_all = "kebab-case", deny_unknown_fields)
20)]
21pub struct Config {
22 /// Specify the names of schemas to create if they don't already exist.
23 ///
24 /// This is done before checking the existence of the migrations table
25 /// (`_sqlx_migrations` or overridden `table_name` below) so that it may be placed in
26 /// one of these schemas.
27 ///
28 /// ### Example
29 /// `sqlx.toml`:
30 /// ```toml
31 /// [migrate]
32 /// create-schemas = ["foo"]
33 /// ```
34 pub create_schemas: BTreeSet<Box<str>>,
35
36 /// Override the name of the table used to track executed migrations.
37 ///
38 /// May be schema-qualified and/or contain quotes. Defaults to `_sqlx_migrations`.
39 ///
40 /// Potentially useful for multi-tenant databases.
41 ///
42 /// ### Warning: Potential Data Loss or Corruption!
43 /// Changing this option for a production database will likely result in data loss or corruption
44 /// as the migration machinery will no longer be aware of what migrations have been applied
45 /// and will attempt to re-run them.
46 ///
47 /// You should create the new table as a copy of the existing migrations table (with contents!),
48 /// and be sure all instances of your application have been migrated to the new
49 /// table before deleting the old one.
50 ///
51 /// ### Example
52 /// `sqlx.toml`:
53 /// ```toml
54 /// [migrate]
55 /// # Put `_sqlx_migrations` in schema `foo`
56 /// table-name = "foo._sqlx_migrations"
57 /// ```
58 pub table_name: Option<Box<str>>,
59
60 /// Override the directory used for migrations files.
61 ///
62 /// Relative to the crate root for `sqlx::migrate!()`, or the current directory for `sqlx-cli`.
63 pub migrations_dir: Option<Box<str>>,
64
65 /// Specify characters that should be ignored when hashing migrations.
66 ///
67 /// Any characters contained in the given array will be dropped when a migration is hashed.
68 ///
69 /// ### Warning: May Change Hashes for Existing Migrations
70 /// Changing the characters considered in hashing migrations will likely
71 /// change the output of the hash.
72 ///
73 /// This may require manual rectification for deployed databases.
74 ///
75 /// ### Example: Ignore Carriage Return (`<CR>` | `\r`)
76 /// Line ending differences between platforms can result in migrations having non-repeatable
77 /// hashes. The most common culprit is the carriage return (`<CR>` | `\r`), which Windows
78 /// uses in its line endings alongside line feed (`<LF>` | `\n`), often written `CRLF` or `\r\n`,
79 /// whereas Linux and macOS use only line feeds.
80 ///
81 /// `sqlx.toml`:
82 /// ```toml
83 /// [migrate]
84 /// ignored-chars = ["\r"]
85 /// ```
86 ///
87 /// For projects using Git, this can also be addressed using [`.gitattributes`]:
88 ///
89 /// ```text
90 /// # Force newlines in migrations to be line feeds on all platforms
91 /// migrations/*.sql text eol=lf
92 /// ```
93 ///
94 /// This may require resetting or re-checking out the migrations files to take effect.
95 ///
96 /// [`.gitattributes`]: https://git-scm.com/docs/gitattributes
97 ///
98 /// ### Example: Ignore all Whitespace Characters
99 /// To make your migrations amenable to reformatting, you may wish to tell SQLx to ignore
100 /// _all_ whitespace characters in migrations.
101 ///
102 /// ##### Warning: Beware Syntactically Significant Whitespace!
103 /// If your migrations use string literals or quoted identifiers which contain whitespace,
104 /// this configuration will cause the migration machinery to ignore some changes to these.
105 /// This may result in a mismatch between the development and production versions of
106 /// your database.
107 ///
108 /// `sqlx.toml`:
109 /// ```toml
110 /// [migrate]
111 /// # Ignore common whitespace characters when hashing
112 /// ignored-chars = [" ", "\t", "\r", "\n"] # Space, tab, CR, LF
113 /// ```
114 // Likely lower overhead for small sets than `HashSet`.
115 pub ignored_chars: BTreeSet<char>,
116
117 /// Specify what to do with a `.sql` file in the migrations directory whose name does not
118 /// parse as `<VERSION>_<DESCRIPTION>.sql`.
119 ///
120 /// Defaults to `error`, since such a file is usually a migration that was named incorrectly
121 /// and would otherwise be skipped without any indication that it did not run.
122 ///
123 /// Set this to `warn` or `ignore` if you deliberately keep other SQL scripts alongside your
124 /// migrations. Files that don't end in `.sql` are always ignored regardless of this setting.
125 ///
126 /// ### Example
127 /// `sqlx.toml`:
128 /// ```toml
129 /// [migrate]
130 /// unrecognized-sql-files = "warn"
131 /// ```
132 pub unrecognized_sql_files: UnrecognizedSqlFiles,
133
134 /// Specify default options for new migrations created with `sqlx migrate add`.
135 pub defaults: MigrationDefaults,
136}
137
138/// What to do with a `.sql` file in the migrations directory that doesn't parse as
139/// `<VERSION>_<DESCRIPTION>.sql`.
140#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
141#[cfg_attr(
142 feature = "sqlx-toml",
143 derive(serde::Deserialize),
144 serde(rename_all = "snake_case")
145)]
146pub enum UnrecognizedSqlFiles {
147 /// Return an error naming the file. The default.
148 #[default]
149 Error,
150
151 /// Log a warning naming the file and skip it.
152 Warn,
153
154 /// Skip the file without any output.
155 Ignore,
156}
157
158#[derive(Debug, Default)]
159#[cfg_attr(
160 feature = "sqlx-toml",
161 derive(serde::Deserialize),
162 serde(default, rename_all = "kebab-case")
163)]
164pub struct MigrationDefaults {
165 /// Specify the default type of migration that `sqlx migrate add` should create by default.
166 ///
167 /// ### Example: Use Reversible Migrations by Default
168 /// `sqlx.toml`:
169 /// ```toml
170 /// [migrate.defaults]
171 /// migration-type = "reversible"
172 /// ```
173 pub migration_type: DefaultMigrationType,
174
175 /// Specify the default scheme that `sqlx migrate add` should use for version integers.
176 ///
177 /// ### Example: Use Sequential Versioning by Default
178 /// `sqlx.toml`:
179 /// ```toml
180 /// [migrate.defaults]
181 /// migration-versioning = "sequential"
182 /// ```
183 pub migration_versioning: DefaultVersioning,
184}
185
186/// The default type of migration that `sqlx migrate add` should create by default.
187#[derive(Debug, Default, PartialEq, Eq)]
188#[cfg_attr(
189 feature = "sqlx-toml",
190 derive(serde::Deserialize),
191 serde(rename_all = "snake_case")
192)]
193pub enum DefaultMigrationType {
194 /// Create the same migration type as that of the latest existing migration,
195 /// or `Simple` otherwise.
196 #[default]
197 Inferred,
198
199 /// Create non-reversible migrations (`<VERSION>_<DESCRIPTION>.sql`) by default.
200 Simple,
201
202 /// Create reversible migrations (`<VERSION>_<DESCRIPTION>.up.sql` and `[...].down.sql`) by default.
203 Reversible,
204}
205
206/// The default scheme that `sqlx migrate add` should use for version integers.
207#[derive(Debug, Default, PartialEq, Eq)]
208#[cfg_attr(
209 feature = "sqlx-toml",
210 derive(serde::Deserialize),
211 serde(rename_all = "snake_case")
212)]
213pub enum DefaultVersioning {
214 /// Infer the versioning scheme from existing migrations:
215 ///
216 /// * If the versions of the last two migrations differ by `1`, infer `Sequential`.
217 /// * If only one migration exists and has version `1`, infer `Sequential`.
218 /// * Otherwise, infer `Timestamp`.
219 #[default]
220 Inferred,
221
222 /// Use UTC timestamps for migration versions.
223 ///
224 /// This is the recommended versioning format as it's less likely to collide when multiple
225 /// developers are creating migrations on different branches.
226 ///
227 /// The exact timestamp format is unspecified.
228 Timestamp,
229
230 /// Use sequential integers for migration versions.
231 Sequential,
232}
233
234#[cfg(feature = "migrate")]
235impl Config {
236 pub fn migrations_dir(&self) -> &str {
237 self.migrations_dir.as_deref().unwrap_or("migrations")
238 }
239
240 pub fn table_name(&self) -> &str {
241 self.table_name.as_deref().unwrap_or("_sqlx_migrations")
242 }
243
244 pub fn to_resolve_config(&self) -> crate::migrate::ResolveConfig {
245 let mut config = crate::migrate::ResolveConfig::new();
246 config.ignore_chars(self.ignored_chars.iter().copied());
247 config.unrecognized_sql_files(self.unrecognized_sql_files);
248 config
249 }
250}