@@ -2,7 +2,7 @@ import Async
22import Foundation
33
44/// Adds ability to create, update, and delete schemas using a `PostgreSQLDatabase`.
5- extension PostgreSQLDatabase : SchemaSupporting {
5+ extension PostgreSQLDatabase : SchemaSupporting , IndexSupporting {
66 /// See `SchemaSupporting.dataType`
77 public static func dataType( for field: SchemaField < PostgreSQLDatabase > ) -> String {
88 var string : String
@@ -18,7 +18,13 @@ extension PostgreSQLDatabase: SchemaSupporting {
1818
1919 if field. isIdentifier {
2020 switch field. type. type {
21- case . int8, . int4, . int2: string += " GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY "
21+ case . int8, . int4, . int2:
22+ if _globalEnableIdentityColumns {
23+ string += " GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY "
24+ } else {
25+ // not appending!
26+ string = " SERIAL PRIMARY KEY "
27+ }
2228 default : string += " PRIMARY KEY "
2329 }
2430 } else if !field. isOptional {
@@ -52,9 +58,37 @@ extension PostgreSQLDatabase: SchemaSupporting {
5258 let sqlString = PostgreSQLSQLSerializer ( ) . serialize ( schema: schemaQuery)
5359 return try connection. query ( sqlString) . map ( to: Void . self) { rows in
5460 assert ( rows. count == 0 )
61+ } . flatMap ( to: Void . self) {
62+ /// handle indexes as separate query
63+ var indexFutures : [ Future < Void > ] = [ ]
64+ for addIndex in schema. addIndexes {
65+ let fields = addIndex. fields. map { " \" \( $0. name) \" " } . joined ( separator: " , " )
66+ let name = addIndex. psqlName ( for: schema. entity)
67+ let add = connection. simpleQuery ( " CREATE \( addIndex. isUnique ? " UNIQUE " : " " ) INDEX \" \( name) \" ON \" \( schema. entity) \" ( \( fields) ) " ) . map ( to: Void . self) { rows in
68+ assert ( rows. count == 0 )
69+ }
70+ indexFutures. append ( add)
71+ }
72+ for removeIndex in schema. removeIndexes {
73+ let name = removeIndex. psqlName ( for: schema. entity)
74+ let remove = connection. simpleQuery ( " DROP INDEX \" \( name) \" " ) . map ( to: Void . self) { rows in
75+ assert ( rows. count == 0 )
76+ }
77+ indexFutures. append ( remove)
78+ }
79+ return indexFutures. flatten ( )
5580 }
81+
82+
5683 } catch {
5784 return Future ( error: error)
5885 }
5986 }
6087}
88+
89+ extension SchemaIndex {
90+ func psqlName( for entity: String ) -> String {
91+ return " _fluent_index_ \( entity) _ " + fields. map { $0. name } . joined ( separator: " _ " )
92+ }
93+ }
94+
0 commit comments