Add a new value to an existing ENUM type
(
conn: &mut Connection,
type_name: &str,
new_value: &str,
before_value: Option<&str>,
after_value: Option<&str>,
)
| 113 | |
| 114 | /// Add a new value to an existing ENUM type |
| 115 | pub fn add_enum_value( |
| 116 | conn: &mut Connection, |
| 117 | type_name: &str, |
| 118 | new_value: &str, |
| 119 | before_value: Option<&str>, |
| 120 | after_value: Option<&str>, |
| 121 | ) -> Result<()> { |
| 122 | let tx = conn.transaction()?; |
| 123 | |
| 124 | // Get type OID |
| 125 | let type_oid: i32 = tx.query_row( |
| 126 | "SELECT type_oid FROM __pgsqlite_enum_types WHERE type_name = ?1", |
| 127 | [type_name], |
| 128 | |row| row.get(0), |
| 129 | )?; |
| 130 | |
| 131 | // Calculate sort order |
| 132 | let sort_order = if let Some(before) = before_value { |
| 133 | // Insert before specified value |
| 134 | let before_order: f64 = tx.query_row( |
| 135 | "SELECT sort_order FROM __pgsqlite_enum_values |
| 136 | WHERE type_oid = ?1 AND label = ?2", |
| 137 | params![type_oid, before], |
| 138 | |row| row.get(0), |
| 139 | )?; |
| 140 | |
| 141 | // Get previous value's sort order (if exists) |
| 142 | let prev_order: Option<f64> = tx.query_row( |
| 143 | "SELECT MAX(sort_order) FROM __pgsqlite_enum_values |
| 144 | WHERE type_oid = ?1 AND sort_order < ?2", |
| 145 | params![type_oid, before_order], |
| 146 | |row| row.get(0), |
| 147 | ).ok(); |
| 148 | |
| 149 | // Place halfway between previous and before value |
| 150 | match prev_order { |
| 151 | Some(prev) => (prev + before_order) / 2.0, |
| 152 | None => before_order / 2.0, |
| 153 | } |
| 154 | } else if let Some(after) = after_value { |
| 155 | // Insert after specified value |
| 156 | let after_order: f64 = tx.query_row( |
| 157 | "SELECT sort_order FROM __pgsqlite_enum_values |
| 158 | WHERE type_oid = ?1 AND label = ?2", |
| 159 | params![type_oid, after], |
| 160 | |row| row.get(0), |
| 161 | )?; |
| 162 | |
| 163 | // Get next value's sort order (if exists) |
| 164 | let next_order: Option<f64> = tx.query_row( |
| 165 | "SELECT MIN(sort_order) FROM __pgsqlite_enum_values |
| 166 | WHERE type_oid = ?1 AND sort_order > ?2", |
| 167 | params![type_oid, after_order], |
| 168 | |row| row.get(0), |
| 169 | ).ok(); |
| 170 | |
| 171 | // Place halfway between after value and next |
| 172 | match next_order { |