@@ -17,22 +17,25 @@ import Opaleye.PGTypes
1717import Data.Profunctor (Profunctor , dimap , lmap )
1818import Data.Profunctor.Product as PP
1919
20+ import Data.Monoid
21+
2022import qualified Data.Profunctor.Product.Default as D
2123
2224class PGType a where
2325 data SchemaOptions a
24- pgTypeName :: a -> String
25- pgTypeOptions :: SchemaOptions a -> String
26+ pgColumnDefinition :: SchemaOptions a -> String
27+ defaultOptions :: SchemaOptions a
2628
2729instance PGType PGInt8 where
28- data SchemaOptions PGInt8 = NoIntOptions | Autogenerated
29- pgTypeName = const " numeric "
30- pgTypeOptions _ = " SERIAL "
30+ data SchemaOptions PGInt8 = NoIntOptions
31+ pgColumnDefinition _ = " SERIAL "
32+ defaultOptions = NoIntOptions
3133
3234instance PGType PGText where
33- data SchemaOptions PGText = NoOptions
34- pgTypeName = const " varchar"
35- pgTypeOptions _ = " (256)"
35+ data SchemaOptions PGText = Length Int | Unspecified
36+ pgColumnDefinition (Length x ) = " varchar (" <> show x <> " )"
37+ pgColumnDefinition _ = " text"
38+ defaultOptions = Unspecified
3639
3740data TableSchema = TableSchema String [UntypedColumn ]
3841
@@ -54,8 +57,27 @@ tableSchema (discardSchema -> (tableName, (IT.TableProperties _ (View tableColum
5457 extractor d = ([d], () )
5558 (columns, () ) = pm extractor tableColumns
5659
60+ data ForeignKey = ForeignKey [String ] [String ]
61+
62+ foreignKey ::
63+ forall from from' to to' fk .
64+ (D. Default SchemaMaker fk fk ) =>
65+ IT. Table from' from -> (from -> fk ) -> IT. Table to' to -> (to -> fk ) -> ForeignKey
66+ foreignKey tableFrom selectSubsetFrom tableTo selectSubsetTo = let
67+ extractor (unUntypedColumn -> TM. TableColumn name' _) = ([name'], () )
68+ (snd . discardSchema -> (IT. TableProperties _ (View tableColsFrom))) = tableFrom
69+ (snd . discardSchema -> (IT. TableProperties _ (View tableColsTo))) = tableTo
70+ keyFrom = selectSubsetFrom tableColsFrom
71+ keyTo = selectSubsetTo tableColsTo
72+ s1 :: SchemaMaker fk fk
73+ s1 = D. def
74+ (SchemaMaker (PM. PackMap pm)) = s1
75+ (columnsFrom, () ) = pm extractor keyFrom
76+ (columnsTo, () ) = pm extractor keyTo
77+ in ForeignKey columnsFrom columnsTo
78+
5779columnSchemaMaker :: SchemaMaker (TM. TableColumn any ) b
58- columnSchemaMaker = SchemaMaker (PM. PackMap (\ f (TM. TableColumn x y z ) -> f (UntypedColumn (TM. TableColumn x y z ))))
80+ columnSchemaMaker = SchemaMaker (PM. PackMap (\ f (TM. TableColumn x y) -> f (UntypedColumn (TM. TableColumn x y))))
5981
6082instance D. Default SchemaMaker (TM. TableColumn a ) (Column a ) where
6183 def = columnSchemaMaker
0 commit comments