Lightweight 0.20261105.1
Loading...
Searching...
No Matches
SqlServerDependentObjects.hpp
1// SPDX-License-Identifier: Apache-2.0
2//
3// Internal to the Lightweight library (not installed): scripts the SQL Server objects
4// that prevent changing a column's type, so `MigrationManager::UnicodeUpgradeTables`
5// can drop them, alter the columns and recreate them exactly.
6//
7// SQL Server refuses `ALTER COLUMN` from CHAR/VARCHAR to NCHAR/NVARCHAR while the column
8// is used by a primary-key, unique, foreign-key, default or check constraint, an index,
9// or user-created statistics. The catalog (`sys.*`) is read once up front; every object
10// is recreated under its original name with its original definition.
11
12#pragma once
13
14#include <string>
15#include <vector>
16
17namespace Lightweight
18{
19
20class SqlStatement;
21
22namespace detail
23{
24
25 /// One column whose type is about to change.
26 struct ColumnToRetype
27 {
28 /// Schema of the table; empty means the connection's default schema.
29 std::string schema;
30 /// Table name.
31 std::string table;
32 /// Column name.
33 std::string column;
34 };
35
36 /// The SQL needed around an `ALTER COLUMN` batch: statements to run before it (in
37 /// order), statements to run after it (in order), and a human-readable line per object.
38 struct DependentObjectScript
39 {
40 /// Drops every dependent object, foreign keys first.
41 std::vector<std::string> drop;
42 /// Recreates every dependent object, referenced keys before the foreign keys.
43 std::vector<std::string> recreate;
44 /// One description per object, e.g. "PRIMARY KEY PK_users on dbo.users".
45 std::vector<std::string> descriptions;
46 /// True when a recreated index has a filter, which SQL Server only accepts with
47 /// `ANSI_WARNINGS ON`.
48 bool needsAnsiWarnings = false;
49 };
50
51 /// Reads the SQL Server catalog and scripts the objects that depend on `columns`.
52 /// Objects that cannot be scripted safely (schema-bound views or functions, computed
53 /// columns, non-rowstore indexes) make it throw `std::runtime_error` naming them,
54 /// before anything has been changed.
55 /// @param stmt Statement on a SQL Server connection.
56 /// @param columns Columns about to be retyped.
57 /// @return The drop / recreate script.
58 [[nodiscard]] DependentObjectScript ScriptSqlServerDependentObjects(SqlStatement& stmt,
59 std::vector<ColumnToRetype> const& columns);
60
61} // namespace detail
62
63} // namespace Lightweight