-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathOrmCommand.cpp
More file actions
496 lines (422 loc) · 14.1 KB
/
Copy pathOrmCommand.cpp
File metadata and controls
496 lines (422 loc) · 14.1 KB
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
/**
*
* @file OrmCommand.cpp
* @author Gaspard Kirira
*
* Copyright 2025, Gaspard Kirira. All rights reserved.
* https://github.com/vixcpp/vix
* Use of this source code is governed by a MIT license
* that can be found in the License file.
*
* Vix.cpp
*
*/
#if defined(_WIN32)
#include <vix/cli/platform/windows.hpp>
#endif
#include <vix/cli/commands/OrmCommand.hpp>
#include <vix/utils/Env.hpp>
#include <iostream>
#include <cstdlib>
#include <filesystem>
#include <string>
#if defined(__APPLE__)
#include <mach-o/dyld.h>
#endif
namespace fs = std::filesystem;
namespace
{
static const char *env_or(const char *k, const char *defv)
{
if (const char *v = vix::utils::vix_getenv(k))
return v;
return defv;
}
static std::string shell_quote(const std::string &s)
{
std::string out = "'";
for (char c : s)
{
if (c == '\'')
out += "'\\''";
else
out += c;
}
out += "'";
return out;
}
static fs::path get_exe_path()
{
#ifdef _WIN32
wchar_t buf[MAX_PATH];
DWORD len = GetModuleFileNameW(NULL, buf, MAX_PATH);
if (len == 0 || len == MAX_PATH)
return {};
return fs::path(buf);
#elif defined(__APPLE__)
uint32_t size = 0;
_NSGetExecutablePath(nullptr, &size);
std::string tmp(size, '\0');
if (_NSGetExecutablePath(tmp.data(), &size) != 0)
return {};
fs::path p = fs::path(tmp.c_str());
// resolve symlinks
std::error_code ec;
p = fs::weakly_canonical(p, ec);
return ec ? fs::path(tmp.c_str()) : p;
#else
std::error_code ec;
fs::path exe = fs::read_symlink("/proc/self/exe", ec);
if (ec || exe.empty())
return {};
return exe;
#endif
}
static fs::path get_exe_dir()
{
fs::path exe = get_exe_path();
if (exe.empty())
return {};
return exe.parent_path();
}
static std::string find_migrator_tool()
{
// New preferred env var
if (const char *t = vix::utils::vix_getenv("VIX_DB_TOOL"))
return std::string(t);
// Backward compat (old name)
if (const char *t = vix::utils::vix_getenv("VIX_ORM_TOOL"))
return std::string(t);
const auto try_paths = [](const std::vector<fs::path> &paths) -> std::string
{
for (const auto &p : paths)
{
if (!p.empty() && fs::exists(p))
return p.string();
}
return {};
};
if (fs::path binDir = get_exe_dir(); !binDir.empty())
{
fs::path prefix = binDir.parent_path();
// Installed layout candidates (vix_db_migrator)
std::vector<fs::path> installed = {
// your current install rule: ${CMAKE_INSTALL_LIBEXECDIR}/vix
prefix / "libexec" / "vix" / "vix_db_migrator",
// some distros / variants
prefix / "lib" / "vix" / "libexec" / "vix_db_migrator",
prefix / "lib" / "vix" / "vix_db_migrator",
// same dir as the CLI binary (dev installs)
binDir / "vix_db_migrator",
// Backward compat for older installs
prefix / "libexec" / "vix" / "vix_orm_migrator",
prefix / "lib" / "vix" / "libexec" / "vix_orm_migrator",
prefix / "lib" / "vix" / "vix_orm_migrator",
binDir / "vix_orm_migrator",
};
if (auto found = try_paths(installed); !found.empty())
return found;
}
// Dev build candidates (umbrella + module builds)
std::vector<fs::path> dev = {
// umbrella builds
fs::path("build/db_build/vix_db_migrator"),
fs::path("build/db_build/vix_db_migrator.exe"),
// module-local builds (varies by generator)
fs::path("modules/db/build/vix_db_migrator"),
fs::path("modules/db/build/vix_db_migrator.exe"),
fs::path("modules/db/build-ninja/vix_db_migrator"),
fs::path("modules/db/build-ninja/vix_db_migrator.exe"),
// relative when running from modules/cli
fs::path("../build/db_build/vix_db_migrator"),
fs::path("../build/db_build/vix_db_migrator.exe"),
fs::path("../db/build/vix_db_migrator"),
fs::path("../db/build/vix_db_migrator.exe"),
fs::path("../db/build-ninja/vix_db_migrator"),
fs::path("../db/build-ninja/vix_db_migrator.exe"),
// Backward compat dev paths (old orm tool)
fs::path("build/orm_build/vix_orm_migrator"),
fs::path("modules/orm/build/vix_orm_migrator"),
fs::path("../build/orm_build/vix_orm_migrator"),
fs::path("../orm/build/vix_orm_migrator"),
};
if (auto found = try_paths(dev); !found.empty())
return found;
// Final fallback: prefer new name, but keep old for legacy systems
return "vix_db_migrator";
}
static std::string get_flag(const std::vector<std::string> &args,
const std::string &key)
{
for (size_t i = 0; i + 1 < args.size(); ++i)
if (args[i] == key)
return args[i + 1];
return {};
}
static bool looks_like_vix_repo_root(const fs::path &p)
{
return fs::exists(p / "modules") &&
fs::is_directory(p / "modules") &&
fs::exists(p / "CMakeLists.txt");
}
static bool looks_like_app_root(const fs::path &p)
{
if (fs::exists(p / "CMakePresets.json"))
return true;
if (fs::exists(p / "src") && fs::is_directory(p / "src") && fs::exists(p / "CMakeLists.txt"))
return true;
return false;
}
static fs::path find_project_root(fs::path p)
{
fs::path best;
fs::path bestVix;
for (int depth = 0; depth < 12; ++depth)
{
if (looks_like_vix_repo_root(p))
bestVix = p;
if (looks_like_app_root(p))
best = p;
if (best.empty() && fs::exists(p / "CMakeLists.txt"))
best = p;
if (!p.has_parent_path())
break;
fs::path parent = p.parent_path();
if (parent == p)
break;
p = parent;
}
if (!bestVix.empty())
return bestVix;
if (!best.empty())
return best;
return {};
}
static fs::path detect_migrations_dir(const fs::path &projectDir)
{
if (looks_like_vix_repo_root(projectDir))
return {};
std::vector<fs::path> candidates = {
projectDir / "migrations",
projectDir / "db" / "migrations",
projectDir / "database" / "migrations",
projectDir / "sql" / "migrations",
projectDir / "db" / "sql",
projectDir / "migrations" / "mysql",
projectDir / "migrations" / "sqlite"};
for (const auto &c : candidates)
{
if (fs::exists(c) && fs::is_directory(c))
return c;
}
return {};
}
}
namespace vix::commands::OrmCommand
{
int run(const std::vector<std::string> &args)
{
if (args.empty() || args[0] == "-h" || args[0] == "--help")
return help();
const std::string sub = args[0];
if (sub != "migrate" && sub != "rollback" && sub != "status" && sub != "makemigrations")
{
std::cerr << "vix: unknown orm subcommand '" << sub << "'\n\n";
help();
return 1;
}
const bool is_make = (sub == "makemigrations");
auto parse_opt = [&](const std::string &key) -> std::string
{
// --key value
{
const std::string v = get_flag(args, key);
if (!v.empty())
return v;
}
// --key=value
const std::string prefix = key + "=";
for (const auto &a : args)
if (a.rfind(prefix, 0) == 0)
return a.substr(prefix.size());
return {};
};
auto flag_or_env = [&](const std::string &flag,
const char *envKey,
const char *defv) -> std::string
{
const std::string v = get_flag(args, flag);
if (!v.empty())
return v;
return env_or(envKey, defv);
};
// Project root
fs::path projectDir;
const std::string projFlag = get_flag(args, "--project-dir");
if (!projFlag.empty())
projectDir = fs::path(projFlag);
else
projectDir = find_project_root(fs::current_path());
if (projectDir.empty())
{
std::cerr << "vix orm: unable to detect project directory.\n";
std::cerr << "Tip: use --project-dir <path>\n";
return 1;
}
// Detect/resolve migrations dir
fs::path migDir;
const std::string dirFlag = get_flag(args, "--dir");
if (!dirFlag.empty())
{
migDir = fs::path(dirFlag);
if (migDir.is_relative())
migDir = fs::weakly_canonical(projectDir / migDir);
}
else
{
const std::string envDir = env_or("VIX_ORM_DIR", "");
if (!envDir.empty())
{
fs::path p = fs::path(envDir);
migDir = p.is_absolute() ? p : (projectDir / p);
}
else
{
migDir = detect_migrations_dir(projectDir);
}
if (migDir.empty())
migDir = projectDir / "migrations";
migDir = fs::weakly_canonical(migDir);
}
// Ensure migrations dir:
// - migrate/rollback/status => must exist
// - makemigrations => create it if missing
if (!fs::exists(migDir) || !fs::is_directory(migDir))
{
if (!is_make)
{
std::cerr << "vix orm: migrations directory not found: " << migDir.string() << "\n";
if (looks_like_app_root(projectDir))
{
std::cerr << "Tip: create it with:\n";
std::cerr << " mkdir -p " << (projectDir / "migrations").string() << "\n";
}
std::cerr << "Or pass: --dir <path>\n";
return 1;
}
else
{
std::error_code ec;
fs::create_directories(migDir, ec);
if (ec)
{
std::cerr << "vix orm makemigrations: cannot create migrations dir: " << migDir.string() << "\n";
return 1;
}
}
}
// Tool path
std::string tool = get_flag(args, "--tool");
if (tool.empty())
tool = find_migrator_tool();
std::string cmd;
cmd += shell_quote(tool) + " ";
if (is_make)
{
// REQUIRED
const std::string newSchema = parse_opt("--new");
if (newSchema.empty())
{
std::cerr << "vix orm makemigrations requires: --new <schema.json>\n";
return 1;
}
std::string snapshot = parse_opt("--snapshot");
if (snapshot.empty())
snapshot = "schema.json";
std::string name = parse_opt("--name");
if (name.empty())
name = "auto";
std::string dialect = parse_opt("--dialect");
if (dialect.empty())
dialect = "mysql";
fs::path newPath = fs::path(newSchema);
if (newPath.is_relative())
newPath = fs::weakly_canonical(projectDir / newPath);
fs::path snapPath = fs::path(snapshot);
if (snapPath.is_relative())
snapPath = fs::weakly_canonical(projectDir / snapPath);
cmd += "makemigrations ";
cmd += "--new " + shell_quote(newPath.string()) + " ";
cmd += "--snapshot " + shell_quote(snapPath.string()) + " ";
cmd += "--dir " + shell_quote(migDir.string()) + " ";
cmd += "--name " + shell_quote(name) + " ";
cmd += "--dialect " + shell_quote(dialect);
}
else
{
const std::string host = flag_or_env("--host", "VIX_ORM_HOST", "tcp://127.0.0.1:3306");
const std::string user = flag_or_env("--user", "VIX_ORM_USER", "root");
const std::string pass = flag_or_env("--pass", "VIX_ORM_PASS", "");
const std::string db = flag_or_env("--db", "VIX_ORM_DB", "vixdb");
cmd += shell_quote(host) + " ";
cmd += shell_quote(user) + " ";
cmd += shell_quote(pass) + " ";
cmd += shell_quote(db) + " ";
cmd += shell_quote(sub);
if (sub == "rollback")
{
std::string steps = get_flag(args, "--steps");
if (steps.empty())
{
std::cerr << "vix orm rollback requires: --steps <n>\n";
return 1;
}
cmd += " --steps " + shell_quote(steps);
}
cmd += " --dir " + shell_quote(migDir.string());
}
int rc = std::system(cmd.c_str());
return rc == 0 ? 0 : 1;
}
int help()
{
std::ostream &out = std::cout;
out << "Vix ORM\n";
out << "Database migrations & schema management\n\n";
out << "Usage:\n";
out << " vix orm migrate [options]\n";
out << " vix orm rollback --steps <n> [options]\n";
out << " vix orm status [options]\n\n";
out << " vix orm makemigrations --new <schema.json> [options]\n\n";
out << "Makemigrations options:\n";
out << " --new <path> New schema json (required)\n";
out << " --snapshot <path> Previous snapshot (default: schema.json)\n";
out << " --name <label> Migration label (default: auto)\n";
out << " --dialect <mysql|sqlite> SQL dialect (default: mysql)\n\n";
out << "Common options:\n";
out << " --db <name> Database name (overrides VIX_ORM_DB)\n";
out << " --dir <path> Migrations directory (overrides VIX_ORM_DIR)\n";
out << " --host <uri> MySQL URI (default: tcp://127.0.0.1:3306)\n";
out << " --user <name> Database user (default: root)\n";
out << " --pass <pass> Database password\n";
out << " --project-dir <path> Force project root detection\n";
out << " --tool <path> Override migrator executable path\n";
out << " -h, --help Show this help\n\n";
out << "Rollback options:\n";
out << " --steps <n> Rollback last N applied migrations (required)\n\n";
out << "Environment defaults:\n";
out << " VIX_ORM_HOST Default DB host (tcp://127.0.0.1:3306)\n";
out << " VIX_ORM_USER Default DB user (root)\n";
out << " VIX_ORM_PASS Default DB password\n";
out << " VIX_ORM_DB Default DB name (vixdb)\n";
out << " VIX_ORM_DIR Default migrations dir (migrations)\n";
out << " VIX_ORM_TOOL Default migrator executable path\n\n";
out << "Examples:\n";
out << " vix orm migrate --db blog_db --dir ./migrations\n";
out << " vix orm rollback --steps 1 --db blog_db --dir ./migrations\n";
out << " vix orm status --db blog_db\n";
out << " VIX_ORM_DB=blog_db vix orm migrate --dir ./migrations\n";
out << " vix orm makemigrations --new ./schema.new.json --snapshot ./schema.json --dir ./migrations --name create_users --dialect mysql\n";
return 0;
}
}