diff --git a/Documentation/WhyAdoptGRDB.md b/Documentation/WhyAdoptGRDB.md index 8a56e72d0..6bf9019c7 100644 --- a/Documentation/WhyAdoptGRDB.md +++ b/Documentation/WhyAdoptGRDB.md @@ -10,7 +10,7 @@ We'll start with a few [core principles](#core-principles), so that you see wher ### It is generally easier to access a database through "record types". -This is because a database row is not an easy type to deal with, and will never be, compared to a regular model. `player.name` looks and feels more natural than `playerRow[nameColumn]`, doesn't it? +This is because a database row is not an easy type to deal with, and will never be, compared to a regular model. `player.name` looks and feels more natural than `playerRow["name"]`, doesn't it? The reputation of "active records" and ORMs has been tarnished by the recent focus on immutability, memory safety, and functional idioms that comes with languages like Swift and Rust. Features of 1st-generation records such as auto-updating, uniquing, lazy loading of relations, etc. are now considered ill-advised, if not plain harmful because of the multi-threading headaches they cause. @@ -39,7 +39,7 @@ This means that dealing with servers, MySQL, or PostgreSQL is out of scope. GRDB Focusing on SQLite and applications has allowed GRDB to build features usually only found in company-sponsored libraries: migrations, record comparison, database observation, multi-threading safety, table view animations, support for reactive streams... -Some will call GRDB "opinionated", or "bloated". Well, the bet of GRDB is that developers can take great profit from a library that provides efficient and community-tested solutions to existing problems. For example, one can not address the multithreading difficulties of Core Data or Realm without looking at database concurrency and records straight in the face. +The bet of GRDB is that developers can take great profit from a library that provides efficient and community-tested solutions to existing problems. For example, one can not address the multithreading difficulties of Core Data or Realm without looking at database concurrency and records straight in the face. Since you don't have to take my words for granted, we'll now see how GRDB actually solves common problems that developers face with other database libraries. @@ -51,7 +51,7 @@ What is the purpose of the above principles, if not providing solutions to diffi ### Allow any Swift struct or class to become a database record -Most libraries that provide record types want you to subclass a root class: NSManagedObject, Realm.Object, FCModel. +Most libraries that provide record types want you to subclass a root class: [NSManagedObject](https://developer.apple.com/documentation/coredata/nsmanagedobject), [Realm.Object](https://www.realm.io/docs/swift/latest), [FCModel](https://github.com/marcoarment/FCModel). The main problem with those root classes is that they are classes. You can't define records from plain Swift structs, and leverage all advantages of Swift value types: immutability, multi-threading safety, etc. @@ -69,7 +69,7 @@ By adopting the [FetchableRecord] protocol, places can be loaded from SQL reques ```swift extension Place: FetchableRecord { ... } -let places = try Place.fetchAll(db, "SELECT * FROM places") // [Place] +let places = try Place.fetchAll(db, "SELECT * FROM place") // [Place] ``` Add the [TableRecord] protocol, and SQL requests are generated for you: @@ -86,7 +86,7 @@ extension Place: PersistableRecord { ... } try place.delete(db) ``` -Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with database change notifications, with many advantages. +Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with **database change notifications**, with many advantages. ### Allow database records to cross threads @@ -129,16 +129,16 @@ First, notifications only come from database changes safely saved on disk. This Next, you choose the dispatch queue on which notifications happen. It can be on the special "writer queue", which allows you to process changes before any other thread has any opportunity to perform further database modifications. But notifications can also happen on the queue of your choice (generally the main queue, by default, as in the example above). Of course, GRDB makes sure notifications happen in the same order as database transactions. -Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, and even SQL triggers. +Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, and even SQL triggers. GRDB roots its notification system in the rock-solid SQLite itself, so that high-level requests and raw SQL queries are equally supported. ### Non-blocking database reads -GRDB ships with two ways to access databases, [database queues](https://github.com/groue/GRDB.swift/blob/master/README.md#database-queues) and [pools](https://github.com/groue/GRDB.swift/blob/master/README.md#database-pools). +GRDB ships with two ways to access databases, [database queues](../README.md#database-queues) and [pools](../README.md#database-pools). Database queues look a lot like FMDB's [FMDatabaseQueue](https://github.com/ccgus/fmdb#using-fmdatabasequeue-and-thread-safety): they serialize database accesses in a serial dispatch queue. There is never more than one thread that is accessing the database. This means that a long running database transaction that happens in a background thread, such as the synchronization of your local database from a remote server, can block your UI. As long as the queue is busy, the main thread can't fetch the values it wants to display on screen. -[Database pools](https://github.com/groue/GRDB.swift/blob/master/README.md#database-pools) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured). +[Database pools](../README.md#database-pools) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured). ### Strong and clear multi-threading guarantees @@ -162,9 +162,9 @@ The more threats are handled by the application, the more skilled and careful a | GRDB's DatabaseQueue | :white_check_mark: | :white_check_mark: | Handled by the application | UI is blocked | | GRDB's DatabasePool | :white_check_mark: | :white_check_mark: | Handled by the application | :white_check_mark: (as long as the maximum number of readers has not been reached) | -I had to omit Realm and FCModel from the list, because I don't know them well enough. Yet I'd bet that Realm shares some behaviors with Core Data, and FCModel shares some behaviors with FMDatabaseQueue. +I had to omit [Realm] and [FCModel] from the list, because I don't know them well enough. Yet I'd bet that Realm shares some behaviors with Core Data, and FCModel shares some behaviors with FMDatabaseQueue. -We can see that the threat of conflicts is *always* left to the application. Core Data provides conflict policies, but no one can pretend that they are easy to use or test. This is an argument for leaving the application 100% responsible for conflict handling, in hope that simple ones can be handled in a simple way. A weaker way to say this is that conflict handling at the library level can wait :sweat_smile:. +We can see that the threat of conflicts is *always* left to the application. Core Data provides conflict policies, but no one can pretend that they are easy to plan, use, or test. This is an argument for leaving the application 100% responsible for conflict handling, in hope that simple ones can be handled in a simple way. Finally, raw FMDatabase, SQLite.swift, and Core Data are the hardest tools, and you'd better be a very skilled developer in order to use them properly. @@ -175,47 +175,62 @@ For further information about GRDB concurrency, check its detailed [Concurrency SQL is a weird language. Born in the 70s, easy to [misuse](https://xkcd.com/327/), feared by some developers, despised by others, and yet wonderfully concise and powerful. -GRDB records can generate SQL for you: +GRDB [query interface] and [associations] can generate SQL for you: ```swift -// SELECT * FROM players ORDER BY score DESC LIMIT 10 +// SELECT * FROM player ORDER BY score DESC LIMIT 10 let bestPlayers: [Player] = try Player .order(scoreColumn.desc) .limit(10) .fetchAll(db) -// SELECT MAX(score) FROM players +// SELECT MAX(score) FROM player let maximumScore: Int? = try Player .select(max(scoreColumn)) .asRequestOf(Int.self) .fetchOne(db) - -// SELECT COUNT(*) FROM players WHERE score = ? -let exAequoCount: Int = try Player - .filter(scoreColumn == maximumScore) - .fetchCount(db) + +// SELECT book.*, author.* +// FROM book +// LEFT JOIN author ON author.id = book.authorId +let request = Book.including(optional: Book.author) +let bookInfos: [BookInfo] = BookInfo.fetchAll(db, request) ``` But you can always switch to SQL when you want to: ```swift let bestPlayers: [Player] = try Player.fetchAll(db, """ - SELECT * FROM players ORDER BY score DESC LIMIT 10 + SELECT * FROM player ORDER BY score DESC LIMIT 10 """) let maximumScore: Int? = try Int.fetchOne(db, """ - SELECT MAX(score) FROM players + SELECT MAX(score) FROM player """) - -let exAequoCount: Int? = try Int.fetchOne(db, """ - SELECT COUNT(*) FROM players WHERE score = ? - """, arguments: [maximumScore]) ``` -In performance-critical sections, you may want to deal with raw database rows, and fetch [lazy cursors](https://github.com/groue/GRDB.swift/blob/master/README.md#cursors) instead of arrays: +Power users can also consume complex joined SQL queries into handy record values, by *adapting* raw database rows to the decoded records (see [Joined Queries Support](#../README.md#joined-queries-support)): ```swift -let rows = try Row.fetchCursor(db, "SELECT id, name, score FROM players") +let bookInfos: [BookInfo] = SQLRequest(""" + SELECT book.*, author.* + FROM book + LEFT JOIN author ON author.id = book.authorId + """) + .adapted { db in + let adapters = try splittingRowAdapters(columnCounts: [ + db.columns(in: "book").count, + db.columns(in: "author").count]) + return ScopeAdapter([ + "book": adapters[0], + "author": adapters[1]]) + } +``` + +In performance-critical sections, you may want to deal with raw database rows, and fetch [lazy cursors](../README.md#cursors) instead of arrays: + +```swift +let rows = try Row.fetchCursor(db, "SELECT id, name, score FROM player") while let row = try rows.next() { let id: Int64 = row[0] let name: String = row[1] @@ -223,7 +238,7 @@ while let row = try rows.next() { } ``` -When you feel like your code clarity would be enhanced by hiding your custom SQL in a dedicated method, you can build [custom requests](https://github.com/groue/GRDB.swift/blob/master/README.md#custom-requests): +When you feel like your code clarity would be enhanced by hiding your custom SQL in a dedicated method, you can build [custom requests](../README.md#custom-requests): ```swift extension Player { @@ -238,8 +253,8 @@ let players = try Player.customRequest(...).fetchAll(db) Those custom requests are welcome in database observation tools like [FetchedRecordsController] and [RxGRDB]: ```swift -Player.customRequest(...) - .rx.fetchAll(in: dbQueue) +Player.customRequest(...).rx + .fetchAll(in: dbQueue) .subscribe(onNext: { players: [Player] in print("Players have changed") }) @@ -253,23 +268,25 @@ And if you happen to maintain an Objective-C application that uses FMDB, checkou Happy GRDB! :gift: -[Concurrency Guide]: https://github.com/groue/GRDB.swift/blob/master/README.md#concurrency +[Concurrency Guide]: ../README.md#concurrency [Core Data]: https://developer.apple.com/documentation/coredata -[DatabasePool]: https://github.com/groue/GRDB.swift/blob/master/README.md#database-pools +[DatabasePool]: ../README.md#database-pools [Diesel]: http://diesel.rs [FCModel]: https://github.com/marcoarment/FCModel -[FetchedRecordsController]: https://github.com/groue/GRDB.swift/blob/master/README.md#fetchedrecordscontroller +[FetchedRecordsController]: ../README.md#fetchedrecordscontroller [Fluent]: https://github.com/vapor/fluent [FMDB]: http://github.com/ccgus/fmdb [GRDB]: http://github.com/groue/GRDB.swift [GRDBObjc]: http://github.com/groue/GRDBObjc -[PersistableRecord]: https://github.com/groue/GRDB.swift/blob/master/README.md#records +[PersistableRecord]: ../README.md#records [Realm]: http://realm.io -[FetchableRecord]: https://github.com/groue/GRDB.swift/blob/master/README.md#records +[FetchableRecord]: ../README.md#records [RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB [RxSwift]: https://github.com/ReactiveX/RxSwift [SQLite.swift]: http://github.com/stephencelis/SQLite.swift [StORM]: https://www.perfect.org/docs/StORM.html [Swift-Kuery]: http://github.com/IBM-Swift/Swift-Kuery -[TableRecord]: https://github.com/groue/GRDB.swift/blob/master/README.md#records -[TransactionObserver]: https://github.com/groue/GRDB.swift/blob/master/README.md#transactionobserver-protocol +[TableRecord]: ../README.md#records +[TransactionObserver]: ../README.md#transactionobserver-protocol +[query interface]: ../README.md#the-query-interface +[associations]: AssociationsBasics.md