Skip to content

Commit 873b0ee

Browse files
authored
Merge pull request #1148 from engalar/feat/run-local-hsqldb
feat: run --local with the built-in HSQLDB database
2 parents 31eee45 + 523ece9 commit 873b0ee

13 files changed

Lines changed: 1295 additions & 25 deletions

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
3636

3737
Pages still bound to the layout are **named in a warning and the drop proceeds**, matching every other DROP in mxcli (none refuse on dependents) and matching how a layout is normally corrected: re-create it under the same name and the pages rebind by qualified name — verified end to end, back to 0 errors. Left dropped, each page fails **CE1613** "The selected layout … no longer exists", which names the *page* and never the layout, so the warning names the pages and gives the `alter pages … where layout =` repoint.
3838

39+
- **`run --local --db-type hsqldb` — boot with no database server** — a local run can now use Mendix's built-in, file-based HSQLDB instead of PostgreSQL. The runtime already ships the driver and derives the file URL from `DatabaseType` and `DatabaseName`, so the data lands under `<project>/deployment/data/database/hsqldb/`. `--db-host`, `--db-user` and `--db-password` are refused with HSQLDB (it is a file, not a connection) and `--ensure-db` is refused too (there is nothing to provision); PostgreSQL remains the default and is unchanged. Intended for local development and demos only — Mendix marks HSQLDB as local-testing-only.
40+
3941
### Fixed
4042

43+
- **The runtime start cycle did not create a database that does not exist yet** — `RuntimeController.Start` only ran `execute_ddl_commands` when Mendix answered result 3 ("the database has to be updated"). A brand-new database answers result 2 ("the database to be used does not exist"), which was unhandled, so the first boot against the built-in HSQLDB database failed with `start failed: The database to be used does not exist.` Both results now trigger the schema step, and a start that still fails after it says so explicitly.
44+
4145
- **`mxcli run --local` hung forever on Windows at `Starting mxbuild --serve...`** — two POSIX assumptions in `cmd/mxcli/docker` combined. `ServeServer.alive()` (and `LocalRuntime.alive()`) asked `os.Process.Signal(syscall.Signal(0))`, which Go implements as `EWINDOWS` ("not supported by windows") for every signal but `Kill` — so a live mxbuild read as dead and `waitReady()` aborted the boot the instant it launched it. And `Stop()` waited on `cmd.Wait()` after a `killProcessGroup` that on Windows only called `p.Kill()`: mxbuild.exe is a wrapper that launches a Deno web-ext worker (`modeler/tools/deno/win-x64/deno.exe`) which inherits the stdout/stderr pipe `exec.Cmd` hands out, so the orphan kept the pipe open and `Wait()` never saw EOF — no error, no exit, just a hang. Windows now has a real liveness check (`OpenProcess(SYNCHRONIZE)` + `WaitForSingleObject`) and a tree kill (`taskkill /F /T`) behind `signalProcessGroup`/`killProcessGroup`; the POSIX implementations are unchanged. The Windows-only tests in `procgroup_windows_test.go` pin both halves — the tree-kill test fails on the pre-fix code, verified as a control — and a `windows-latest` CI job runs them (asserting they actually executed) so neither can come back.
4246

4347
- **`raise error;` on a microflow's main flow passed check and exec, then failed the build** (mendixlabs/mxcli#1030) — with `[error] [CE0710] "The main flow cannot join an error flow or end in an error event."`, one per microflow. Mendix's error event *re-raises the error being handled*, so it is legal only where an error is in scope: inside an `on error { … }` handler. Studio Pro will not draw the connection from the normal flow to an error event; mxcli could, and did. It is now **MDL084**, at error severity, so `exec`'s pre-flight refuses the script with nothing written (`--no-check` still applies it, for reproducing the build failure).

‎cmd/mxcli/cmd_run.go‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ Requirements:
3636
- A reachable PostgreSQL (the devcontainer provides one); the database must
3737
already exist. Defaults: 127.0.0.1:5432, user 'mendix', db from the project
3838
name. Override with --db-host/--db-name/--db-user/--db-password.
39+
- --db-type hsqldb runs against the built-in file database instead of
40+
PostgreSQL, so no database server is needed. Its data lives under the
41+
project's deployment directory and is meant for local development only.
3942
4043
With --hub, the running app is exposed in a browser at a public URL through an
4144
mxcli tunnel-hub, without leaving this machine: a tunnel client reverse-tunnels
@@ -147,6 +150,7 @@ Examples:
147150
adminPort, _ := cmd.Flags().GetInt("admin-port")
148151
servePort, _ := cmd.Flags().GetInt("serve-port")
149152
mxbuildPath, _ := cmd.Flags().GetString("mxbuild-path")
153+
dbType, _ := cmd.Flags().GetString("db-type")
150154
dbHost, _ := cmd.Flags().GetString("db-host")
151155
dbName, _ := cmd.Flags().GetString("db-name")
152156
dbUser, _ := cmd.Flags().GetString("db-user")
@@ -219,6 +223,7 @@ Examples:
219223
TraceService: traceService,
220224
TraceOTLP: traceOTLP,
221225
DB: docker.DBConfig{
226+
Type: dbType,
222227
Host: dbHost,
223228
Name: dbName,
224229
User: dbUser,
@@ -313,6 +318,7 @@ func init() {
313318
runCmd.Flags().Int("admin-port", 0, "M2EE admin API port (default 8090)")
314319
runCmd.Flags().Int("serve-port", 0, "mxbuild --serve port (default 6543)")
315320
runCmd.Flags().String("mxbuild-path", "", "Path to the mxbuild to build with, overriding resolution (Studio Pro's bundled mxbuild on macOS/Windows, the cached CDN download on Linux)")
321+
runCmd.Flags().String("db-type", "", "Database type for a local run: postgresql (default) or hsqldb (the runtime's built-in file database — no server, no --db-host/--db-user/--db-password, data under <project>/deployment/data/database/hsqldb/)")
316322
runCmd.Flags().String("db-host", "", "Database host:port (IPv6: [::1]:5432; default 127.0.0.1:5432)")
317323
runCmd.Flags().String("db-name", "", "Database name (default derived from the project name)")
318324
runCmd.Flags().String("db-user", "", "Database user (default mendix)")

‎cmd/mxcli/docker/dbtype.go‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// SPDX-License-Identifier: Apache-2.0
2+
3+
package docker
4+
5+
import (
6+
"fmt"
7+
"strings"
8+
)
9+
10+
// Canonical database types a local run understands. The runtime's own enum also
11+
// has Db2/MySql/Oracle/SapHana/SqlServer; those all need a server and are out of
12+
// scope for `run --local`.
13+
const (
14+
DBTypePostgreSQL = "postgresql"
15+
DBTypeHSQLDB = "hsqldb"
16+
)
17+
18+
// NormalizeDBType maps a user-supplied --db-type to a canonical value. Empty
19+
// means PostgreSQL, which is what a local run has always used, so the flag stays
20+
// backwards compatible.
21+
func NormalizeDBType(raw string) (string, error) {
22+
switch strings.ToLower(strings.TrimSpace(raw)) {
23+
case "", DBTypePostgreSQL, "postgres":
24+
return DBTypePostgreSQL, nil
25+
case DBTypeHSQLDB:
26+
return DBTypeHSQLDB, nil
27+
default:
28+
return "", fmt.Errorf("unknown --db-type %q (want postgresql or hsqldb)", raw)
29+
}
30+
}
31+
32+
// IsFileBasedDBType reports whether a canonical type is the runtime's built-in
33+
// file database, which has no host to reach and no credentials.
34+
func IsFileBasedDBType(canonical string) bool {
35+
return canonical == DBTypeHSQLDB
36+
}
37+
38+
// RuntimeDatabaseType maps a canonical type to the spelling the runtime's
39+
// DatabaseType parameter expects (the runtime enum is upper case).
40+
func RuntimeDatabaseType(canonical string) string {
41+
if canonical == DBTypeHSQLDB {
42+
return "HSQLDB"
43+
}
44+
return "PostgreSQL"
45+
}

‎cmd/mxcli/docker/dbtype_test.go‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// SPDX-License-Identifier: Apache-2.0
2+
3+
package docker
4+
5+
import "testing"
6+
7+
func TestNormalizeDBType(t *testing.T) {
8+
cases := []struct {
9+
in string
10+
want string
11+
wantErr bool
12+
}{
13+
{"", DBTypePostgreSQL, false},
14+
{"postgresql", DBTypePostgreSQL, false},
15+
{"PostgreSQL", DBTypePostgreSQL, false},
16+
{"postgres", DBTypePostgreSQL, false},
17+
{"hsqldb", DBTypeHSQLDB, false},
18+
{"HSQLDB", DBTypeHSQLDB, false},
19+
{" Hsqldb ", DBTypeHSQLDB, false},
20+
{"mysql", "", true},
21+
}
22+
for _, c := range cases {
23+
got, err := NormalizeDBType(c.in)
24+
if c.wantErr {
25+
if err == nil {
26+
t.Errorf("NormalizeDBType(%q) = %q, want error", c.in, got)
27+
}
28+
continue
29+
}
30+
if err != nil || got != c.want {
31+
t.Errorf("NormalizeDBType(%q) = %q, %v; want %q", c.in, got, err, c.want)
32+
}
33+
}
34+
}
35+
36+
func TestRuntimeDatabaseType(t *testing.T) {
37+
if got := RuntimeDatabaseType(DBTypeHSQLDB); got != "HSQLDB" {
38+
t.Errorf("RuntimeDatabaseType(hsqldb) = %q, want HSQLDB", got)
39+
}
40+
if got := RuntimeDatabaseType(DBTypePostgreSQL); got != "PostgreSQL" {
41+
t.Errorf("RuntimeDatabaseType(postgresql) = %q, want PostgreSQL", got)
42+
}
43+
}

‎cmd/mxcli/docker/localboot.go‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,9 @@ import (
3333
// already resolved, to <deployDir>/model/config.json — readDeploymentConstants
3434
// lifts them from there.
3535

36-
// DBConfig is the external Postgres the standalone runtime connects to.
36+
// DBConfig is the database the standalone runtime connects to: either an external
37+
// Postgres (Host/User/Password set) or the runtime's built-in file database
38+
// (Type "HSQLDB", Host/User/Password empty — see applyDatabaseDefaults).
3739
type DBConfig struct {
3840
Type string // e.g. "PostgreSQL"
3941
Host string // "host:port", e.g. "127.0.0.1:5432"
@@ -42,6 +44,13 @@ type DBConfig struct {
4244
Password string
4345
}
4446

47+
// IsFileBased reports whether this is the runtime's built-in file database, which
48+
// has no host to reach. It keys on the runtime spelling that applyDatabaseDefaults
49+
// sets (RuntimeDatabaseType), not the raw --db-type flag.
50+
func (c DBConfig) IsFileBased() bool {
51+
return c.Type == RuntimeDatabaseType(DBTypeHSQLDB)
52+
}
53+
4554
// LocalRuntimeOptions configures StartLocalRuntime.
4655
type LocalRuntimeOptions struct {
4756
// DeployDir is the deployment directory (the runtime's BasePath). The mxbuild

‎cmd/mxcli/docker/localboot_test.go‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,24 @@ func TestRuntimeConfigParams_ApplicationRootUrl(t *testing.T) {
161161
}
162162
}
163163

164+
func TestRuntimeConfigParams_HSQLDB(t *testing.T) {
165+
o := testLocalOpts()
166+
o.DB = DBConfig{Type: "HSQLDB", Name: "appdb"}
167+
p := runtimeConfigParams(o, nil)
168+
checks := map[string]any{
169+
"DatabaseType": "HSQLDB",
170+
"DatabaseHost": "",
171+
"DatabaseName": "appdb",
172+
"DatabaseUserName": "",
173+
"DatabasePassword": "",
174+
}
175+
for k, want := range checks {
176+
if p[k] != want {
177+
t.Errorf("%s = %v, want %v", k, p[k], want)
178+
}
179+
}
180+
}
181+
164182
func TestReadDeploymentConstants(t *testing.T) {
165183
dir := t.TempDir()
166184
modelDir := filepath.Join(dir, "model")

‎cmd/mxcli/docker/runlocal.go‎

Lines changed: 50 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -182,21 +182,6 @@ func (o *LocalRunOptions) applyDefaults() {
182182
if o.PollInterval == 0 {
183183
o.PollInterval = time.Second
184184
}
185-
if o.DB.Type == "" {
186-
o.DB.Type = "PostgreSQL"
187-
}
188-
if o.DB.Host == "" {
189-
o.DB.Host = "127.0.0.1:5432"
190-
}
191-
if o.DB.User == "" {
192-
o.DB.User = "mendix"
193-
}
194-
if o.DB.Password == "" {
195-
o.DB.Password = "mendix"
196-
}
197-
if o.DB.Name == "" {
198-
o.DB.Name = deriveDBName(o.ProjectPath)
199-
}
200185
if o.ScreenshotPath == "" {
201186
o.ScreenshotPath = filepath.Join(filepath.Dir(o.ProjectPath), ".mxcli", "run-local.png")
202187
}
@@ -214,6 +199,47 @@ func (o *LocalRunOptions) applyDefaults() {
214199
}
215200
}
216201

202+
// applyDatabaseDefaults validates --db-type and fills the connection settings the
203+
// chosen database needs. It is separate from applyDefaults because it can fail:
204+
// a flag combination that cannot work (--db-type hsqldb with --db-host) is a user
205+
// error, not something to silently normalise away.
206+
func (o *LocalRunOptions) applyDatabaseDefaults() error {
207+
kind, err := NormalizeDBType(o.DB.Type)
208+
if err != nil {
209+
return err
210+
}
211+
if o.DB.Name == "" {
212+
o.DB.Name = deriveDBName(o.ProjectPath)
213+
}
214+
if IsFileBasedDBType(kind) {
215+
// The built-in database is a file: it has no host or credentials, and
216+
// accepting them would imply a connection that never happens.
217+
if o.DB.Host != "" || o.DB.User != "" || o.DB.Password != "" {
218+
return fmt.Errorf("--db-type hsqldb uses the built-in file database and takes no " +
219+
"--db-host, --db-user or --db-password")
220+
}
221+
if o.EnsureDB {
222+
return fmt.Errorf("--ensure-db provisions PostgreSQL; the built-in HSQLDB database " +
223+
"needs no provisioning — drop --ensure-db")
224+
}
225+
o.DB.Type = RuntimeDatabaseType(kind)
226+
o.DB.Host, o.DB.User, o.DB.Password = "", "", ""
227+
return nil
228+
}
229+
// PostgreSQL (unchanged behaviour).
230+
if o.DB.Host == "" {
231+
o.DB.Host = "127.0.0.1:5432"
232+
}
233+
if o.DB.User == "" {
234+
o.DB.User = "mendix"
235+
}
236+
if o.DB.Password == "" {
237+
o.DB.Password = "mendix"
238+
}
239+
o.DB.Type = RuntimeDatabaseType(kind)
240+
return nil
241+
}
242+
217243
// defaultOtelSpanFilters are the internal runtime spans suppressed under --trace.
218244
// Unfiltered per-activity tracing is ~10x slower; these bring it near baseline
219245
// while keeping the microflow-level spans (findings — OpenTelemetry).
@@ -541,6 +567,9 @@ func sourceMTime(projectPath string) time.Time {
541567
// and hot-apply on every project change until interrupted.
542568
func RunLocal(opts LocalRunOptions) error {
543569
opts.applyDefaults()
570+
if err := opts.applyDatabaseDefaults(); err != nil {
571+
return err
572+
}
544573
w, stderr := opts.Stdout, opts.Stderr
545574

546575
// 0. Refuse fast if the loop's ports are already taken (a stale run/serve/
@@ -610,10 +639,12 @@ func RunLocal(opts LocalRunOptions) error {
610639
if err := EnsureDatabase(&opts.DB, w); err != nil {
611640
return fmt.Errorf("ensuring database: %w", err)
612641
}
613-
} else if err := pingTCP(opts.DB.Host, 3*time.Second); err != nil {
614-
return fmt.Errorf("database not reachable at %s: %w\n"+
615-
" Pass --ensure-db to provision it, or start Postgres and create the '%s' database (user %q).",
616-
opts.DB.Host, err, opts.DB.Name, opts.DB.User)
642+
} else if !opts.DB.IsFileBased() {
643+
if err := pingTCP(opts.DB.Host, 3*time.Second); err != nil {
644+
return fmt.Errorf("database not reachable at %s: %w\n"+
645+
" Pass --ensure-db to provision it, or start Postgres and create the '%s' database (user %q).",
646+
opts.DB.Host, err, opts.DB.Name, opts.DB.User)
647+
}
617648
}
618649

619650
// Setup-only: prerequisites are ready (mxbuild+runtime cached, database up).
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
// SPDX-License-Identifier: Apache-2.0
2+
3+
//go:build integration
4+
5+
package docker
6+
7+
import (
8+
"bytes"
9+
"io"
10+
"net/http"
11+
"os"
12+
"os/exec"
13+
"path/filepath"
14+
"testing"
15+
"time"
16+
)
17+
18+
// The point of the built-in database: an app boots with NO database server.
19+
// Modeled on localapp_integration_test.go — scaffold a project when no fixture
20+
// is given, build it with a real mxbuild serve, then boot the runtime with
21+
// HSQLDB and require it to answer. Self-contained: HSQLDB is a file, so there is
22+
// nothing else to stand up.
23+
func TestRunLocal_HSQLDBNeedsNoDatabaseServer(t *testing.T) {
24+
mprPath := os.Getenv("MXCLI_IT_PROJECT")
25+
if mprPath == "" {
26+
mxPath, err := ResolveMx("")
27+
if err != nil {
28+
t.Skipf("mx not resolvable and MXCLI_IT_PROJECT unset: %v", err)
29+
}
30+
dir, err := os.MkdirTemp("", "mxhsql")
31+
if err != nil {
32+
t.Fatal(err)
33+
}
34+
defer os.RemoveAll(dir)
35+
scaffold := exec.Command(mxPath, "create-project")
36+
scaffold.Dir = dir
37+
if out, err := scaffold.CombinedOutput(); err != nil {
38+
t.Skipf("mx create-project failed: %v\n%s", err, out)
39+
}
40+
mprPath = filepath.Join(dir, "App.mpr")
41+
}
42+
if _, err := os.Stat(mprPath); err != nil {
43+
t.Skipf("no project fixture at %s: %v", mprPath, err)
44+
}
45+
46+
reader, err := openReadOnly(mprPath)
47+
if err != nil {
48+
t.Skipf("cannot open project: %v", err)
49+
}
50+
version := reader.ProjectVersion().ProductVersion
51+
reader.Disconnect()
52+
53+
installPath, err := resolveRuntimeInstall(version, io.Discard)
54+
if err != nil {
55+
t.Skipf("no runtime for %s: %v", version, err)
56+
}
57+
javaMajor, _ := ProjectJavaMajor(mprPath)
58+
59+
serve, err := StartServe(ServeOptions{Version: version, JavaMajor: javaMajor, Host: "127.0.0.1", Port: 6549})
60+
if err != nil {
61+
t.Skipf("cannot start mxbuild serve: %v", err)
62+
}
63+
defer serve.Stop()
64+
65+
build, err := serve.Build(BuildRequest{Target: TargetDeploy, ProjectFilePath: mprPath})
66+
if err != nil {
67+
t.Fatalf("build: %v", err)
68+
}
69+
if !build.OK() {
70+
t.Fatalf("build failed: %s", build.Message)
71+
}
72+
73+
deployDir := filepath.Join(filepath.Dir(mprPath), "deployment")
74+
var rtOut bytes.Buffer
75+
rt, err := StartLocalRuntime(LocalRuntimeOptions{
76+
DeployDir: deployDir,
77+
InstallPath: installPath,
78+
JavaMajor: javaMajor,
79+
AdminPass: defaultLocalAdminPass,
80+
AppPort: 8087,
81+
AdminPort: 8097,
82+
DB: DBConfig{Type: "HSQLDB", Name: deriveDBName(mprPath)},
83+
Stdout: &rtOut,
84+
Stderr: &rtOut,
85+
})
86+
if err != nil {
87+
t.Fatalf("boot with the built-in database: %v", err)
88+
}
89+
defer rt.Stop()
90+
91+
client := &http.Client{Timeout: 5 * time.Second}
92+
deadline := time.Now().Add(90 * time.Second)
93+
for {
94+
resp, err := client.Get(rt.AppURL())
95+
if err == nil {
96+
resp.Body.Close()
97+
if resp.StatusCode == 200 {
98+
break
99+
}
100+
}
101+
if time.Now().After(deadline) {
102+
t.Fatalf("app did not answer 200 at %s\n--- runtime output ---\n%s", rt.AppURL(), rt.Log())
103+
}
104+
time.Sleep(time.Second)
105+
}
106+
107+
hsqlDir := filepath.Join(deployDir, "data", "database", "hsqldb")
108+
entries, err := os.ReadDir(hsqlDir)
109+
if err != nil || len(entries) == 0 {
110+
t.Fatalf("expected the built-in database files under %s (err=%v, n=%d)", hsqlDir, err, len(entries))
111+
}
112+
}

0 commit comments

Comments
 (0)