1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
module ERD2Curry
  ( main, startWithERD, EROptions(..), defaultEROptions
  , erd2CDBI, erd2curryWithDBandERD )
 where

import Control.Monad        ( when, unless )
import Data.List            ( isSuffixOf )
import System.Environment   ( getArgs, setEnv )

import AbstractCurry.Files     ( readCurry )
import AbstractCurry.Select    ( imports )
import AbstractCurry.Pretty
import AbstractCurry.Transform ( renameCurryModule )
import Database.ERD
import Data.Time
import System.Directory     ( doesFileExist, getModificationTime )
import System.Process       ( exitWith, system )
import XML                  ( readXmlFile )

import Database.ERD.FromXML
import Database.ERD.Goodies
import Database.ERD.ToCDBI  ( writeCDBI )
import Database.ERD.ToKeyDB
import Database.ERD.Transformation
import Database.ERD.View    ( viewERD )
import ERToolsPackageConfig ( packagePath, packageVersion, packageLoadPath )

systemBanner :: String
systemBanner =
  let bannerText = "ERD->Curry Compiler (Version " ++ packageVersion ++
                   " of 04/06/23)"
      bannerLine = take (length bannerText) (repeat '-')
   in bannerLine ++ "\n" ++ bannerText ++ "\n" ++ bannerLine

data EROptions = EROptions
  { optERProg    :: String  -- Curry program containing ERD
  , optFromXml   :: Bool    -- read ERD from XML file?
  , optVisualize :: Bool    -- visualize ERD?
  , optStorage   :: Storage -- storage of data
  , optToERDT    :: Bool    -- only transform into ERDT term file
  , optCDBI      :: Bool    -- generate Curry for Database.CDBI libraries
  , optModule    :: String  -- name of generated Curry module
  , optFile      :: String  -- file to store generated Curry module
  }

defaultEROptions :: EROptions
defaultEROptions = EROptions
  { optERProg    = ""
  , optFromXml   = False
  , optVisualize = False
  , optStorage   = SQLite ""
  , optToERDT    = False
  , optCDBI      = False
  , optModule    = ""
  , optFile      = ""
  }

--- Main function for saved state. The argument is the directory containing
--- these sources.
main :: IO ()
main = do
  putStrLn systemBanner
  args <- getArgs
  configs <- parseArgs defaultEROptions args
  startERD2Curry configs

parseArgs :: EROptions -> [String] -> IO (Maybe EROptions)
parseArgs _    []         = return Nothing
parseArgs opts (arg:args) = case arg of
  "-h" -> putStrLn helpText >> exitWith 0
  "-?" -> putStrLn helpText >> exitWith 0
  "--help" -> putStrLn helpText >> exitWith 0
  "-x" -> parseArgs opts { optFromXml = True } args
  "-l" -> parseArgs (setSQLite (optStorage opts)) args
  "-d" -> parseArgs opts { optStorage = DB } args
  "--db" -> if null args
              then return Nothing
              else parseArgs (setFilePath (head args) (optStorage opts))
                             (tail args)
  "-t" -> parseArgs opts { optToERDT = True } args
  "-v" -> parseArgs opts { optVisualize = True } args
  "--cdbi"   -> parseArgs opts { optCDBI = True } args
  "--module" -> if null args
                  then return Nothing
                  else parseArgs opts { optModule = head args } (tail args)
  "--outfile"-> if null args
                  then return Nothing
                  else parseArgs opts { optFile = head args } (tail args)
  f    -> return $ if null args then Just opts { optERProg = f }
                                else Nothing
 where
  setFilePath path (Files  _) = opts { optStorage = Files  path }
  setFilePath path (SQLite _) = opts { optStorage = SQLite path }
  setFilePath _    DB         = opts { optStorage = DB }

  setSQLite (Files  p) = opts { optStorage = SQLite p  }
  setSQLite (SQLite p) = opts { optStorage = SQLite p  }
  setSQLite DB         = opts { optStorage = SQLite "" }

storagePath :: Storage -> String
storagePath (Files  p) = p
storagePath (SQLite p) = p
storagePath DB         = ""

helpText :: String
helpText = unlines
  [ ""
  , "Usage:"
  , ""
  , "    erd2curry <options> <prog>"
  , ""
  , "with options:"
  , ""
  , "-l           : generate interface to SQLite3 database (default)"
  , "-d           : generate interface to SQL database (experimental)"
  , "-x           : generate from ERD xmi document instead of ERD Curry program"
  , "-t           : only transform ERD into ERDT term file"
  , "-v           : only show visualization of ERD with dotty"
  , "--db <dbfile>: file of the SQLite3 database"
  , "--cdbi       : generate Curry module for Database.CDBI modules"
  , "--module <m> : name of generated Curry module (default: <ERD name>)"
  , "--outfile <f>: file to store the generated module (default: <ERD name>.curry)"
  , "<prog>       : name of Curry program file containing ERD definition"
  ]

--- Runs ERD2Curry with a given database and ERD program.
erd2curryWithDBandERD :: String -> String -> IO ()
erd2curryWithDBandERD dbname erfile =
  startERD2Curry
    (Just defaultEROptions
             { optStorage = SQLite dbname, optERProg = erfile })

--- Translate an ERD into a Curry program using the API provided by the
--- Curry package `cdbi`. The parameters are the name of the database,
--- the name of the Curry program containing the ERD (only used in
--- a comment of the generated program), and the ERD definition.
--- The generated Curry module has the name of the ERD and
--- is put into the current directory.
erd2CDBI :: String -> String -> ERD -> IO ()
erd2CDBI dbname erdfile erd =
  startWithERD
    (defaultEROptions { optStorage = SQLite dbname, optCDBI = True })
    erdfile
    erd

startERD2Curry :: Maybe EROptions -> IO ()
startERD2Curry Nothing = do
  putStrLn $ "ERROR: Illegal arguments\n\n" ++ helpText
  exitWith 1
startERD2Curry (Just opts) = do
  -- set CURRYPATH in order to compile ERD model (which requires Database.ERD)
  unless (null packageLoadPath) $ setEnv "CURRYPATH" packageLoadPath
  -- the directory containing the sources of this tool:
  let orgfile = optERProg opts
  if optFromXml opts
    then do (_,erd) <- transformXmlFile orgfile
            startWithERD opts orgfile erd
    else do
      unless (".curry"  `isSuffixOf` orgfile ||
              ".lcurry" `isSuffixOf` orgfile) $ do
        putStrLn $ "ERROR: '" ++ orgfile ++ "' is not a Curry program file!"
        exitWith 1
      if optVisualize opts
        then readERDFromProgram orgfile >>= viewERD
        else readERDFromProgram orgfile >>= startWithERD opts orgfile

--- Main function to invoke the ERD->Curry translator.
--- The parameters are the tool options,
--- the name of the Curry program containing the ERD (only used in
--- a comment of the generated program), and the ERD definition.
--- If not changed by specific options, the generated Curry module
--- has the name of the ERD and is put into the current directory.
startWithERD :: EROptions -> String -> ERD -> IO ()
startWithERD opts srcfile erd = do
  let erdname      = erdName erd
      transerdfile = erdname ++ "_ERDT.term"
      curryfile    = if null (optFile opts) then erdname ++ ".curry"
                                            else optFile opts
      transerd     = transform erd
      opt          = ( if optStorage opts == SQLite ""
                         then SQLite (erdname ++ ".db")
                         else optStorage opts
                     , WithConsistencyTest )
      erdprog      = let prog = erd2code opt (transform erd)
                     in if null (optModule opts)
                          then prog
                          else renameCurryModule (optModule opts) prog
  writeFile transerdfile $
    "{- ERD specification transformed from " ++ srcfile ++ " -}\n\n " ++
    showERD 2 transerd ++ "\n"
  putStrLn $ "Transformed ERD term written into file '" ++ transerdfile ++ "'."
  when (optCDBI opts) $
    writeCDBI srcfile curryfile
              (if null (optModule opts) then erdname else optModule opts)
              transerd (storagePath (fst opt))
  unless (optToERDT opts || optCDBI opts) $ do
    moveOldVersion curryfile
    impprogs <- mapM readCurry (imports erdprog)
    writeFile curryfile $
      prettyCurryProg
        (setOnDemandQualification (erdprog:impprogs) defaultOptions)
        erdprog
    putStrLn $ unlines
      [ "Database operations generated into file '" ++ curryfile ++ "'"
      , "with " ++ showOption opt ++ "."
      , "NOTE: To compile this module, use packages " ++
        "'keydb', 'ertools' and 'time'." ]
 where
  showOption (Files f,_) = "database files stored in directory '"++f++"'"
  showOption (SQLite f,_) =
    "SQLite3 database stored in file '" ++ f ++ "'"
  showOption (DB,_) = "SQL database interface"

--- Moves a file (if it exists) to one with extension ".versYYMMDDhhmmss".
moveOldVersion :: String -> IO ()
moveOldVersion fname = do
  exists <- doesFileExist fname
  if exists
   then do
     mtime <- getModificationTime fname
     cmtime <- toCalendarTime mtime
     let fnamevers = fname ++ ".vers" ++ calTime2Digits cmtime
     system $ "mv "++fname++" "++fnamevers
     putStrLn $ "Old contents of file \""++fname++"\" saved into file \""++
                fnamevers++"\"."
   else return ()
 where
  calTime2Digits (CalendarTime y mo d h mi s _) =
    toD (y `mod` 100) ++ toD mo ++ toD d ++ toD h ++ toD mi ++ toD s

  toD i = if i<10 then '0':show i else show i


--- Read an ERD specification from an XML file in Umbrello format.
transformXmlFile :: String -> IO (String,ERD)
transformXmlFile xmlfile = do
  putStrLn $ "Reading XML file " ++ xmlfile ++ "..."
  xml <- readXmlFile xmlfile
  let erd     = convert xml
  let erdfile = erdName erd ++ "_ERD.term"
  writeFile erdfile
            ("{- ERD specification read from "++xmlfile++" -}\n\n " ++
             showERD 2 erd ++ "\n")
  putStrLn $ "ERD term written into file \""++erdfile++"\"."
  return (erdfile,erd)

{-
-- Uni.xmi -> ERD term:
(ERD "Uni"
 [(Entity "Student" [(Attribute "MatNum" (IntDom Nothing) PKey False),
                     (Attribute "Name" (StringDom Nothing) NoKey False),
                     (Attribute "Firstname" (StringDom Nothing) NoKey False),
                     (Attribute "Email" (UserDefined "MyModule.Email" Nothing) NoKey True)]),
  (Entity "Lecture" [(Attribute "Id" (IntDom Nothing) PKey False),
                     (Attribute "Title" (StringDom Nothing) Unique False),
                     (Attribute "Hours" (IntDom (Just 4)) NoKey False)]),
  (Entity "Lecturer" [(Attribute "Id" (IntDom Nothing) PKey False),
                      (Attribute "Name" (StringDom Nothing) NoKey False),
                      (Attribute "Firstname" (StringDom Nothing) NoKey False)]),
  (Entity "Group" [(Attribute "Time" (StringDom Nothing) NoKey False)])]
 [(Relationship "Teaching" [(REnd "Lecturer" "taught_by" (Exactly 1)),
                            (REnd "Lecture" "teaches" (Between 0 Infinite))]),
  (Relationship "Participation" [(REnd "Student" "participated_by" (Between 0 Infinite)),
                                 (REnd "Lecture" "participates" (Between 0 Infinite))]),
  (Relationship "Membership" [(REnd "Student" "consists_of" (Exactly 3)),
                              (REnd "Group" "member_of" (Between 0 Infinite))])])

-- Transformation of ERD term:
(ERD "Uni"
 [(Entity "Membership"
          [(Attribute "Student_Membership_Key" (KeyDom "Student") PKey False),
           (Attribute "Group_Membership_Key" (KeyDom "Group") PKey False)]),
  (Entity "Participation"
          [(Attribute "Student_Participation_Key" (KeyDom "Student") PKey False),
           (Attribute "Lecture_Participation_Key" (KeyDom "Lecture") PKey False)]),
  (Entity "Student"
          [(Attribute "Key" (IntDom Nothing) PKey False),
           (Attribute "MatNum" (IntDom Nothing) Unique False),
           (Attribute "Name" (StringDom Nothing) NoKey False),
           (Attribute "Firstname" (StringDom Nothing) NoKey False),
           (Attribute "Email" (UserDefined "MyModule.Email" Nothing) NoKey True)]),
  (Entity "Lecture"
          [(Attribute "Key" (IntDom Nothing) PKey False),
           (Attribute "Lecturer_Teaching_Key" (KeyDom "Lecturer") NoKey False),
           (Attribute "Id" (IntDom Nothing) Unique False),
           (Attribute "Title" (StringDom Nothing) Unique False),
           (Attribute "Hours" (IntDom (Just 4)) NoKey False)]),
  (Entity "Lecturer"
          [(Attribute "Key" (IntDom Nothing) PKey False),
           (Attribute "Id" (IntDom Nothing) Unique False),
           (Attribute "Name" (StringDom Nothing) NoKey False),
           (Attribute "Firstname" (StringDom Nothing) NoKey False)]),
  (Entity "Group"
          [(Attribute "Key" (IntDom Nothing) PKey False),
           (Attribute "Time" (StringDom Nothing) NoKey False)])]
 [(Relationship [] [(REnd "Student" [] (Exactly 1)),
                    (REnd "Membership" "member_of" (Between 0 Infinite))]),
  (Relationship [] [(REnd "Group" [] (Exactly 1)),
                    (REnd "Membership" "consists_of" (Exactly 3))]),
  (Relationship [] [(REnd "Student" [] (Exactly 1)),
                    (REnd "Participation" "participates" (Between 0 Infinite))]),
  (Relationship [] [(REnd "Lecture" [] (Exactly 1)),
                    (REnd "Participation" "participated_by" (Between 0 Infinite))]),
  (Relationship "Teaching" [(REnd "Lecturer" "taught_by" (Exactly 1)),
                            (REnd "Lecture" "teaches" (Between 0 Infinite))])])
-}