Chapter 10 page 164

Hi,
On page 164 if I execute DELETE http://localhost:8080/api/acronyms/1/ it suppose to generate an error
But in my case I can delete the acronym without any errors

My code on Acronym.swift (like is define Chapter 10 page 154)

// Sibling Relationships
extension Acronym {
  var categories: Siblings<Acronym, Category, AcronymCategoryPivot> {
    return siblings()
  }
}

My code on AcronymCategoryPivot.swift

import FluentPostgreSQL
import Foundation

final class AcronymCategoryPivot: PostgreSQLUUIDPivot, ModifiablePivot {
  
  var id: UUID?
  
  var acronymID: Acronym.ID
  var categoryID: Category.ID
  
  typealias Left = Acronym
  typealias Right = Category
  
  static let leftIDKey: LeftIDKey = \.acronymID
  static let rightIDKey: RightIDKey = \.categoryID
  
  init(_ acronym: Acronym, _ category: Category) throws {
    self.acronymID = try acronym.requireID()
    self.categoryID = try category.requireID()
  }
}

extension AcronymCategoryPivot: Migration {

  static func prepare(on connection: PostgreSQLConnection) -> Future<Void> {

    return Database.create(self, on: connection) {
      builder in
      
      try addProperties(to: builder)

      builder.reference(
        from: \.acronymID,
        to: \Acronym.id,
        onDelete: .cascade)
      
      builder.reference(
        from: \.categoryID,
        to: \Category.id,
        onDelete: .cascade)
    }
    
  }

On postgres the table Acronym_Category is defined like this:

CREATE TABLE "Acronym_Category" (
    id uuid PRIMARY KEY,
    "acronymID" bigint NOT NULL REFERENCES "Acronym"(id) ON DELETE CASCADE,
    "categoryID" bigint NOT NULL REFERENCES "Category"(id) ON DELETE CASCADE
);

CREATE UNIQUE INDEX "pk:Acronym_Category.id" ON "Acronym_Category"(id uuid_ops);

An idea of why it generates me no error?

@0xtim Can you please help with this when you get a chance? Thank you - much appreciated! :]

@tof

Looking at your migration extension for AcronymCategoryPivot - you are setting the references to acronym and category to “onDelete: .cascade”. That shows in the postgres table definition for Acronym_Category, where both acronym and category show “ON DELETE CASCADE”.

With that in place, you won’t get an error when deleting an acronym that has associated categories. Instead of giving you an error, it will delete the associated categories from the pivot table, and then delete the acronym.

Hope that helps!

1 Like

@tof you are right, there’s an error in the book. It shouldn’t error thanks to the cascade stuff, but the book says it should (because cascade was added later :man_facepalming:

This will be fixed in the next edition!

@rcasey thanks for your answer :slight_smile:
@0xtim Ok good :slight_smile: