Skip to content

A native macOS / windows / Linux database IDE built with Swift and AppKit. Connect to PostgreSQL, MySQL, SQLite, and Redis from a single app with a fast, keyboard-driven interface.

C++

v0.1.7: ClickHouse adapter + function source viewer (#23)

haidang181091b247e21dbf
diff --git a/windows/Gridex/ClickHouseAdapter.cpp b/windows/Gridex/ClickHouseAdapter.cpp
new file mode 100644
index 0000000..9f2076c
--- /dev/null
+++ b/windows/Gridex/ClickHouseAdapter.cpp
@@ -0,0 +1,681 @@
+// windows.h transitively drags in the legacy winsock.h whose structs
+// (sockaddr, fd_set, timeval...) clash with winsock2.h. Gate that off
+// with WIN32_LEAN_AND_MEAN and explicitly include winsock2 FIRST so
+// httplib's own winsock2 include is a no-op. Order here matters —
+// do not rearrange.
+#define WIN32_LEAN_AND_MEAN
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#include <windows.h>
+
+#pragma warning(push)
+#pragma warning(disable: 4996) // deprecation inside httplib
+#include <httplib.h>
+#pragma warning(pop)
+
+#include <nlohmann/json.hpp>
+
+#include "Models/ClickHouseAdapter.h"
+#include <chrono>
+#include <sstream>
+#include <algorithm>
+
+namespace DBModels
+{
+ // ── Pimpl struct ──────────────────────────────────────────────────────────
+ // Owns the single httplib::Client kept alive for the session.
+ // One client = one persistent TCP connection (httplib keep-alive default).
+ struct ClickHouseAdapter::Impl
+ {
+ std::unique_ptr<httplib::Client> client;
+ std::string host; // UTF-8
+ int port = 8123;
+ std::string user;
+ std::string password;
+ std::string database; // current DB sent as query param
+ };
+
+ // ── UTF-8 <-> wstring helpers ─────────────────────────────────────────────
+ std::string ClickHouseAdapter::toUtf8(const std::wstring& wstr)
+ {
+ if (wstr.empty()) return {};
+ int size = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(),
+ static_cast<int>(wstr.size()), nullptr, 0, nullptr, nullptr);
+ std::string result(size, '\0');
+ WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(),
+ static_cast<int>(wstr.size()), &result[0], size, nullptr, nullptr);
+ return result;
+ }
+
+ std::wstring ClickHouseAdapter::fromUtf8(const std::string& str)
+ {
+ if (str.empty()) return {};
+ int size = MultiByteToWideChar(CP_UTF8, 0, str.c_str(),
+ static_cast<int>(str.size()), nullptr, 0);
+ std::wstring result(size, L'\0');
+ MultiByteToWideChar(CP_UTF8, 0, str.c_str(),
+ static_cast<int>(str.size()), &result[0], size);
+ return result;
+ }
+
+ // Backtick-quote an identifier (ClickHouse / MySQL style).
+ std::string ClickHouseAdapter::quoteIdentifier(const std::wstring& name)
+ {
+ std::string utf8 = toUtf8(name);
+ // Escape any backtick that already appears inside the name.
+ std::string escaped;
+ escaped.reserve(utf8.size() + 2);
+ escaped += '`';
+ for (char c : utf8)
+ {
+ if (c == '`') escaped += "``";
+ else escaped += c;
+ }
+ escaped += '`';
+ return escaped;
+ }
+
+ // Single-quote a string literal with single-quote escaping.
+ std::string ClickHouseAdapter::quoteLiteral(const std::wstring& value)
+ {
+ std::string utf8 = toUtf8(value);
+ std::string escaped;
+ escaped.reserve(utf8.size() + 2);
+ escaped += '\'';
+ for (char c : utf8)
+ {
+ if (c == '\'') escaped += "\\'"; // ClickHouse accepts \'
+ else if (c == '\\') escaped += "\\\\";
+ else escaped += c;
+ }
+ escaped += '\'';
+ return escaped;
+ }
+
+ // Public wstring-returning variants used by callers that build wide SQL.
+ std::wstring ClickHouseAdapter::quoteSqlLiteral(const std::wstring& value) const
+ {
+ return fromUtf8(quoteLiteral(value));
+ }
+
+ std::wstring ClickHouseAdapter::quoteSqlIdentifier(const std::wstring& name) const
+ {
+ return fromUtf8(quoteIdentifier(name));
+ }
+
+ void ClickHouseAdapter::ensureConnected() const
+ {
+ if (!connected_ || !impl_ || !impl_->client)
+ throw DatabaseError(DatabaseError::Code::ConnectionFailed,
+ "Not connected to ClickHouse");
+ }
+
+ // ── Constructor / Destructor ──────────────────────────────────────────────
+ ClickHouseAdapter::ClickHouseAdapter()
+ : impl_(std::make_unique<Impl>())
+ {}
+
+ ClickHouseAdapter::~ClickHouseAdapter() { disconnect(); }
+
+ // ── Connection ────────────────────────────────────────────────────────────
+ void ClickHouseAdapter::connect(const ConnectionConfig& config,
+ const std::wstring& password)
+ {
+ disconnect();
+
+ impl_->host = toUtf8(config.host);
+ impl_->port = config.port > 0 ? config.port : 8123;
+ impl_->user = toUtf8(config.username);
+ impl_->password = toUtf8(password);
+ impl_->database = toUtf8(config.database);
+ currentDb_ = config.database;
+
+ // Plain HTTP only. Vendored cpp-httplib is built without
+ // CPPHTTPLIB_OPENSSL_SUPPORT, so httplib::SSLClient is not
+ // available. Users who need TLS should front ClickHouse with
+ // an nginx/Caddy terminator and point us at the plaintext
+ // backend — matches how most CH deployments look anyway.
+ impl_->client = std::make_unique<httplib::Client>(
+ impl_->host, impl_->port);
+
+ impl_->client->set_connection_timeout(10);
+ impl_->client->set_read_timeout(30);
+
+ // Verify connectivity with a trivial query.
+ auto probe = executeInternal("SELECT 1");
+ if (!probe.success)
+ throw DatabaseError(DatabaseError::Code::ConnectionFailed,
+ toUtf8(probe.error));
+
+ connected_ = true;
+ }
+
+ void ClickHouseAdapter::disconnect()
+ {
+ connected_ = false;
+ if (impl_)
+ impl_->client.reset();
+ }
+
+ bool ClickHouseAdapter::testConnection(const ConnectionConfig& config,
+ const std::wstring& password)
+ {
+ try
+ {
+ connect(config, password);
+ disconnect();
+ return true;
+ }
+ catch (...)
+ {
+ disconnect();
+ return false;
+ }
+ }
+
+ bool ClickHouseAdapter::isConnected() const
+ {
+ return connected_ && impl_ && impl_->client;
+ }
+
+ // ── Core HTTP query execution ─────────────────────────────────────────────
+ // Appends "FORMAT JSONCompact" to SELECT-like statements so results come
+ // back as:
+ // { "meta": [{"name":"col","type":"T"},...],
+ // "data": [[v1,v2,...], ...],
+ // "rows": N }
+ // DDL / DML (ALTER, INSERT, etc.) gets no FORMAT suffix.
+ static bool needsFormat(const std::string& sql)
+ {
+ // Quick heuristic: trim leading whitespace, check first keyword.
+ size_t i = 0;
+ while (i < sql.size() && std::isspace((unsigned char)sql[i])) ++i;
+ if (i >= sql.size()) return false;
+ // Convert first 10 chars to uppercase for comparison
+ std::string head = sql.substr(i, 10);
+ std::transform(head.begin(), head.end(), head.begin(),
+ [](unsigned char c) { return (char)std::toupper(c); });
+ return head.rfind("SELECT", 0) == 0 ||
+ head.rfind("SHOW", 0) == 0 ||
+ head.rfind("DESC", 0) == 0 ||
+ head.rfind("EXPLAIN",0) == 0 ||
+ head.rfind("WITH", 0) == 0;
+ }
+
+ QueryResult ClickHouseAdapter::executeInternal(const std::string& sql)
+ {
+ QueryResult result;
+ result.sql = fromUtf8(sql);
+
+ if (!impl_ || !impl_->client)
+ {
+ result.success = false;
+ result.error = L"No active connection";
+ return result;
+ }
+
+ // Build query string: database param + output format
+ std::string body = sql;
+ bool isSelect = needsFormat(sql);
+ if (isSelect) body += " FORMAT JSONCompact";
+
+ // Query params
+ std::string params = "?";
+ if (!impl_->database.empty())
+ params += "database=" + impl_->database + "&";
+ params += "default_format=JSONCompact";
+
+ // Build request with auth headers
+ httplib::Headers headers = {
+ { "X-ClickHouse-User", impl_->user },
+ { "X-ClickHouse-Key", impl_->password },
+ { "Content-Type", "text/plain; charset=utf-8" }
+ };
+
+ auto t0 = std::chrono::high_resolution_clock::now();
+ auto res = impl_->client->Post(params.c_str(), headers, body, "text/plain");
+ auto t1 = std::chrono::high_resolution_clock::now();
+ result.executionTimeMs =
+ std::chrono::duration<double, std::milli>(t1 - t0).count();
+
+ if (!res)
+ {
+ // Network-level failure
+ result.success = false;
+ result.error = L"HTTP request failed (network error)";
+ return result;
+ }
+
+ if (res->status == 401)
+ {
+ result.success = false;
+ result.error = fromUtf8(res->body);
+ throw DatabaseError(DatabaseError::Code::AuthenticationFailed,
+ "ClickHouse authentication failed: " + res->body);
+ }
+
+ if (res->status != 200)
+ {
+ result.success = false;
+ // ClickHouse puts the error text in the body
+ result.error = fromUtf8(res->body);
+ return result;
+ }
+
+ // DDL / DML returns empty body on success
+ if (!isSelect || res->body.empty())
+ {
+ result.success = true;
+ result.totalRows = 0;
+ return result;
+ }
+
+ // Parse JSONCompact response
+ try
+ {
+ auto j = nlohmann::json::parse(res->body);
+
+ // Column metadata
+ auto& meta = j["meta"];
+ result.columnNames.reserve(meta.size());
+ result.columnTypes.reserve(meta.size());
+ for (auto& col : meta)
+ {
+ result.columnNames.push_back(fromUtf8(col["name"].get<std::string>()));
+ result.columnTypes.push_back(fromUtf8(col["type"].get<std::string>()));
+ }
+
+ // Row data
+ auto& data = j["data"];
+ result.rows.reserve(data.size());
+ for (auto& rowArr : data)
+ {
+ TableRow row;
+ row.reserve(result.columnNames.size());
+ for (size_t c = 0; c < result.columnNames.size() && c < rowArr.size(); ++c)
+ {
+ const auto& cell = rowArr[c];
+ if (cell.is_null())
+ row.emplace(result.columnNames[c], nullValue());
+ else if (cell.is_string())
+ row.emplace(result.columnNames[c], fromUtf8(cell.get<std::string>()));
+ else
+ // Numbers, booleans — serialize to string
+ row.emplace(result.columnNames[c], fromUtf8(cell.dump()));
+ }
+ result.rows.push_back(std::move(row));
+ }
+
+ result.totalRows = static_cast<int>(result.rows.size());
+ if (j.contains("rows"))
+ result.totalRows = j["rows"].get<int>();
+
+ result.success = true;
+ }
+ catch (const std::exception& ex)
+ {
+ result.success = false;
+ result.error = fromUtf8(std::string("JSON parse error: ") + ex.what());
+ }
+
+ return result;
+ }
+
+ QueryResult ClickHouseAdapter::execute(const std::wstring& sql)
+ {
+ ensureConnected();
+ return executeInternal(toUtf8(sql));
+ }
+
+ QueryResult ClickHouseAdapter::fetchRows(
+ const std::wstring& table, const std::wstring& schema,
+ int limit, int offset,
+ const std::wstring& orderBy, bool ascending)
+ {
+ ensureConnected();
+
+ // schema == database in ClickHouse (see listSchemas() note)
+ std::string db = schema.empty() ? impl_->database : toUtf8(schema);
+
+ std::string sql = std::string("SELECT * FROM `") + db + "`." + quoteIdentifier(table);
+ if (!orderBy.empty())
+ sql += " ORDER BY " + quoteIdentifier(orderBy) + (ascending ? " ASC" : " DESC");
+ sql += " LIMIT " + std::to_string(limit) + " OFFSET " + std::to_string(offset);
+
+ auto result = executeInternal(sql);
+
+ // Fetch total row count for pagination metadata.
+ // ClickHouse COUNT(*) is fast even on large tables (stored in system.tables).
+ std::string countSql = "SELECT COUNT(*) AS cnt FROM `" + db + "`." +
+ quoteIdentifier(table);
+ auto countResult = executeInternal(countSql);
+ if (countResult.success && !countResult.rows.empty())
+ {
+ auto it = countResult.rows[0].find(L"cnt");
+ if (it != countResult.rows[0].end() && !isNullCell(it->second))
+ {
+ try { result.totalRows = std::stoi(toUtf8(it->second)); }
+ catch (...) {}
+ }
+ }
+
+ result.currentPage = (offset / limit) + 1;
+ result.pageSize = limit;
+ return result;
+ }
+
+ // ── Schema Inspection ─────────────────────────────────────────────────────
+ std::vector<std::wstring> ClickHouseAdapter::listDatabases()
+ {
+ ensureConnected();
+ auto result = executeInternal(
+ "SELECT name FROM system.databases ORDER BY name");
+ std::vector<std::wstring> dbs;
+ for (auto& row : result.rows)
+ {
+ auto it = row.find(L"name");
+ if (it != row.end()) dbs.push_back(it->second);
+ }
+ return dbs;
+ }
+
+ // ClickHouse has no sub-database schemas. We expose one "schema"
+ // entry equal to the connected database so the sidebar tree is
+ // consistent with the PG adapter (schema node → tables list).
+ std::vector<std::wstring> ClickHouseAdapter::listSchemas()
+ {
+ ensureConnected();
+ return { currentDb_ };
+ }
+
+ std::vector<TableInfo> ClickHouseAdapter::listTables(const std::wstring& schema)
+ {
+ ensureConnected();
+ std::string db = schema.empty() ? impl_->database : toUtf8(schema);
+
+ std::string sql =
+ "SELECT name, engine, total_rows "
+ "FROM system.tables "
+ "WHERE database = " + quoteLiteral(fromUtf8(db)) +
+ " AND engine NOT LIKE '%View%' "
+ "ORDER BY name";
+
+ auto result = executeInternal(sql);
+ std::vector<TableInfo> tables;
+ for (auto& row : result.rows)
+ {
+ TableInfo info;
+ info.name = row[L"name"];
+ info.schema = fromUtf8(db);
+ info.type = L"table";
+ // engine maps to a comment-like extra field
+ auto engIt = row.find(L"engine");
+ if (engIt != row.end()) info.comment = engIt->second;
+ auto rowsIt = row.find(L"total_rows");
+ if (rowsIt != row.end() && !isNullCell(rowsIt->second))
+ {
+ try { info.estimatedRows = std::stoll(toUtf8(rowsIt->second)); }
+ catch (...) {}
+ }
+ tables.push_back(info);
+ }
+ return tables;
+ }
+
+ std::vector<TableInfo> ClickHouseAdapter::listViews(const std::wstring& schema)
+ {
+ ensureConnected();
+ std::string db = schema.empty() ? impl_->database : toUtf8(schema);
+
+ std::string sql =
+ "SELECT name, engine "
+ "FROM system.tables "
+ "WHERE database = " + quoteLiteral(fromUtf8(db)) +
+ " AND engine LIKE '%View%' "
+ "ORDER BY name";
+
+ auto result = executeInternal(sql);
+ std::vector<TableInfo> views;
+ for (auto& row : result.rows)
+ {
+ TableInfo info;
+ info.name = row[L"name"];
+ info.schema = fromUtf8(db);
+ info.type = L"view";
+ views.push_back(info);
+ }
+ return views;
+ }
+
+ std::vector<ColumnInfo> ClickHouseAdapter::describeTable(
+ const std::wstring& table, const std::wstring& schema)
+ {
+ ensureConnected();
+ std::string db = schema.empty() ? impl_->database : toUtf8(schema);
+
+ std::string sql =
+ "SELECT name, type, default_expression, is_in_primary_key "
+ "FROM system.columns "
+ "WHERE database = " + quoteLiteral(fromUtf8(db)) +
+ " AND table = " + quoteLiteral(table) +
+ " ORDER BY position";
+
+ auto result = executeInternal(sql);
+ std::vector<ColumnInfo> columns;
+ int pos = 1;
+ for (auto& row : result.rows)
+ {
+ ColumnInfo col;
+ col.name = row[L"name"];
+ col.dataType = row[L"type"];
+ // ClickHouse nullable columns: type is "Nullable(T)"
+ col.nullable = (col.dataType.find(L"Nullable") != std::wstring::npos);
+ col.ordinalPosition = pos++;
+
+ auto defIt = row.find(L"default_expression");
+ if (defIt != row.end() && !isNullCell(defIt->second))
+ col.defaultValue = defIt->second;
+
+ auto pkIt = row.find(L"is_in_primary_key");
+ if (pkIt != row.end())
+ col.isPrimaryKey = (pkIt->second == L"1" || pkIt->second == L"true");
+
+ // FK detection: ClickHouse has no FKs — always false.
+ col.isForeignKey = false;
+ columns.push_back(col);
+ }
+ return columns;
+ }
+
+ // ClickHouse has no index concept in the relational sense.
+ std::vector<IndexInfo> ClickHouseAdapter::listIndexes(
+ const std::wstring& /*table*/, const std::wstring& /*schema*/)
+ {
+ return {};
+ }
+
+ // ClickHouse has no foreign key constraints.
+ std::vector<ForeignKeyInfo> ClickHouseAdapter::listForeignKeys(
+ const std::wstring& /*table*/, const std::wstring& /*schema*/)
+ {
+ return {};
+ }
+
+ std::vector<std::wstring> ClickHouseAdapter::listFunctions(
+ const std::wstring& /*schema*/)
+ {
+ ensureConnected();
+ // Only surface user-defined functions (origin='SQLUserDefined').
+ // ClickHouse ships ~1000 built-ins (BIT_AND, sumMap, etc.) — showing
+ // them as sidebar entries swamps the UI and some consumers were
+ // even treating them as tables. User-defined scope matches what
+ // PG / MySQL show.
+ auto result = executeInternal(
+ "SELECT name FROM system.functions "
+ "WHERE origin = 'SQLUserDefined' ORDER BY name");
+ std::vector<std::wstring> funcs;
+ for (auto& row : result.rows)
+ {
+ auto it = row.find(L"name");
+ if (it != row.end()) funcs.push_back(it->second);
+ }
+ return funcs;
+ }
+
+ // For user-defined functions (CREATE FUNCTION ...), system.functions
+ // stores the full DDL in `create_query`. Built-ins have no source
+ // exposed — callers get an empty string and should render a stub.
+ //
+ // The raw create_query is `CREATE FUNCTION name AS ...` which errors
+ // with FUNCTION_ALREADY_EXISTS if the user tweaks + re-runs it.
+ // Rewrite to `CREATE OR REPLACE FUNCTION` so Run is idempotent and
+ // doubles as a cheap edit flow.
+ std::wstring ClickHouseAdapter::getFunctionSource(
+ const std::wstring& name, const std::wstring& /*schema*/)
+ {
+ ensureConnected();
+ auto result = executeInternal(
+ "SELECT create_query FROM system.functions "
+ "WHERE name = " + quoteLiteral(name) + " LIMIT 1");
+ if (result.rows.empty()) return L"";
+ auto it = result.rows[0].find(L"create_query");
+ if (it == result.rows[0].end()) return L"";
+
+ std::wstring src = it->second;
+ const std::wstring prefix = L"CREATE FUNCTION ";
+ if (src.rfind(prefix, 0) == 0)
+ src = L"CREATE OR REPLACE FUNCTION " + src.substr(prefix.size());
+ return src;
+ }
+
+ std::wstring ClickHouseAdapter::getCreateTableSQL(
+ const std::wstring& table, const std::wstring& schema)
+ {
+ ensureConnected();
+ std::string db = schema.empty() ? impl_->database : toUtf8(schema);
+
+ // SHOW CREATE TABLE returns a single row with the DDL string.
+ std::string sql = "SHOW CREATE TABLE `" + db + "`." + quoteIdentifier(table);
+ auto result = executeInternal(sql);
+ if (!result.rows.empty())
+ {
+ // Column name varies by CH version: "statement" or "CREATE TABLE ..."
+ for (auto& [k, v] : result.rows[0])
+ if (!isNullCell(v) && !v.empty()) return v;
+ }
+ return L"";
+ }
+
+ // ── Data Manipulation ─────────────────────────────────────────────────────
+ QueryResult ClickHouseAdapter::insertRow(
+ const std::wstring& table, const std::wstring& schema,
+ const TableRow& values)
+ {
+ ensureConnected();
+ std::string db = schema.empty() ? impl_->database : toUtf8(schema);
+
+ std::string sql = "INSERT INTO `" + db + "`." + quoteIdentifier(table) + " (";
+ std::string vals;
+ bool first = true;
+ for (auto& [col, val] : values)
+ {
+ if (!isNullCell(val) && val.empty()) continue; // skip blank → DEFAULT
+ if (!first) { sql += ", "; vals += ", "; }
+ sql += quoteIdentifier(col);
+ vals += isNullCell(val) ? "NULL" : quoteLiteral(val);
+ first = false;
+ }
+ if (first)
+ {
+ // No values provided — ClickHouse does not support DEFAULT VALUES
+ // syntax; emit an explicit empty insert (will fail on NOT NULL cols,
+ // which is the correct behaviour).
+ sql = "INSERT INTO `" + db + "`." + quoteIdentifier(table) + " VALUES ()";
+ }
+ else
+ {
+ sql += ") VALUES (" + vals + ")";
+ }
+ return executeInternal(sql);
+ }
+
+ // ClickHouse UPDATE syntax: ALTER TABLE t UPDATE col=val WHERE ...
+ // (Unlike standard SQL which uses UPDATE t SET col=val WHERE ...).
+ QueryResult ClickHouseAdapter::updateRow(
+ const std::wstring& table, const std::wstring& schema,
+ const TableRow& setValues, const TableRow& whereValues)
+ {
+ ensureConnected();
+ std::string db = schema.empty() ? impl_->database : toUtf8(schema);
+
+ std::string sql = "ALTER TABLE `" + db + "`." + quoteIdentifier(table) + " UPDATE ";
+ bool first = true;
+ for (auto& [col, val] : setValues)
+ {
+ if (!first) sql += ", ";
+ sql += quoteIdentifier(col) + " = " +
+ (isNullCell(val) ? "NULL" : quoteLiteral(val));
+ first = false;
+ }
+ sql += " WHERE ";
+ first = true;
+ for (auto& [col, val] : whereValues)
+ {
+ if (!first) sql += " AND ";
+ if (isNullCell(val))
+ sql += quoteIdentifier(col) + " IS NULL";
+ else
+ sql += quoteIdentifier(col) + " = " + quoteLiteral(val);
+ first = false;
+ }
+ return executeInternal(sql);
+ }
+
+ // ClickHouse DELETE syntax: ALTER TABLE t DELETE WHERE ...
+ QueryResult ClickHouseAdapter::deleteRow(
+ const std::wstring& table, const std::wstring& schema,
+ const TableRow& whereValues)
+ {
+ ensureConnected();
+ std::string db = schema.empty() ? impl_->database : toUtf8(schema);
+
+ std::string sql = "ALTER TABLE `" + db + "`." + quoteIdentifier(table) + " DELETE WHERE ";
+ bool first = true;
+ for (auto& [col, val] : whereValues)
+ {
+ if (!first) sql += " AND ";
+ if (isNullCell(val))
+ sql += quoteIdentifier(col) + " IS NULL";
+ else
+ sql += quoteIdentifier(col) + " = " + quoteLiteral(val);
+ first = false;
+ }
+ return executeInternal(sql);
+ }
+
+ // ── Transactions (no-ops) ─────────────────────────────────────────────────
+ // ClickHouse does not support classic ACID transactions by default.
+ // Mutations (ALTER ... UPDATE/DELETE) are applied asynchronously in
+ // the background; BEGIN/COMMIT/ROLLBACK would fail if sent.
+ void ClickHouseAdapter::beginTransaction() { /* no-op */ }
+ void ClickHouseAdapter::commitTransaction() { /* no-op */ }
+ void ClickHouseAdapter::rollbackTransaction() { /* no-op */ }
+
+ // ── Server Info ───────────────────────────────────────────────────────────
+ std::wstring ClickHouseAdapter::serverVersion()
+ {
+ ensureConnected();
+ auto result = executeInternal("SELECT version() AS ver");
+ if (!result.rows.empty())
+ {
+ auto it = result.rows[0].find(L"ver");
+ if (it != result.rows[0].end()) return it->second;
+ }
+ return L"Unknown";
+ }
+
+ std::wstring ClickHouseAdapter::currentDatabase()
+ {
+ return currentDb_;
+ }
+}
diff --git a/windows/Gridex/ConnectionManager.cpp b/windows/Gridex/ConnectionManager.cpp
index 2475a00..74f951b 100644
--- a/windows/Gridex/ConnectionManager.cpp
+++ b/windows/Gridex/ConnectionManager.cpp
@@ -6,6 +6,7 @@
#include "Models/RedisAdapter.h"
#include "Models/MongoDBAdapter.h"
#include "Models/MSSQLAdapter.h"
+#include "Models/ClickHouseAdapter.h"
namespace DBModels
{
@@ -147,6 +148,8 @@ namespace DBModels
return std::make_shared<MongoDBAdapter>();
case DatabaseType::MSSQLServer:
return std::make_shared<MSSQLAdapter>();
+ case DatabaseType::ClickHouse:
+ return std::make_shared<ClickHouseAdapter>();
default:
throw DatabaseError(DatabaseError::Code::ConnectionFailed,
"Unsupported database type");
diff --git a/windows/Gridex/DatabaseTypePickerDialog.cpp b/windows/Gridex/DatabaseTypePickerDialog.cpp
index 868f33f..262afa7 100644
--- a/windows/Gridex/DatabaseTypePickerDialog.cpp
+++ b/windows/Gridex/DatabaseTypePickerDialog.cpp
@@ -26,6 +26,7 @@ namespace winrt::Gridex::implementation
else if (tag == L"Redis") selectedType = DBModels::DatabaseType::Redis;
else if (tag == L"MongoDB") selectedType = DBModels::DatabaseType::MongoDB;
else if (tag == L"MSSQLServer") selectedType = DBModels::DatabaseType::MSSQLServer;
+ else if (tag == L"ClickHouse") selectedType = DBModels::DatabaseType::ClickHouse;
if (OnTypeSelected) OnTypeSelected(selectedType);
}
}
diff --git a/windows/Gridex/DatabaseTypePickerDialog.xaml b/windows/Gridex/DatabaseTypePickerDialog.xaml
index 305e5cd..b237f27 100644
--- a/windows/Gridex/DatabaseTypePickerDialog.xaml
+++ b/windows/Gridex/DatabaseTypePickerDialog.xaml
@@ -52,7 +52,7 @@
</Button>
</StackPanel>
- <!-- Row 2: Redis, MongoDB -->
+ <!-- Row 2: Redis, MongoDB, SQL Server -->
<StackPanel Orientation="Horizontal" Spacing="12"
HorizontalAlignment="Center">
<Button Tag="Redis" Click="TypeButton_Click"
@@ -95,5 +95,22 @@
</StackPanel>
</Button>
</StackPanel>
+ <!-- Row 3: ClickHouse -->
+ <StackPanel Orientation="Horizontal" Spacing="12"
+ HorizontalAlignment="Center">
+ <Button Tag="ClickHouse" Click="TypeButton_Click"
+ Padding="16,12" CornerRadius="8"
+ Background="Transparent" BorderThickness="1"
+ BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}">
+ <StackPanel Width="88" Spacing="8" HorizontalAlignment="Center">
+ <Border Width="48" Height="48" CornerRadius="12"
+ Background="#FFCC00" HorizontalAlignment="Center">
+ <FontIcon Glyph="&#xE968;" FontSize="24" Foreground="White" />
+ </Border>
+ <TextBlock Text="ClickHouse" FontSize="11" FontWeight="SemiBold"
+ HorizontalAlignment="Center" />
+ </StackPanel>
+ </Button>
+ </StackPanel>
</StackPanel>
</UserControl>
diff --git a/windows/Gridex/Gridex.items.props b/windows/Gridex/Gridex.items.props
index 7fa53bd..289edc6 100644
--- a/windows/Gridex/Gridex.items.props
+++ b/windows/Gridex/Gridex.items.props
@@ -79,6 +79,7 @@
<ClInclude Include="$(MSBuildThisFileDirectory)Models\RedisAdapter.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)Models\MongoDBAdapter.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)Models\MSSQLAdapter.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Models\ClickHouseAdapter.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)Models\SSHTunnelService.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)Models\ChangeTracker.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)Models\CredentialManager.h" />
@@ -295,6 +296,9 @@
<ClCompile Include="$(MSBuildThisFileDirectory)MSSQLAdapter.cpp">
<PrecompiledHeader>NotUsing</PrecompiledHeader>
</ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)ClickHouseAdapter.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
<ClCompile Include="$(MSBuildThisFileDirectory)SSHTunnelService.cpp">
<PrecompiledHeader>NotUsing</PrecompiledHeader>
</ClCompile>
diff --git a/windows/Gridex/Models/ChangeTracker.h b/windows/Gridex/Models/ChangeTracker.h
index f628076..3eaaca6 100644
--- a/windows/Gridex/Models/ChangeTracker.h
+++ b/windows/Gridex/Models/ChangeTracker.h
@@ -142,10 +142,18 @@ namespace DBModels
statements.push_back(generateInsert(table, schema, edit, dbType, columnTypes));
break;
case EditType::Update:
- statements.push_back(generateUpdate(table, schema, edit, dbType, columnTypes));
+ // ClickHouse uses ALTER TABLE ... UPDATE instead of standard UPDATE.
+ if (dbType == DatabaseType::ClickHouse)
+ statements.push_back(generateClickHouseUpdate(table, schema, edit, dbType, columnTypes));
+ else
+ statements.push_back(generateUpdate(table, schema, edit, dbType, columnTypes));
break;
case EditType::Delete:
- statements.push_back(generateDelete(table, schema, edit, dbType));
+ // ClickHouse uses ALTER TABLE ... DELETE instead of standard DELETE FROM.
+ if (dbType == DatabaseType::ClickHouse)
+ statements.push_back(generateClickHouseDelete(table, schema, edit, dbType));
+ else
+ statements.push_back(generateDelete(table, schema, edit, dbType));
break;
}
}
@@ -157,9 +165,10 @@ namespace DBModels
static std::wstring quoteId(const std::wstring& name, DatabaseType dbType)
{
- if (dbType == DatabaseType::MySQL)
+ if (dbType == DatabaseType::MySQL ||
+ dbType == DatabaseType::ClickHouse)
return L"`" + name + L"`";
- return L"\"" + name + L"\""; // PostgreSQL, SQLite
+ return L"\"" + name + L"\""; // PostgreSQL, SQLite, MSSQL
}
static std::wstring quoteLit(const std::wstring& value)
@@ -314,5 +323,32 @@ namespace DBModels
sql += L" WHERE " + buildWhere(edit.primaryKey, dbType);
return sql;
}
+
+ // ClickHouse mutation: ALTER TABLE db.t UPDATE col=val WHERE ...
+ static std::wstring generateClickHouseUpdate(
+ const std::wstring& table,
+ const std::wstring& schema,
+ const PendingEdit& edit,
+ DatabaseType dbType,
+ const std::unordered_map<std::wstring, std::wstring>& columnTypes = {})
+ {
+ std::wstring sql = L"ALTER TABLE " + qualifiedTable(table, schema, dbType) + L" UPDATE ";
+ sql += quoteId(edit.column, dbType) + L" = "
+ + quoteLitTyped(edit.column, edit.newValue, dbType, columnTypes);
+ sql += L" WHERE " + buildWhere(edit.primaryKey, dbType);
+ return sql;
+ }
+
+ // ClickHouse mutation: ALTER TABLE db.t DELETE WHERE ...
+ static std::wstring generateClickHouseDelete(
+ const std::wstring& table,
+ const std::wstring& schema,
+ const PendingEdit& edit,
+ DatabaseType dbType)
+ {
+ std::wstring sql = L"ALTER TABLE " + qualifiedTable(table, schema, dbType) + L" DELETE";
+ sql += L" WHERE " + buildWhere(edit.primaryKey, dbType);
+ return sql;
+ }
};
}
diff --git a/windows/Gridex/Models/ClickHouseAdapter.h b/windows/Gridex/Models/ClickHouseAdapter.h
new file mode 100644
index 0000000..66bfc2a
--- /dev/null
+++ b/windows/Gridex/Models/ClickHouseAdapter.h
@@ -0,0 +1,107 @@
+#pragma once
+#include "DatabaseAdapter.h"
+#include <string>
+#include <memory>
+
+// Forward-declare httplib types to keep this header lightweight.
+// The full httplib.h (WinSock + OpenSSL chain) is only pulled in
+// by ClickHouseAdapter.cpp via the Impl pimpl pattern.
+namespace httplib { class Client; }
+
+namespace DBModels
+{
+ // ClickHouse adapter — communicates via the ClickHouse HTTP interface
+ // (default port 8123). No native clickhouse-cpp client is used so
+ // there is no abseil/protobuf build dependency.
+ //
+ // Schema mapping: ClickHouse has no sub-database schemas.
+ // listSchemas() returns a single entry equal to the connected
+ // database name so the sidebar tree shows one "schema" node that
+ // contains the tables, matching the PG adapter's UX contract.
+ class ClickHouseAdapter : public DatabaseAdapter
+ {
+ public:
+ ClickHouseAdapter();
+ ~ClickHouseAdapter() override;
+
+ // ── Connection ──────────────────────────────
+ void connect(const ConnectionConfig& config, const std::wstring& password) override;
+ void disconnect() override;
+ bool testConnection(const ConnectionConfig& config, const std::wstring& password) override;
+ bool isConnected() const override;
+
+ // ── Query Execution ─────────────────────────
+ QueryResult execute(const std::wstring& sql) override;
+ QueryResult fetchRows(
+ const std::wstring& table, const std::wstring& schema,
+ int limit, int offset,
+ const std::wstring& orderBy, bool ascending) override;
+
+ // ── Schema Inspection ───────────────────────
+ std::vector<std::wstring> listDatabases() override;
+ std::vector<std::wstring> listSchemas() override;
+ std::vector<TableInfo> listTables(const std::wstring& schema) override;
+ std::vector<TableInfo> listViews(const std::wstring& schema) override;
+ std::vector<ColumnInfo> describeTable(
+ const std::wstring& table, const std::wstring& schema) override;
+ // ClickHouse has no index/FK concepts — returns empty vectors.
+ std::vector<IndexInfo> listIndexes(
+ const std::wstring& table, const std::wstring& schema) override;
+ std::vector<ForeignKeyInfo> listForeignKeys(
+ const std::wstring& table, const std::wstring& schema) override;
+ std::vector<std::wstring> listFunctions(const std::wstring& schema) override;
+ std::wstring getFunctionSource(
+ const std::wstring& name, const std::wstring& schema) override;
+ std::wstring getCreateTableSQL(
+ const std::wstring& table, const std::wstring& schema) override;
+
+ // ── Data Manipulation ───────────────────────
+ QueryResult insertRow(
+ const std::wstring& table, const std::wstring& schema,
+ const TableRow& values) override;
+ // ClickHouse UPDATE: ALTER TABLE t UPDATE col=val WHERE ...
+ QueryResult updateRow(
+ const std::wstring& table, const std::wstring& schema,
+ const TableRow& setValues, const TableRow& whereValues) override;
+ // ClickHouse DELETE: ALTER TABLE t DELETE WHERE ...
+ QueryResult deleteRow(
+ const std::wstring& table, const std::wstring& schema,
+ const TableRow& whereValues) override;
+
+ // ── Transactions ────────────────────────────
+ // ClickHouse has no classic transactions; these are no-ops
+ // that succeed silently (mutations are applied immediately).
+ void beginTransaction() override;
+ void commitTransaction() override;
+ void rollbackTransaction() override;
+
+ // ── Server Info ─────────────────────────────
+ std::wstring serverVersion() override;
+ std::wstring currentDatabase() override;
+
+ // ── SQL string assembly ─────────────────────
+ std::wstring quoteSqlLiteral(const std::wstring& value) const override;
+ std::wstring quoteSqlIdentifier(const std::wstring& name) const override;
+
+ private:
+ // Pimpl: keeps httplib headers out of all translation units
+ // that include this header (saves ~2 s compile time per TU).
+ struct Impl;
+ std::unique_ptr<Impl> impl_;
+
+ bool connected_ = false;
+ std::wstring currentDb_;
+
+ // ── Helpers ──────────────────────────────────
+ static std::string toUtf8(const std::wstring& wstr);
+ static std::wstring fromUtf8(const std::string& str);
+ // Backtick-quote an identifier for ClickHouse SQL.
+ static std::string quoteIdentifier(const std::wstring& name);
+ // Single-quote a string literal with escaping.
+ static std::string quoteLiteral(const std::wstring& value);
+ void ensureConnected() const;
+
+ // Execute a raw UTF-8 SQL string, parse JSONCompact response.
+ QueryResult executeInternal(const std::string& sql);
+ };
+}
diff --git a/windows/Gridex/Models/DatabaseType.h b/windows/Gridex/Models/DatabaseType.h
index b82158b..eaed6af 100644
--- a/windows/Gridex/Models/DatabaseType.h
+++ b/windows/Gridex/Models/DatabaseType.h
@@ -12,7 +12,8 @@ namespace DBModels
SQLite,
Redis,
MongoDB,
- MSSQLServer
+ MSSQLServer,
+ ClickHouse
};
inline std::wstring DatabaseTypeDisplayName(DatabaseType type)
@@ -25,6 +26,7 @@ namespace DBModels
case DatabaseType::Redis: return L"Redis";
case DatabaseType::MongoDB: return L"MongoDB";
case DatabaseType::MSSQLServer: return L"SQL Server";
+ case DatabaseType::ClickHouse: return L"ClickHouse";
default: return L"Unknown";
}
}
@@ -38,6 +40,7 @@ namespace DBModels
case DatabaseType::Redis: return 6379;
case DatabaseType::MongoDB: return 27017;
case DatabaseType::MSSQLServer: return 1433;
+ case DatabaseType::ClickHouse: return 8123;
default: return 0;
}
}
@@ -80,6 +83,17 @@ namespace DBModels
L"String", L"Int32", L"Int64", L"Double", L"Boolean",
L"Date", L"ObjectId", L"Array", L"Object", L"Binary"
};
+ case DatabaseType::ClickHouse:
+ return {
+ L"Array", L"Date", L"Date32", L"DateTime", L"DateTime64",
+ L"Decimal", L"Enum8", L"Enum16",
+ L"Float32", L"Float64",
+ L"Int8", L"Int16", L"Int32", L"Int64",
+ L"UInt8", L"UInt16", L"UInt32", L"UInt64",
+ L"IPv4", L"IPv6", L"JSON",
+ L"LowCardinality(String)", L"Map", L"Nullable(String)",
+ L"String", L"Tuple", L"UUID"
+ };
case DatabaseType::MSSQLServer:
return {
L"bigint", L"bit", L"char", L"date", L"datetime",
@@ -106,6 +120,7 @@ namespace DBModels
case DatabaseType::Redis: return L"\xE8D7"; // Permissions/Key
case DatabaseType::MongoDB: return L"\xE943"; // Globe/Document DB
case DatabaseType::MSSQLServer: return L"\xE968"; // Database
+ case DatabaseType::ClickHouse: return L"\xE968"; // Database (same glyph)
default: return L"\xE774";
}
}
diff --git a/windows/Gridex/SidebarPanel.cpp b/windows/Gridex/SidebarPanel.cpp
index 7d70334..3088ff5 100644
--- a/windows/Gridex/SidebarPanel.cpp
+++ b/windows/Gridex/SidebarPanel.cpp
@@ -618,7 +618,7 @@ namespace winrt::Gridex::implementation
item.type == DBModels::SidebarItemType::Function)
{
if (OnItemSelected)
- OnItemSelected(item.title, item.schema);
+ OnItemSelected(item.title, item.schema, item.type);
}
}
}
diff --git a/windows/Gridex/SidebarPanel.h b/windows/Gridex/SidebarPanel.h
index 3138146..4b19d7d 100644
--- a/windows/Gridex/SidebarPanel.h
+++ b/windows/Gridex/SidebarPanel.h
@@ -19,8 +19,12 @@ namespace winrt::Gridex::implementation
// SQL Open/Export/Import).
void SetDatabaseType(DBModels::DatabaseType type) { currentDbType_ = type; }
- // Callback invoked when user clicks a table/view/function
- std::function<void(const std::wstring& name, const std::wstring& schema)> OnItemSelected;
+ // Callback invoked when user clicks a table/view/function. The
+ // item type lets callers route Function clicks to a source-
+ // viewer flow instead of fetchRows.
+ std::function<void(const std::wstring& name,
+ const std::wstring& schema,
+ DBModels::SidebarItemType type)> OnItemSelected;
// Callback invoked when schema picker changes
std::function<void(const std::wstring& schema)> OnSchemaChanged;
diff --git a/windows/Gridex/WorkspacePage.cpp b/windows/Gridex/WorkspacePage.cpp
index 47f875b..19983fa 100644
--- a/windows/Gridex/WorkspacePage.cpp
+++ b/windows/Gridex/WorkspacePage.cpp
@@ -1322,6 +1322,18 @@ namespace winrt::Gridex::implementation
state_.statusSchema = config.database;
}
}
+ // ClickHouse: no schema concept, the connected database is the
+ // "schema". Without this branch currentSchema_ keeps the PG
+ // default "public" and listTables / fetchRows look for non-
+ // existent public.<table>.
+ else if (config.databaseType == DBModels::DatabaseType::ClickHouse)
+ {
+ if (!config.database.empty())
+ {
+ currentSchema_ = config.database;
+ state_.statusSchema = config.database;
+ }
+ }
UpdateBreadcrumb();
@@ -1604,9 +1616,14 @@ namespace winrt::Gridex::implementation
}
Sidebar().as<SidebarPanel>()->SetItems(state_.sidebarItems);
- Sidebar().as<SidebarPanel>()->OnItemSelected = [this](const std::wstring& name, const std::wstring& schema)
+ Sidebar().as<SidebarPanel>()->OnItemSelected =
+ [this](const std::wstring& name, const std::wstring& schema,
+ DBModels::SidebarItemType type)
{
- OnTableSelected(name, schema);
+ if (type == DBModels::SidebarItemType::Function)
+ ShowFunctionSource(name, schema);
+ else
+ OnTableSelected(name, schema);
};
// Feed table/function names to query editor autocomplete
@@ -1997,6 +2014,31 @@ namespace winrt::Gridex::implementation
SwitchContentView();
}
+ void WorkspacePage::ShowFunctionSource(
+ const std::wstring& name, const std::wstring& schema)
+ {
+ // Pull source via the active adapter. Each dialect maps this
+ // to its own metadata query (pg_proc / system.functions /
+ // mysql.proc / sys.sql_modules / ...).
+ std::wstring source;
+ try
+ {
+ auto adapter = connMgr_.getActiveAdapter();
+ if (adapter) source = adapter->getFunctionSource(name, schema);
+ }
+ catch (const std::exception&) { /* fall through — show stub */ }
+
+ if (source.empty())
+ source = L"-- " + name + L"\n-- (no source available for this function)";
+
+ // Reuse the query-tab flow: open a fresh tab, drop the DDL
+ // into the shared QueryEditorView. Matches how DataGrip /
+ // Navicat surface UDF bodies — user can tweak + re-run
+ // CREATE FUNCTION in place.
+ OpenNewQueryTab();
+ QueryEditor().as<QueryEditorView>()->SetSql(source);
+ }
+
// ── CRUD Operations ─────────────────────────────────
DBModels::TableRow WorkspacePage::ExtractPrimaryKey(int rowIndex)
@@ -4372,9 +4414,14 @@ g.er-selected > foreignObject > div.er-card{
state_.sidebarItems = { functionsGroup, tablesGroup, viewsGroup };
Sidebar().as<SidebarPanel>()->SetItems(state_.sidebarItems);
- Sidebar().as<SidebarPanel>()->OnItemSelected = [this](const std::wstring& name, const std::wstring& schema)
+ Sidebar().as<SidebarPanel>()->OnItemSelected =
+ [this](const std::wstring& name, const std::wstring& schema,
+ DBModels::SidebarItemType type)
{
- OnTableSelected(name, schema);
+ if (type == DBModels::SidebarItemType::Function)
+ ShowFunctionSource(name, schema);
+ else
+ OnTableSelected(name, schema);
};
}
diff --git a/windows/Gridex/WorkspacePage.h b/windows/Gridex/WorkspacePage.h
index 567f056..632e7ce 100644
--- a/windows/Gridex/WorkspacePage.h
+++ b/windows/Gridex/WorkspacePage.h
@@ -112,6 +112,10 @@ namespace winrt::Gridex::implementation
void SwitchContentView();
void OnTableSelected(const std::wstring& tableName, const std::wstring& schema);
void OpenNewQueryTab();
+ // Opens a read-only query tab showing the function's source
+ // (CREATE FUNCTION DDL or body) fetched via
+ // DatabaseAdapter::getFunctionSource.
+ void ShowFunctionSource(const std::wstring& name, const std::wstring& schema);
// ── CRUD Operations ─────────────────────────
void DeleteSelectedRow();
diff --git a/windows/README.md b/windows/README.md
index 0f0630a..f87250d 100644
--- a/windows/README.md
+++ b/windows/README.md
@@ -66,29 +66,29 @@ windows/scripts/
**Git Bash / MSYS2**:
```bash
cd /e/dev/be/vura
-powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-and-pack.ps1 -Version "0.1.6"
+powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-and-pack.ps1 -Version "0.1.7"
```
**PowerShell (5.1 / 7+)**:
```powershell
cd E:\dev\be\vura
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.6"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.7"
```
**CMD**:
```cmd
cd /d E:\dev\be\vura
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.6"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.7"
```
Script sẽ:
1. Cài/update `vpk` global tool (skip nếu đã có)
-2. Build `Gridex.exe` unpackaged, stamp version `0.1.6` vào About section
-3. Pack thành `Setup.exe` qua Velopack với metadata version `0.1.6`
+2. Build `Gridex.exe` unpackaged, stamp version `0.1.7` vào About section
+3. Pack thành `Setup.exe` qua Velopack với metadata version `0.1.7`
**Output**: `windows/Releases/`
- `Gridex-stable-Setup.exe` — installer user-facing
-- `Gridex-0.1.6-stable-full.nupkg` — package Velopack
+- `Gridex-0.1.7-stable-full.nupkg` — package Velopack
- `releases.stable.json`, `RELEASES-stable` — feed manifests
- `Gridex-stable-Portable.zip` — bản portable
@@ -140,7 +140,7 @@ powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\install-vp
powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-unpackaged.ps1
# Build với version cụ thể — About section hiện đúng string
-powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-unpackaged.ps1 -Version "0.1.6-test"
+powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-unpackaged.ps1 -Version "0.1.7-test"
```
**PowerShell**:
@@ -149,7 +149,7 @@ powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-unpa
powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-unpackaged.ps1
# Build với version cụ thể — About section hiện đúng string
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-unpackaged.ps1 -Version "0.1.6-test"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-unpackaged.ps1 -Version "0.1.7-test"
```
**CMD**:
@@ -158,7 +158,7 @@ REM Dev build — About section hiện "0.0.0-dev"
powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-unpackaged.ps1
REM Build với version cụ thể — About section hiện đúng string
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-unpackaged.ps1 -Version "0.1.6-test"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-unpackaged.ps1 -Version "0.1.7-test"
```
Chạy trực tiếp exe để test nhanh mà không cần cài installer:
@@ -177,17 +177,17 @@ Chạy trực tiếp exe để test nhanh mà không cần cài installer:
**Git Bash / MSYS2**:
```bash
-powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/pack-velopack.ps1 -Version "0.1.6-test"
+powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/pack-velopack.ps1 -Version "0.1.7-test"
```
**PowerShell**:
```powershell
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\pack-velopack.ps1 -Version "0.1.6-test"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\pack-velopack.ps1 -Version "0.1.7-test"
```
**CMD**:
```cmd
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\pack-velopack.ps1 -Version "0.1.6-test"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\pack-velopack.ps1 -Version "0.1.7-test"
```
**Lưu ý**: `-Version` truyền vào `pack-velopack.ps1` **phải khớp** với `-Version` truyền vào `build-unpackaged.ps1`, nếu không thì Velopack sẽ in một số, còn About section của app sẽ in số khác. Dùng `build-and-pack.ps1` ở trên để tránh trường hợp này.
@@ -196,10 +196,10 @@ powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\pack-velop
- `windows/Gridex/GridexVersion.h` — include unconditional file generated
- `windows/Gridex/GridexVersion.generated.h` — **auto-generated, gitignored**, do `build-unpackaged.ps1` ghi mỗi lần chạy
- - Có `-Version` → `#define GRIDEX_VERSION L"0.1.6"`
+ - Có `-Version` → `#define GRIDEX_VERSION L"0.1.7"`
- Không `-Version` → `#define GRIDEX_VERSION L"0.0.0-dev"`
- `windows/Gridex/SettingsPage.xaml.cpp` — đọc `GRIDEX_VERSION` và set vào `VersionText` text block
-- CI workflow `.github/workflows/windows-release.yml` tự parse version từ git tag (`v0.1.6` → `0.1.6`) và forward sang script
+- CI workflow `.github/workflows/windows-release.yml` tự parse version từ git tag (`v0.1.7` → `0.1.7`) và forward sang script
Build script chỉ rewrite `GridexVersion.generated.h` khi nội dung khác → không force recompile vô ích.
@@ -209,17 +209,17 @@ Mặc định Velopack dùng channel `stable`. Nếu muốn phát hành kênh ri
**Git Bash / MSYS2**:
```bash
-powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-and-pack.ps1 -Version "0.1.6-beta.1" -Channel "beta"
+powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-and-pack.ps1 -Version "0.1.7-beta.1" -Channel "beta"
```
**PowerShell**:
```powershell
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.6-beta.1" -Channel "beta"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.7-beta.1" -Channel "beta"
```
**CMD**:
```cmd
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.6-beta.1" -Channel "beta"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.7-beta.1" -Channel "beta"
```
Output sẽ là `Gridex-beta-Setup.exe` + `releases.beta.json` — auto-updater phân luồng theo channel.
@@ -253,7 +253,7 @@ Chưa cài đủ vcpkg deps. Xem section "Cài vcpkg deps" ở đầu file.
### Gridex.exe crash ngay khi khởi động với `MSVCP140.dll not found`
Máy thiếu VC++ 2015-2022 Redistributable. Script `build-unpackaged.ps1` tự copy CRT DLLs vào output folder → nếu vẫn lỗi thì check VS install path / logs script.
-### Setup.exe cài xong nhưng About hiện `0.0.0-dev` dù pack với `-Version 0.1.6`
+### Setup.exe cài xong nhưng About hiện `0.0.0-dev` dù pack với `-Version 0.1.7`
Dùng `build-and-pack.ps1` thay vì gọi `pack-velopack.ps1` trực tiếp. Trường hợp chạy `pack-velopack.ps1` với version khác version lúc build `Gridex.exe` → xóa `windows\Gridex\x64\Release\` rồi build lại đúng thứ tự.
### Lỗi `pwsh.exe exited with code 9009` trong vcpkg applocal step
@@ -288,8 +288,8 @@ del /q .\windows\Gridex\GridexVersion.generated.h
CI tự chạy khi push tag matching `v*.*.*`:
```bash
-git tag v0.1.6
-git push origin v0.1.6
+git tag v0.1.7
+git push origin v0.1.7
```
GitHub Actions workflow `windows-release.yml` sẽ tự build + pack + upload assets lên GitHub Release. Xem chi tiết ở `.github/workflows/windows-release.yml`.