@@ -24,7 +24,7 @@ extension _FluentSQLiteDatabase: Database {
2424 switch query. action {
2525 case . create:
2626 return connection. lastAutoincrementID ( ) . map {
27- onRow ( LastInsertRow ( lastAutoincrementID: $0) )
27+ onRow ( LastInsertRow ( idKey : query . idKey , lastAutoincrementID: $0) )
2828 }
2929 default :
3030 return self . eventLoop. makeSucceededFuture ( ( ) )
@@ -86,29 +86,39 @@ extension _FluentSQLiteDatabase: SQLiteDatabase {
8686
8787private struct LastInsertRow : DatabaseRow {
8888 var description : String {
89- return [ " id " : lastAutoincrementID] . description
89+ [ " id " : self . lastAutoincrementID] . description
9090 }
9191
92+ let idKey : String
9293 let lastAutoincrementID : Int
9394
94- init ( lastAutoincrementID: Int ) {
95- self . lastAutoincrementID = lastAutoincrementID
96- }
97-
9895 func contains( field: String ) -> Bool {
99- return field == " fluentID "
96+ field == self . idKey
10097 }
10198
10299 func decode< T> ( field: String , as type: T . Type , for database: Database ) throws -> T where T : Decodable {
103- switch field {
104- case " fluentID " :
105- if T . self is Int ? . Type || T . self is Int . Type {
106- return self . lastAutoincrementID as! T
107- } else {
108- fatalError ( " cannot decode last autoincrement type: \( T . self) " )
109- }
110- default :
111- throw FluentError . missingField ( name: field)
100+ guard field == self . idKey else {
101+ fatalError ( " Cannot decode field from last insert row: \( field) . " )
112102 }
103+ if let autoincrementInitializable = T . self as? AutoincrementIDInitializable . Type {
104+ return autoincrementInitializable. init ( autoincrementID: self . lastAutoincrementID) as! T
105+ } else {
106+ fatalError ( " Unsupported database generated identiifer type: \( T . self) " )
107+ }
108+ }
109+ }
110+
111+ protocol AutoincrementIDInitializable {
112+ init ( autoincrementID: Int )
113+ }
114+
115+ extension AutoincrementIDInitializable where Self: FixedWidthInteger {
116+ init ( autoincrementID: Int ) {
117+ self = numericCast ( autoincrementID)
113118 }
114119}
120+
121+ extension Int : AutoincrementIDInitializable { }
122+ extension UInt : AutoincrementIDInitializable { }
123+ extension Int64 : AutoincrementIDInitializable { }
124+ extension UInt64 : AutoincrementIDInitializable { }
0 commit comments