Skip to content

Commit

Permalink
Using Prisma file alongside Wasp (#2035)
Browse files Browse the repository at this point in the history
  • Loading branch information
infomiho authored Jul 3, 2024
1 parent 6285014 commit 8ead2e0
Show file tree
Hide file tree
Showing 172 changed files with 4,373 additions and 1,945 deletions.
15 changes: 1 addition & 14 deletions examples/tutorials/TodoApp/main.wasp
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
app TodoApp {
wasp: {
version: "^0.13.0" // Pins the version of Wasp to use.
version: "^0.14.0" // Pins the version of Wasp to use.
},
title: "TodoApp", // Used as the browser tab title. Note that all strings in Wasp are double quoted!
auth: {
Expand Down Expand Up @@ -34,19 +34,6 @@ page LoginPage {
component: import { LoginPage } from "@src/LoginPage"
}

entity User {=psl
id Int @id @default(autoincrement())
tasks Task[]
psl=}

entity Task {=psl
id Int @id @default(autoincrement())
description String
isDone Boolean @default(false)
user User? @relation(fields: [userId], references: [id])
userId Int?
psl=}

query getTasks {
// Specifies where the implementation for the query function is.
// The path `@src/queries` resolves to `src/queries.js`.
Expand Down
23 changes: 23 additions & 0 deletions examples/tutorials/TodoApp/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
datasource db {
provider = "sqlite"
// Wasp requires that the url is set to the DATABASE_URL environment variable.
url = env("DATABASE_URL")
}

// Wasp requires the `prisma-client-js` generator to be present.
generator client {
provider = "prisma-client-js"
}

model User {
id Int @id @default(autoincrement())
tasks Task[]
}

model Task {
id Int @id @default(autoincrement())
description String
isDone Boolean @default(false)
user User? @relation(fields: [userId], references: [id])
userId Int?
}
15 changes: 1 addition & 14 deletions examples/tutorials/TodoAppTs/main.wasp
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
app TodoApp {
wasp: {
version: "^0.13.0" // Pins the version of Wasp to use.
version: "^0.14.0" // Pins the version of Wasp to use.
},
title: "TodoApp", // Used as the browser tab title. Note that all strings in Wasp are double quoted!
auth: {
Expand Down Expand Up @@ -34,19 +34,6 @@ page LoginPage {
component: import { LoginPage } from "@src/LoginPage"
}

entity User {=psl
id Int @id @default(autoincrement())
tasks Task[]
psl=}

entity Task {=psl
id Int @id @default(autoincrement())
description String
isDone Boolean @default(false)
user User? @relation(fields: [userId], references: [id])
userId Int?
psl=}

query getTasks {
// Specifies where the implementation for the query function is.
// The path `@src/queries` resolves to `src/queries.ts`.
Expand Down
23 changes: 23 additions & 0 deletions examples/tutorials/TodoAppTs/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
datasource db {
provider = "sqlite"
// Wasp requires that the url is set to the DATABASE_URL environment variable.
url = env("DATABASE_URL")
}

// Wasp requires the `prisma-client-js` generator to be present.
generator client {
provider = "prisma-client-js"
}

model User {
id Int @id @default(autoincrement())
tasks Task[]
}

model Task {
id Int @id @default(autoincrement())
description String
isDone Boolean @default(false)
user User? @relation(fields: [userId], references: [id])
userId Int?
}
3 changes: 3 additions & 0 deletions mage/src/client/components/FileTree.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import "./FileTree.css";
import TreeView, { flattenTree } from "react-accessible-treeview";
import { DiCss3, DiJavascript, DiNpm, DiReact } from "react-icons/di";
import { FaList, FaRegFolder, FaRegFolderOpen } from "react-icons/fa";
import { SiPrisma } from "react-icons/si";
import { WaspIcon } from "./WaspIcon";

export function FileTree({
Expand Down Expand Up @@ -125,6 +126,8 @@ const FileIcon = ({ filename }) => {
return <DiNpm color="red" className="icon" />;
case "wasp":
return <WaspIcon className="icon" />;
case "prisma":
return <SiPrisma color="turquoise" className="icon" />;
default:
return null;
}
Expand Down
2 changes: 1 addition & 1 deletion mage/src/client/pages/ResultPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ export const ResultPage = () => {
appAuthMethod: project.authMethod,
appCreativityLevel: project.creativityLevel,
});
alert("Now I will go to " + appId);
alert("Okay, redirecting to the new attempt");
history.push(`/result/${appId}`);
} catch (e) {
alert(e.message);
Expand Down
5 changes: 2 additions & 3 deletions waspc/cli/src/Wasp/Cli/Command/Info.hs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import Wasp.Cli.Command.Common (readWaspCompileInfo)
import Wasp.Cli.Command.Compile (analyze)
import Wasp.Cli.Command.Message (cliSendMessageC)
import Wasp.Cli.Command.Require (InWaspProject (InWaspProject), require)
import Wasp.Cli.Command.Start.Db (getDbSystem)
import Wasp.Cli.Terminal (title)
import qualified Wasp.Message as Msg
import Wasp.Project (WaspProjectDir)
Expand All @@ -29,15 +28,15 @@ info = do
projectSize <- liftIO $ readDirectorySizeMB waspDir

appSpec <- analyze waspDir
let (appName, app) = ASV.getApp appSpec
let (appName, _) = ASV.getApp appSpec

cliSendMessageC $
Msg.Info $
unlines
[ "",
title "Project information",
printInfo "Name" appName,
printInfo "Database system" $ show $ getDbSystem app,
printInfo "Database system" $ show $ ASV.getValidDbSystem appSpec,
printInfo "Last compile" compileInfo,
printInfo "Project dir size" projectSize
]
Expand Down
12 changes: 3 additions & 9 deletions waspc/cli/src/Wasp/Cli/Command/Start/Db.hs
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
module Wasp.Cli.Command.Start.Db
( start,
getDbSystem,
waspDevDbDockerVolumePrefix,
)
where

import Control.Monad (when)
import qualified Control.Monad.Except as E
import Control.Monad.IO.Class (liftIO)
import Data.Maybe (fromMaybe, isJust)
import Data.Maybe (isJust)
import StrongPath (Abs, Dir, File', Path', Rel, fromRelFile)
import System.Environment (lookupEnv)
import System.Process (callCommand)
import Text.Printf (printf)
import qualified Wasp.AppSpec as AS
import qualified Wasp.AppSpec.App as AS.App
import qualified Wasp.AppSpec.App.Db as AS.App.Db
import qualified Wasp.AppSpec.Valid as ASV
import Wasp.Cli.Command (Command, CommandError (CommandError))
Expand Down Expand Up @@ -42,8 +40,8 @@ start = do

throwIfCustomDbAlreadyInUse appSpec

let (appName, app) = ASV.getApp appSpec
case getDbSystem app of
let (appName, _) = ASV.getApp appSpec
case ASV.getValidDbSystem appSpec of
AS.App.Db.SQLite -> noteSQLiteDoesntNeedStart
AS.App.Db.PostgreSQL -> startPostgreDevDb waspProjectDir appName
where
Expand Down Expand Up @@ -85,10 +83,6 @@ throwIfCustomDbAlreadyInUse spec = do
throwCustomDbAlreadyInUseError msg =
E.throwError $ CommandError "You are using custom database already" msg

getDbSystem :: AS.App.App -> AS.App.Db.DbSystem
getDbSystem app =
fromMaybe AS.App.Db.SQLite (AS.App.db app >>= AS.App.Db.system)

startPostgreDevDb :: Path' Abs (Dir WaspProjectDir) -> String -> Command ()
startPostgreDevDb waspProjectDir appName = do
throwIfExeIsNotAvailable
Expand Down
13 changes: 5 additions & 8 deletions waspc/cli/src/Wasp/Cli/Command/Studio.hs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import qualified Wasp.AppSpec as AS
import qualified Wasp.AppSpec.Api as AS.Api
import qualified Wasp.AppSpec.App as AS.App
import qualified Wasp.AppSpec.App.Auth as AS.App.Auth
import qualified Wasp.AppSpec.App.Db as AS.App.Db
import qualified Wasp.AppSpec.Job as AS.Job
import Wasp.AppSpec.Operation (Operation (..))
import qualified Wasp.AppSpec.Operation as Operation
Expand Down Expand Up @@ -117,7 +116,7 @@ studio = do
.= object
[ "name" .= (appName :: String),
"auth" .= getAuthInfo appSpec app,
"db" .= getDbInfo app
"db" .= getDbInfo appSpec
]
-- TODO: Add CRUDs.
]
Expand Down Expand Up @@ -155,12 +154,10 @@ studio = do
resolveEntities spec entityRefs =
AS.resolveRef spec <$> fromMaybe [] entityRefs

getDbInfo app = do
db <- AS.App.db app
return $
object
[ "system" .= (show <$> AS.App.Db.system db)
]
getDbInfo spec =
object
[ "system" .= show (ASV.getValidDbSystem spec)
]

getAuthInfo spec app = do
auth <- AS.App.auth app
Expand Down
10 changes: 10 additions & 0 deletions waspc/data/Cli/templates/basic/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
datasource db {
provider = "sqlite"
// Wasp requires that the url is set to the DATABASE_URL environment variable.
url = env("DATABASE_URL")
}

// Wasp requires the `prisma-client-js` generator to be present.
generator client {
provider = "prisma-client-js"
}
22 changes: 9 additions & 13 deletions waspc/data/Generator/templates/db/schema.prisma
Original file line number Diff line number Diff line change
@@ -1,20 +1,16 @@
{{={= =}=}}

datasource db {
provider = "{= datasourceProvider =}"
url = {=& datasourceUrl =}
{=# dbExtensions =}
extensions = {=& . =}
{=/ dbExtensions =}
}
{=& datasourceSchema =}

generator client {
provider = "prisma-client-js"
{=# prismaPreviewFeatures =}
previewFeatures = {=& . =}
{=/ prismaPreviewFeatures =}
}
{=# generatorSchemas =}
{=& . =}
{=/ generatorSchemas =}

{=# modelSchemas =}
{=& . =}

{=/ modelSchemas =}
{=# enumSchemas =}
{=& . =}

{=/ enumSchemas =}
25 changes: 19 additions & 6 deletions waspc/e2e-test/ShellCommands.hs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ module ShellCommands
combineShellCommands,
cdIntoCurrentProject,
appendToWaspFile,
appendToPrismaFile,
createFile,
setDbToPSQL,
waspCliNew,
Expand Down Expand Up @@ -55,10 +56,16 @@ cdIntoCurrentProject = do
context <- ask
return $ "cd " ++ _ctxtCurrentProjectName context

appendToWaspFile :: String -> ShellCommandBuilder ShellCommand
appendToWaspFile content =
appendToWaspFile :: FilePath -> ShellCommandBuilder ShellCommand
appendToWaspFile = appendToFile "main.wasp"

appendToPrismaFile :: FilePath -> ShellCommandBuilder ShellCommand
appendToPrismaFile = appendToFile "schema.prisma"

appendToFile :: FilePath -> String -> ShellCommandBuilder ShellCommand
appendToFile fileName content =
-- NOTE: Using `show` to preserve newlines in string.
return $ "printf " ++ show (content ++ "\n") ++ " >> main.wasp"
return $ "printf " ++ show (content ++ "\n") ++ " >> " ++ fileName

-- NOTE: Pretty fragile. Can't handle spaces in args, *nix only, etc.
createFile :: String -> FilePath -> String -> ShellCommandBuilder ShellCommand
Expand All @@ -69,11 +76,9 @@ createFile content relDirFp filename = return $ combineShellCommands [createPare
contents = show (content ++ "\n")
writeContentsToFile = unwords ["printf", contents, ">", destinationFile]

-- NOTE: This is fragile and will likely break in future. Assumes `app` decl is first line and by default
-- we do not have a `db` field. Consider better alternatives.
setDbToPSQL :: ShellCommandBuilder ShellCommand
-- Change DB to postgres by adding string at specific line so it still parses.
setDbToPSQL = insertCodeIntoFileAtLineNumber "main.wasp" 2 " db: { system: PostgreSQL },"
setDbToPSQL = replaceLineInFile "schema.prisma" 2 " provider = \"postgresql\""

insertCodeIntoFileAtLineNumber :: FilePath -> Int -> String -> ShellCommandBuilder ShellCommand
insertCodeIntoFileAtLineNumber fileName atLineNumber line =
Expand All @@ -83,6 +88,14 @@ insertCodeIntoFileAtLineNumber fileName atLineNumber line =
"mv " ++ fileName ++ ".tmp " ++ fileName
]

replaceLineInFile :: FilePath -> Int -> String -> ShellCommandBuilder ShellCommand
replaceLineInFile fileName lineNumber line =
return $
combineShellCommands
[ "awk 'NR==" ++ show lineNumber ++ "{$0=" ++ show line ++ "}1' " ++ fileName ++ " > " ++ fileName ++ ".tmp",
"mv " ++ fileName ++ ".tmp " ++ fileName
]

waspCliNew :: ShellCommandBuilder ShellCommand
waspCliNew = do
context <- ask
Expand Down
21 changes: 11 additions & 10 deletions waspc/e2e-test/Tests/WaspComplexTest.hs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import GoldenTest (GoldenTest, makeGoldenTest)
import ShellCommands
( ShellCommand,
ShellCommandBuilder,
appendToPrismaFile,
appendToWaspFile,
cdIntoCurrentProject,
createFile,
Expand Down Expand Up @@ -171,7 +172,7 @@ addAuth :: ShellCommandBuilder [ShellCommand]
addAuth = do
sequence
[ insertCodeIntoWaspFileAfterVersion authField,
appendToWaspFile userEntity,
appendToPrismaFile userModel,
createFile hooksFile "./src/auth" "hooks.ts"
]
where
Expand All @@ -189,13 +190,12 @@ addAuth = do
" },"
]

userEntity =
userModel =
unlines
[ "entity User {=psl",
" id Int @id @default(autoincrement())",
"psl=}"
[ "model User {",
" id Int @id @default(autoincrement())",
"}"
]

hooksFile =
unlines
[ "import type {",
Expand Down Expand Up @@ -360,18 +360,19 @@ addEmailSender = do
addCrud :: ShellCommandBuilder [ShellCommand]
addCrud = do
sequence
[ appendToWaspFile taskEntityDecl,
[ appendToPrismaFile taskModel,
appendToWaspFile crudDecl
]
where
taskEntityDecl =
taskModel =
unlines
[ "entity Task {=psl",
[ "model Task {",
" id Int @id @default(autoincrement())",
" description String",
" isDone Boolean @default(false)",
"psl=}"
"}"
]

crudDecl =
unlines
[ "crud tasks {",
Expand Down
Loading

0 comments on commit 8ead2e0

Please sign in to comment.