|
56 | 56 | /// - ``select(_:as:)-3o8qw`` |
57 | 57 | /// - ``select(literal:as:)`` |
58 | 58 | /// - ``select(sql:arguments:as:)`` |
| 59 | +/// - ``selectID()`` |
59 | 60 | /// - ``selectPrimaryKey(as:)`` |
60 | 61 | /// |
61 | 62 | /// ### Batch Delete |
@@ -237,7 +238,7 @@ extension QueryInterfaceRequest: SelectionRequest { |
237 | 238 | select(sqlLiteral, as: type) |
238 | 239 | } |
239 | 240 |
|
240 | | - /// Selects the primary key. |
| 241 | + /// Returns a request that selects the primary key. |
241 | 242 | /// |
242 | 243 | /// All primary keys are supported: |
243 | 244 | /// |
@@ -281,6 +282,46 @@ extension QueryInterfaceRequest: SelectionRequest { |
281 | 282 | .asRequest(of: PrimaryKey.self) |
282 | 283 | } |
283 | 284 |
|
| 285 | + /// Returns a request that selects the primary key. |
| 286 | + /// |
| 287 | + /// For example: |
| 288 | + /// |
| 289 | + /// ```swift |
| 290 | + /// // SELECT id FROM player WHERE ... |
| 291 | + /// let request = try Player.filter(...).selectID() |
| 292 | + /// ``` |
| 293 | + /// |
| 294 | + /// **Important**: if the record type has an `ID` type that is an |
| 295 | + /// optional, such as `Int64?`, it is recommended to prefer |
| 296 | + /// ``selectPrimaryKey(as:)`` instead: |
| 297 | + /// |
| 298 | + /// ```swift |
| 299 | + /// struct Player: Identifiable { |
| 300 | + /// var id: Int64? |
| 301 | + /// } |
| 302 | + /// |
| 303 | + /// // NOT RECOMMENDED: Set<Int64?> |
| 304 | + /// let ids = try Player.filter(...) |
| 305 | + /// .selectID() |
| 306 | + /// .fetchSet(db) |
| 307 | + /// |
| 308 | + /// // BETTER: Set<Int64> |
| 309 | + /// let ids = try Player.filter(...) |
| 310 | + /// .selectPrimaryKey(as: Int64.self) |
| 311 | + /// .fetchSet(db) |
| 312 | + /// ``` |
| 313 | + public func selectID() -> QueryInterfaceRequest<RowDecoder.ID> |
| 314 | + where RowDecoder: Identifiable |
| 315 | + { |
| 316 | + selectWhenConnected { db in |
| 317 | + let primaryKey = try db.primaryKey(self.databaseTableName) |
| 318 | + GRDBPrecondition( |
| 319 | + primaryKey.columns.count == 1, |
| 320 | + "selectID requires a single-column primary key in the table \(self.databaseTableName)") |
| 321 | + return [Column(primaryKey.columns[0])] |
| 322 | + }.asRequest(of: RowDecoder.ID.self) |
| 323 | + } |
| 324 | + |
284 | 325 | public func annotatedWhenConnected( |
285 | 326 | with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]) |
286 | 327 | -> Self |
|
0 commit comments