mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-25 04:07:47 +00:00
Validation
This commit is contained in:
1 parent
4ec2964ddf
commit
9ee0d200ac
1 file changed
+36
@@ -980,9 +980,11 @@ RowModel methods can throw [DatabaseError](#error-handling) and also specific er
|
||||
Based on those facts, here are a few hints:
|
||||
|
||||
- [Autoincrement](#autoincrement)
|
||||
- [Validation](#validation)
|
||||
- [Default Values](#default-values)
|
||||
- [INSERT OR REPLACE](#insert-or-replace)
|
||||
|
||||
|
||||
#### Autoincrement
|
||||
|
||||
**For "autoincremented" ids**, declare your id column as INTEGER PRIMARY KEY, and declare a RowID primary key:
|
||||
@@ -1025,6 +1027,40 @@ person.id // some value
|
||||
```
|
||||
|
||||
|
||||
#### Validation
|
||||
|
||||
RowModel does not provide any built-in validation.
|
||||
|
||||
You can use some external library such as [GRValidation](https://github.com/groue/GRValidation) in the update() and insert() methods:
|
||||
|
||||
```swift
|
||||
class Person : RowModel, Validable {
|
||||
var name: String?
|
||||
|
||||
override func update(db: Database) throws {
|
||||
// Validate before update
|
||||
try validate()
|
||||
try super.update(db)
|
||||
}
|
||||
|
||||
override func insert(db: Database) throws {
|
||||
// Validate before insert
|
||||
try validate()
|
||||
try super.insert(db)
|
||||
}
|
||||
|
||||
func validate() throws {
|
||||
// Name should not be nil
|
||||
try validate(property: "name", with: name >>> ValidationNotNil())
|
||||
}
|
||||
}
|
||||
|
||||
// fatal error: 'try!' expression unexpectedly raised an error:
|
||||
// Invalid <Person name:nil>: name should not be nil.
|
||||
try! Person(name: nil).save(db)
|
||||
```
|
||||
|
||||
|
||||
#### Default Values
|
||||
|
||||
**Avoid default values in table declarations.** RowModel doesn't know about them, and those default values won't be present in a row model after it has been inserted.
|
||||
|
||||
Reference in new issue
Block a user