mirror of
https://github.com/Ranchero-Software/NetNewsWire
synced 2026-11-30 17:29:23 +00:00
Complete authors schema migration. Read and write to JSON authors column. Delete old tables and indexes.
This commit is contained in:
1 parent
0c3245c41b
commit
b811981f45
8 files changed
+47
-234
No files matched your search
@@ -406,7 +406,6 @@ public struct ArticleChanges: Sendable {
|
||||
}
|
||||
articlesTable.deleteArticlesNotInSubscribedToFeedIDs(subscribedToFeedIDs)
|
||||
articlesTable.deleteOldStatuses()
|
||||
articlesTable.deleteOrphanedAuthorsLookupRows()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -419,15 +418,10 @@ private extension ArticlesDatabase {
|
||||
|
||||
CREATE TABLE if not EXISTS statuses (articleID TEXT NOT NULL PRIMARY KEY, read BOOL NOT NULL DEFAULT 0, starred BOOL NOT NULL DEFAULT 0, dateArrived DATE NOT NULL DEFAULT 0);
|
||||
|
||||
CREATE TABLE if not EXISTS authors (authorID TEXT NOT NULL PRIMARY KEY, name TEXT, url TEXT, avatarURL TEXT, emailAddress TEXT);
|
||||
CREATE TABLE if not EXISTS authorsLookup (authorID TEXT NOT NULL, articleID TEXT NOT NULL, PRIMARY KEY(authorID, articleID));
|
||||
|
||||
CREATE INDEX if not EXISTS articles_feedID_datePublished_articleID on articles (feedID, datePublished, articleID);
|
||||
|
||||
CREATE INDEX if not EXISTS statuses_starred_index on statuses (starred);
|
||||
|
||||
CREATE INDEX if not EXISTS authorsLookup_articleID on authorsLookup (articleID);
|
||||
|
||||
CREATE VIRTUAL TABLE if not EXISTS search using fts4(title, body);
|
||||
|
||||
CREATE TRIGGER if not EXISTS articles_after_delete_trigger_delete_search_text after delete on articles begin delete from search where rowid = OLD.searchRowID; end;
|
||||
|
||||
@@ -21,7 +21,6 @@ final class ArticlesTable: DatabaseTable, Sendable {
|
||||
private let queue: DatabaseQueue
|
||||
private let statusesTable: StatusesTable
|
||||
private let searchTable: SearchTable
|
||||
private let authorsLookupTable: DatabaseLookupTable
|
||||
private let retentionStyle: ArticlesDatabase.RetentionStyle
|
||||
private let articlesCache = OSAllocatedUnfairLock(initialState: [String: Article]())
|
||||
|
||||
@@ -38,9 +37,6 @@ final class ArticlesTable: DatabaseTable, Sendable {
|
||||
self.statusesTable = StatusesTable(queue: queue)
|
||||
self.retentionStyle = retentionStyle
|
||||
|
||||
let authorsTable = AuthorsTable(name: DatabaseTableName.authors)
|
||||
self.authorsLookupTable = DatabaseLookupTable(name: DatabaseTableName.authorsLookup, objectIDKey: DatabaseKey.articleID, relatedObjectIDKey: DatabaseKey.authorID, relatedTable: authorsTable, relationshipName: RelationshipName.authors)
|
||||
|
||||
self.searchTable = SearchTable(queue: queue)
|
||||
self.searchTable.articlesTable = self
|
||||
|
||||
@@ -674,18 +670,6 @@ final class ArticlesTable: DatabaseTable, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete `authorsLookup` rows whose article no longer exists, then delete `authors`
|
||||
/// rows that are no longer referenced by any `authorsLookup` row.
|
||||
func deleteOrphanedAuthorsLookupRows() {
|
||||
queue.runInTransaction { databaseResult in
|
||||
guard let database = databaseResult.database else {
|
||||
return
|
||||
}
|
||||
database.executeUpdate("delete from authorsLookup where articleID not in (select articleID from articles);", withArgumentsIn: nil)
|
||||
database.executeUpdate("delete from authors where authorID not in (select distinct authorID from authorsLookup);", withArgumentsIn: nil)
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete articles from feeds that are no longer in the current set of subscribed-to feeds.
|
||||
/// This deletes from the articles and articleStatuses tables,
|
||||
/// and, via a trigger, it also deletes from the search index.
|
||||
@@ -793,8 +777,7 @@ nonisolated private extension ArticlesTable {
|
||||
}
|
||||
|
||||
func articlesWithResultSet(_ resultSet: FMResultSet, _ database: FMDatabase) -> Set<Article> {
|
||||
var cachedArticles = Set<Article>()
|
||||
var fetchedArticles = Set<Article>()
|
||||
var articles = Set<Article>()
|
||||
|
||||
while resultSet.next() {
|
||||
|
||||
@@ -803,8 +786,8 @@ nonisolated private extension ArticlesTable {
|
||||
continue
|
||||
}
|
||||
|
||||
if let article = articlesCache.withLock({ $0[articleID] }) {
|
||||
cachedArticles.insert(article)
|
||||
if let cachedArticle = articlesCache.withLock({ $0[articleID] }) {
|
||||
articles.insert(cachedArticle)
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -818,32 +801,12 @@ nonisolated private extension ArticlesTable {
|
||||
guard let article = Article(accountID: accountID, row: resultSet, status: status) else {
|
||||
continue
|
||||
}
|
||||
fetchedArticles.insert(article)
|
||||
articlesCache.withLock { $0[articleID] = article }
|
||||
articles.insert(article)
|
||||
}
|
||||
|
||||
resultSet.close()
|
||||
|
||||
if fetchedArticles.isEmpty {
|
||||
return cachedArticles
|
||||
}
|
||||
|
||||
// Fetch authors for non-cached articles. (Articles from the cache already have authors.)
|
||||
let fetchedArticleIDs = fetchedArticles.articleIDs()
|
||||
let authorsMap = authorsLookupTable.fetchRelatedObjects(for: fetchedArticleIDs, in: database)
|
||||
let articlesWithFetchedAuthors = fetchedArticles.map { (article) -> Article in
|
||||
if let authors = authorsMap?.authors(for: article.articleID) {
|
||||
return article.byAdding(authors)
|
||||
}
|
||||
return article
|
||||
}
|
||||
|
||||
// Add fetchedArticles to cache, now that they have attached authors.
|
||||
articlesCache.withLock { articlesCache in
|
||||
for article in articlesWithFetchedAuthors {
|
||||
articlesCache[article.articleID] = article
|
||||
}
|
||||
}
|
||||
|
||||
return cachedArticles.union(articlesWithFetchedAuthors)
|
||||
return articles
|
||||
}
|
||||
|
||||
func fetchArticlesWithWhereClause(_ database: FMDatabase, whereClause: String, parameters: [AnyObject]) -> Set<Article> {
|
||||
@@ -1021,41 +984,11 @@ nonisolated private extension ArticlesTable {
|
||||
}
|
||||
|
||||
func saveNewArticles(_ articles: Set<Article>, _ database: FMDatabase) {
|
||||
saveRelatedObjectsForNewArticles(articles, database)
|
||||
|
||||
if let databaseDictionaries = articles.databaseDictionaries() {
|
||||
insertRows(databaseDictionaries, insertType: .orReplace, in: database)
|
||||
}
|
||||
}
|
||||
|
||||
func saveRelatedObjectsForNewArticles(_ articles: Set<Article>, _ database: FMDatabase) {
|
||||
let databaseObjects = articles.databaseObjects()
|
||||
authorsLookupTable.saveRelatedObjects(for: databaseObjects, in: database)
|
||||
insertRows(articles.databaseDictionaries(), insertType: .orReplace, in: database)
|
||||
}
|
||||
|
||||
// MARK: - Updating Existing Articles
|
||||
|
||||
func articlesWithRelatedObjectChanges<T>(_ comparisonKeyPath: KeyPath<Article, Set<T>?>, _ updatedArticles: Set<Article>, _ fetchedArticles: [String: Article]) -> Set<Article> {
|
||||
return updatedArticles.filter { (updatedArticle) -> Bool in
|
||||
if let fetchedArticle = fetchedArticles[updatedArticle.articleID] {
|
||||
return updatedArticle[keyPath: comparisonKeyPath] != fetchedArticle[keyPath: comparisonKeyPath]
|
||||
}
|
||||
assertionFailure("Expected to find matching fetched article.")
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func updateRelatedObjects<T>(_ comparisonKeyPath: KeyPath<Article, Set<T>?>, _ updatedArticles: Set<Article>, _ fetchedArticles: [String: Article], _ lookupTable: DatabaseLookupTable, _ database: FMDatabase) {
|
||||
let articlesWithChanges = articlesWithRelatedObjectChanges(comparisonKeyPath, updatedArticles, fetchedArticles)
|
||||
if !articlesWithChanges.isEmpty {
|
||||
lookupTable.saveRelatedObjects(for: articlesWithChanges.databaseObjects(), in: database)
|
||||
}
|
||||
}
|
||||
|
||||
func saveUpdatedRelatedObjects(_ updatedArticles: Set<Article>, _ fetchedArticles: [String: Article], _ database: FMDatabase) {
|
||||
updateRelatedObjects(\Article.authors, updatedArticles, fetchedArticles, authorsLookupTable, database)
|
||||
}
|
||||
|
||||
func findUpdatedArticles(_ incomingArticles: Set<Article>, _ fetchedArticlesDictionary: [String: Article]) -> Set<Article>? {
|
||||
let updatedArticles = incomingArticles.filter { (incomingArticle) -> Bool in // 6
|
||||
if let existingArticle = fetchedArticlesDictionary[incomingArticle.articleID] {
|
||||
@@ -1078,8 +1011,6 @@ nonisolated private extension ArticlesTable {
|
||||
}
|
||||
|
||||
func saveUpdatedArticles(_ updatedArticles: Set<Article>, _ fetchedArticles: [String: Article], _ database: FMDatabase) {
|
||||
saveUpdatedRelatedObjects(updatedArticles, fetchedArticles, database)
|
||||
|
||||
for updatedArticle in updatedArticles {
|
||||
saveUpdatedArticle(updatedArticle, fetchedArticles, database)
|
||||
}
|
||||
|
||||
@@ -49,6 +49,8 @@ struct AuthorsSchemaMigration: Sendable {
|
||||
try? await Task.sleep(for: .milliseconds(100))
|
||||
}
|
||||
|
||||
await dropLegacyTables()
|
||||
|
||||
if didLogStart {
|
||||
let elapsed = Date().timeIntervalSince(startTime)
|
||||
Self.logger.info("AuthorsSchemaMigration: finished for \(totalCount, privacy: .public) articles in account \(self.accountID, privacy: .public) — \(elapsed, privacy: .public) seconds")
|
||||
@@ -84,6 +86,19 @@ private extension AuthorsSchemaMigration {
|
||||
}
|
||||
}
|
||||
|
||||
func dropLegacyTables() async {
|
||||
await withCheckedContinuation { continuation in
|
||||
queue.runInDatabase { result in
|
||||
guard let database = try? result.get() else {
|
||||
continuation.resume()
|
||||
return
|
||||
}
|
||||
database.executeStatements("drop index if exists authorsLookup_articleID; drop table if exists authorsLookup; drop table if exists authors;")
|
||||
continuation.resume()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func backfillBatch(_ articleIDs: Set<String>) async {
|
||||
await withCheckedContinuation { continuation in
|
||||
queue.runInDatabase { result in
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
//
|
||||
// AuthorsTable.swift
|
||||
// NetNewsWire
|
||||
//
|
||||
// Created by Brent Simmons on 7/13/17.
|
||||
// Copyright © 2017 Ranchero Software. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import RSDatabase
|
||||
import RSDatabaseObjC
|
||||
import Articles
|
||||
|
||||
// article->authors is a many-to-many relationship.
|
||||
// There’s a lookup table relating authorID and articleID.
|
||||
//
|
||||
// CREATE TABLE if not EXISTS authors (authorID TEXT NOT NULL PRIMARY KEY, name TEXT, url TEXT, avatarURL TEXT, emailAddress TEXT);
|
||||
// CREATE TABLE if not EXISTS authorLookup (authorID TEXT NOT NULL, articleID TEXT NOT NULL, PRIMARY KEY(authorID, articleID));
|
||||
|
||||
final class AuthorsTable: DatabaseRelatedObjectsTable, Sendable {
|
||||
let name: String
|
||||
let databaseIDKey = DatabaseKey.authorID
|
||||
let cache = DatabaseObjectCache()
|
||||
|
||||
init(name: String) {
|
||||
self.name = name
|
||||
}
|
||||
|
||||
// MARK: - DatabaseRelatedObjectsTable
|
||||
|
||||
func objectWithRow(_ row: FMResultSet) -> DatabaseObject? {
|
||||
if let author = Author(row: row) {
|
||||
return author as DatabaseObject
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
+24
-36
@@ -38,8 +38,16 @@ extension Article {
|
||||
let imageURL = row.swiftString(forColumn: DatabaseKey.imageURL)
|
||||
let datePublished = row.date(forColumn: DatabaseKey.datePublished)
|
||||
let dateModified = row.date(forColumn: DatabaseKey.dateModified)
|
||||
let authors = Self.authorsFromRow(row)
|
||||
|
||||
self.init(accountID: accountID, articleID: articleID, feedID: feedID, uniqueID: uniqueID, title: title, contentHTML: contentHTML, contentText: contentText, markdown: markdown, url: url, externalURL: externalURL, summary: summary, imageURL: imageURL, datePublished: datePublished, dateModified: dateModified, authors: nil, status: status)
|
||||
self.init(accountID: accountID, articleID: articleID, feedID: feedID, uniqueID: uniqueID, title: title, contentHTML: contentHTML, contentText: contentText, markdown: markdown, url: url, externalURL: externalURL, summary: summary, imageURL: imageURL, datePublished: datePublished, dateModified: dateModified, authors: authors, status: status)
|
||||
}
|
||||
|
||||
private static func authorsFromRow(_ row: FMResultSet) -> Set<Author>? {
|
||||
guard let json = row.swiftString(forColumn: DatabaseKey.authors), !json.isEmpty, let data = json.data(using: .utf8) else {
|
||||
return nil
|
||||
}
|
||||
return Author.authorsWithJSON(data)
|
||||
}
|
||||
|
||||
convenience init(parsedItem: ParsedItem, maximumDateAllowed: Date, accountID: String, feedID: String, status: ArticleStatus) {
|
||||
@@ -68,13 +76,6 @@ extension Article {
|
||||
}
|
||||
}
|
||||
|
||||
func byAdding(_ authors: Set<Author>) -> Article {
|
||||
if authors.isEmpty {
|
||||
return self
|
||||
}
|
||||
return Article(accountID: self.accountID, articleID: self.articleID, feedID: self.feedID, uniqueID: self.uniqueID, title: self.title, contentHTML: self.contentHTML, contentText: self.contentText, markdown: self.markdown, url: self.rawLink, externalURL: self.rawExternalLink, summary: self.summary, imageURL: self.rawImageLink, datePublished: self.datePublished, dateModified: self.dateModified, authors: authors, status: self.status)
|
||||
}
|
||||
|
||||
func changesFrom(_ existingArticle: Article) -> DatabaseDictionary? {
|
||||
if self == existingArticle {
|
||||
return nil
|
||||
@@ -93,6 +94,14 @@ extension Article {
|
||||
addPossibleStringChangeWithKeyPath(\Article.summary, existingArticle, DatabaseKey.summary, &d)
|
||||
addPossibleStringChangeWithKeyPath(\Article.rawImageLink, existingArticle, DatabaseKey.imageURL, &d)
|
||||
|
||||
if authors != existingArticle.authors {
|
||||
if let authors, !authors.isEmpty, let json = authors.json() {
|
||||
d[DatabaseKey.authors] = json
|
||||
} else {
|
||||
d[DatabaseKey.authors] = ""
|
||||
}
|
||||
}
|
||||
|
||||
// If updated versions of dates are nil, and we have existing dates, keep the existing dates.
|
||||
// This is data that’s good to have, and it’s likely that a feed removing dates is doing so in error.
|
||||
if datePublished != existingArticle.datePublished {
|
||||
@@ -137,9 +146,9 @@ extension Article {
|
||||
}
|
||||
}
|
||||
|
||||
extension Article: @retroactive DatabaseObject {
|
||||
extension Article {
|
||||
|
||||
public func databaseDictionary() -> DatabaseDictionary? {
|
||||
func databaseDictionary() -> DatabaseDictionary {
|
||||
var d = DatabaseDictionary()
|
||||
|
||||
d[DatabaseKey.articleID] = articleID
|
||||
@@ -176,28 +185,11 @@ extension Article: @retroactive DatabaseObject {
|
||||
if let dateModified = dateModified {
|
||||
d[DatabaseKey.dateModified] = dateModified
|
||||
}
|
||||
if let authors, !authors.isEmpty, let json = authors.json() {
|
||||
d[DatabaseKey.authors] = json
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
public var databaseID: String {
|
||||
return articleID
|
||||
}
|
||||
|
||||
public func relatedObjectsWithName(_ name: String) -> [DatabaseObject]? {
|
||||
switch name {
|
||||
case RelationshipName.authors:
|
||||
return databaseObjectArray(with: authors)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
private func databaseObjectArray<T: DatabaseObject>(with objects: Set<T>?) -> [DatabaseObject]? {
|
||||
guard let objects = objects else {
|
||||
return nil
|
||||
}
|
||||
return Array(objects)
|
||||
}
|
||||
}
|
||||
|
||||
extension Set where Element == Article {
|
||||
@@ -214,11 +206,7 @@ extension Set where Element == Article {
|
||||
return d
|
||||
}
|
||||
|
||||
func databaseObjects() -> [DatabaseObject] {
|
||||
return self.map { $0 as DatabaseObject }
|
||||
}
|
||||
|
||||
func databaseDictionaries() -> [DatabaseDictionary]? {
|
||||
return self.compactMap { $0.databaseDictionary() }
|
||||
func databaseDictionaries() -> [DatabaseDictionary] {
|
||||
return self.map { $0.databaseDictionary() }
|
||||
}
|
||||
}
|
||||
@@ -8,24 +8,10 @@
|
||||
|
||||
import Foundation
|
||||
import Articles
|
||||
import RSDatabase
|
||||
import RSDatabaseObjC
|
||||
import RSParser
|
||||
|
||||
// MARK: - DatabaseObject
|
||||
|
||||
extension Author {
|
||||
|
||||
init?(row: FMResultSet) {
|
||||
let authorID = row.swiftString(forColumn: DatabaseKey.authorID)
|
||||
let name = row.swiftString(forColumn: DatabaseKey.name)
|
||||
let url = row.swiftString(forColumn: DatabaseKey.url)
|
||||
let avatarURL = row.swiftString(forColumn: DatabaseKey.avatarURL)
|
||||
let emailAddress = row.swiftString(forColumn: DatabaseKey.emailAddress)
|
||||
|
||||
self.init(authorID: authorID, name: name, url: url, avatarURL: avatarURL, emailAddress: emailAddress)
|
||||
}
|
||||
|
||||
init?(parsedAuthor: ParsedAuthor) {
|
||||
self.init(authorID: nil, name: parsedAuthor.name, url: parsedAuthor.url, avatarURL: parsedAuthor.avatarURL, emailAddress: parsedAuthor.emailAddress)
|
||||
}
|
||||
@@ -39,27 +25,3 @@ extension Author {
|
||||
return authors.isEmpty ? nil: authors
|
||||
}
|
||||
}
|
||||
|
||||
extension Author: @retroactive DatabaseObject {
|
||||
|
||||
public var databaseID: String {
|
||||
return authorID
|
||||
}
|
||||
|
||||
public func databaseDictionary() -> DatabaseDictionary? {
|
||||
var d: DatabaseDictionary = [DatabaseKey.authorID: authorID]
|
||||
if let name = name {
|
||||
d[DatabaseKey.name] = name
|
||||
}
|
||||
if let url = url {
|
||||
d[DatabaseKey.url] = url
|
||||
}
|
||||
if let avatarURL = avatarURL {
|
||||
d[DatabaseKey.avatarURL] = avatarURL
|
||||
}
|
||||
if let emailAddress = emailAddress {
|
||||
d[DatabaseKey.emailAddress] = emailAddress
|
||||
}
|
||||
return d
|
||||
}
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
//
|
||||
// DatabaseObject+Database.swift
|
||||
// NetNewsWire
|
||||
//
|
||||
// Created by Brent Simmons on 9/13/17.
|
||||
// Copyright © 2017 Ranchero Software. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import RSDatabase
|
||||
import Articles
|
||||
|
||||
extension Array where Element == DatabaseObject {
|
||||
|
||||
func asAuthors() -> Set<Author>? {
|
||||
let authors = Set(self.map { $0 as! Author })
|
||||
return authors.isEmpty ? nil : authors
|
||||
}
|
||||
}
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
//
|
||||
// RelatedObjectsMap+Database.swift
|
||||
// Database
|
||||
//
|
||||
// Created by Brent Simmons on 9/13/17.
|
||||
// Copyright © 2017 Ranchero Software. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import RSDatabase
|
||||
import Articles
|
||||
|
||||
extension RelatedObjectsMap {
|
||||
|
||||
func authors(for articleID: String) -> Set<Author>? {
|
||||
if let objects = self[articleID] {
|
||||
return objects.asAuthors()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user