1
1
mirror of https://github.com/Fabio286/antares.git synced 2025-06-05 21:59:22 +02:00

Compare commits

..

1 Commits

Author SHA1 Message Date
76dc66c14d chore(release): 0.3.10 2021-11-24 17:26:42 +01:00
99 changed files with 421 additions and 4184 deletions

View File

@@ -120,33 +120,6 @@
"contributions": [
"code"
]
},
{
"login": "wenj91",
"name": "文杰",
"avatar_url": "https://avatars.githubusercontent.com/u/12549338?v=4",
"profile": "https://github.com/wenj91",
"contributions": [
"code"
]
},
{
"login": "goYou",
"name": "goYou",
"avatar_url": "https://avatars.githubusercontent.com/u/62732795?v=4",
"profile": "https://github.com/goYou",
"contributions": [
"translation"
]
},
{
"login": "raliqala",
"name": "Topollo",
"avatar_url": "https://avatars.githubusercontent.com/u/30502407?v=4",
"profile": "https://github.com/raliqala",
"contributions": [
"code"
]
}
],
"contributorsPerLine": 7,

View File

@@ -12,18 +12,12 @@ jobs:
steps:
- name: Check out Git repository
uses: actions/checkout@v2
uses: actions/checkout@v1
- name: Install Node.js, NPM and Yarn
uses: actions/setup-node@v1
with:
node-version: 14
- name: Install dependencies
run: npm i
- name: Run tests
run: npm run test
- name: Build/release Electron app
uses: samuelmeuli/action-electron-builder@v1

View File

@@ -12,18 +12,12 @@ jobs:
steps:
- name: Check out Git repository
uses: actions/checkout@v2
uses: actions/checkout@v1
- name: Install Node.js, NPM and Yarn
uses: actions/setup-node@v1
with:
node-version: 14
- name: Install dependencies
run: npm i
- name: Run tests
run: npm run test
- name: Build/release Electron app
uses: samuelmeuli/action-electron-builder@v1

View File

@@ -8,23 +8,17 @@ jobs:
strategy:
matrix:
os: [windows-2019]
os: [windows-latest]
steps:
- name: Check out Git repository
uses: actions/checkout@v2
uses: actions/checkout@v1
- name: Install Node.js, NPM and Yarn
uses: actions/setup-node@v1
with:
node-version: 14
- name: Install dependencies
run: npm i
- name: Run tests
run: npm run test
- name: Build/release Electron app
uses: samuelmeuli/action-electron-builder@v1
with:

3
.gitignore vendored
View File

@@ -5,5 +5,4 @@ node_modules
thumbs.db
NOTES.md
*.txt
package-lock.json
*.heapsnapshot
package-lock.json

14
.vscode/launch.json vendored
View File

@@ -2,8 +2,8 @@
"version": "0.2.0",
"configurations": [
{
"name": "Electron: Main",
"cwd": "${workspaceFolder}",
"name": "Electron: Main",
"port": 9222,
"protocol": "inspector",
"request": "attach",
@@ -18,17 +18,7 @@
"sourceMaps": true,
"type": "chrome",
"webRoot": "${workspaceFolder}"
},
{
"name": "Electron: Worker",
"cwd": "${workspaceFolder}",
"port": 9224,
"protocol": "inspector",
"request": "attach",
"sourceMaps": true,
"type": "node",
"timeout": 1000000
},
}
],
"compounds": [
{

View File

@@ -4,8 +4,7 @@
"core",
"MySQL",
"PostgreSQL",
"SQLite",
"Windows"
"SQLite"
],
"svg.preview.background": "transparent"
}

View File

@@ -2,133 +2,7 @@
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
## [0.5.0](https://github.com/Fabio286/antares/compare/v0.4.4...v0.5.0) (2022-03-12)
### Features
* delete dump file when the export is canceled ([d25c62b](https://github.com/Fabio286/antares/commit/d25c62b4da9480e040d0bfac8b76732a4c69a5f1))
* initial db export implementation ([0de2321](https://github.com/Fabio286/antares/commit/0de232192076d1de827424c593ac9dff63903531))
* initial mysql import support ([4e9f8d1](https://github.com/Fabio286/antares/commit/4e9f8d16ee3c204d5f0c2bed081206f8b38207a6))
* mysql export for trigger, views, schedulers, functions and routines ([b2a5b40](https://github.com/Fabio286/antares/commit/b2a5b40c03d56bced5a7968c3454f36060e56dd0))
* **MySQL:** enhance export characters escaping ([3be826d](https://github.com/Fabio286/antares/commit/3be826df4b02ff0df0aa922d96755b31b7155784))
* **MySQL:** support to multi spatial fields export ([4be55f3](https://github.com/Fabio286/antares/commit/4be55f3fe9bb48324b780734762f2ff6da2ccb61))
* **PostgreSQL:** :sparkles: Postgress connection string feature for local and server connection string ([6305752](https://github.com/Fabio286/antares/commit/6305752ad117cc29c04bce3ce3df321f743cdc44))
* **PostgreSQL:** :sparkles: Postgress connection string feature for local and server connection string ([f4a63ea](https://github.com/Fabio286/antares/commit/f4a63eae2aca2a84647a5027137614950aef1eac))
* **UI:** auto-refresh schema at the end of the import process ([abf2b92](https://github.com/Fabio286/antares/commit/abf2b92e6e66b6668e698c5addf4e3c00ae5157b))
* **UI:** better real-time import stats ([a6f5645](https://github.com/Fabio286/antares/commit/a6f5645a226454cc2c415311ac321ba3d4db4454))
* **UI:** toggle tables checkbox by column on export modal ([1c4d5b0](https://github.com/Fabio286/antares/commit/1c4d5b05b3f94b3e7bef930aa7f89bdaa596c0b9))
### Bug Fixes
* **MySQL:** exception exporting empty procedures/functions ([ee415da](https://github.com/Fabio286/antares/commit/ee415da127d6d0de95aac901a2a01af863736344))
* **MySQL:** export crash with large databases ([8cf738b](https://github.com/Fabio286/antares/commit/8cf738bac85698fddd0504eef7844279e8c11f44))
* **MySQL:** missing functions and procedures definer escapes on exporter ([f0351e5](https://github.com/Fabio286/antares/commit/f0351e5b94830f9f52256096c2601b0ca9cd811d))
* **MySQL:** missing initial delimiter for exported procedures ([1a9fc37](https://github.com/Fabio286/antares/commit/1a9fc3728580f789727256d7893ca4bb90c16a50))
* **MySQL:** procedures exportation ([4276586](https://github.com/Fabio286/antares/commit/4276586e1141500401ff1ab570b29e485f459987))
* sql parser hangs during import ([7a6bd8b](https://github.com/Fabio286/antares/commit/7a6bd8bdbd69e3b5fe265d0bb0be844699dd77c2))
* wrong schema and table size on explore bar ([4479a96](https://github.com/Fabio286/antares/commit/4479a9600b5e59ef1bcf9135d661b4d7900a4bde))
* wrong soft sort algorithm for numeric fields, closes [#199](https://github.com/Fabio286/antares/issues/199) ([763be85](https://github.com/Fabio286/antares/commit/763be8532d2b61d0b4d45e72343f6a2e5fee1db9))
### Improvements
* avoid to load schema elements if already loaded in export modal ([d9d3bf2](https://github.com/Fabio286/antares/commit/d9d3bf2bc9d39ce8eec5dffbecbf767fbcf47782))
* **MySQL:** import performance improvement ([f444746](https://github.com/Fabio286/antares/commit/f444746f465ed0e8bd2e4c007faf17e167814278))
* **MySQL:** import tasks managed with async queue ([bbe13f2](https://github.com/Fabio286/antares/commit/bbe13f27dc29f997898f8c13f36b5d582770b21d))
* **MySQL:** improved several field types support on exporter ([1990d9a](https://github.com/Fabio286/antares/commit/1990d9a3d441f0e2075ac7e893d5b166275c48c0))
* **MySQL:** prevent memory leak on large dump import ([f3759b6](https://github.com/Fabio286/antares/commit/f3759b65411a40d92b98208176cdf8e6dd8230ce))
* **PostgreSQL:** :zap: Postgres connection update, better error handling and connection string accommodation. ([330a80f](https://github.com/Fabio286/antares/commit/330a80fe70b81f466f5e883029f42087b4b5c411))
* split the export select query to avoid running out of memory ([409ed54](https://github.com/Fabio286/antares/commit/409ed54608ad402b63fcc26a6e724bc447ba89d2))
* use fork() for the export process ([748d449](https://github.com/Fabio286/antares/commit/748d44977e76c6c8d6344df52e8e3ccfab84f670))
* use fork() for the import process ([573ac6d](https://github.com/Fabio286/antares/commit/573ac6d42ef833f250d102e5b30ae6cf5877f330))
### [0.4.4](https://github.com/Fabio286/antares/compare/v0.4.3...v0.4.4) (2022-02-27)
### Features
* execution notification for ROLLBACK and COMMIT ([76743e8](https://github.com/Fabio286/antares/commit/76743e8f7c02b824cb21540bfbcbe66ba43de8fa))
* **MySQL:** manual commit mode ([4ed2f9a](https://github.com/Fabio286/antares/commit/4ed2f9a93937b4293436a64318b7d6ae3a0d93c2))
* **PostgreSQL:** manual commit mode ([d81e091](https://github.com/Fabio286/antares/commit/d81e0911ab82fb75745ab11e67e867a00d8ac273))
* reminder for uncommitted changes closing a tab ([5bfff64](https://github.com/Fabio286/antares/commit/5bfff649e92f6fe5aba4b16aa4c8d5a5a70b31b2))
* **SQLite:** manual commit mode ([7dcd444](https://github.com/Fabio286/antares/commit/7dcd4441c49fafc0f47e12c2129708fe1092e1a4))
### Bug Fixes
* bigint support, closes [#197](https://github.com/Fabio286/antares/issues/197) ([b703955](https://github.com/Fabio286/antares/commit/b7039553ccaac4fd59e521530c4a053922854130))
* **MySQL:** default value not displayed for DECIMAL fields ([fa3f3e1](https://github.com/Fabio286/antares/commit/fa3f3e1fd8101f19f18df71e90d60fd37cdddaee))
* zero-padded bit fields beyond length ([265f28b](https://github.com/Fabio286/antares/commit/265f28b4d94cde4608a1d6d3d306824134808ec2))
### [0.4.3](https://github.com/Fabio286/antares/compare/v0.4.2...v0.4.3) (2022-01-30)
### Features
* add Simplified Chinese translation ([6ef565c](https://github.com/Fabio286/antares/commit/6ef565cf078cb3f5b7bcdc226894cddeb6239db9))
* **MySQL:** spatial fields support ([#165](https://github.com/Fabio286/antares/issues/165)) ([48ebf23](https://github.com/Fabio286/antares/commit/48ebf23bd1574408f429f2e1200ce878352007f6))
### Bug Fixes
* cell copy returns "undefined" in some conditions, closes [#170](https://github.com/Fabio286/antares/issues/170) ([8fb1f08](https://github.com/Fabio286/antares/commit/8fb1f0803efd9df0b66521e73bb6e1a229cf9691))
* indexes and foreign keys not cleared after deletion of related field, closes [#182](https://github.com/Fabio286/antares/issues/182) ([9f033fb](https://github.com/Fabio286/antares/commit/9f033fb994916b4fb165e81e55e86127ca817791))
* **PostgreSQL:** schema different than public not automatically selected, closes [#172](https://github.com/Fabio286/antares/issues/172) ([46b45c8](https://github.com/Fabio286/antares/commit/46b45c8ab64fb6837a532c4f8342167e4fd794bb))
* scale on numeric fields that doesn't support it ([0cfd793](https://github.com/Fabio286/antares/commit/0cfd7938ee7d607dbad66ae452d0200223a6bab2))
* **Windows:** temporary fix to Windows 7 style frame on app startup, closes [#169](https://github.com/Fabio286/antares/issues/169) ([1356011](https://github.com/Fabio286/antares/commit/1356011ba3b7dd72e12cb252a8787ce48a364fd4))
### Improvements
* support of scale in field's length setting ([eef7c1d](https://github.com/Fabio286/antares/commit/eef7c1dcecc6593ab0e69ed678187a57fe0a4fb6))
### [0.4.2](https://github.com/Fabio286/antares/compare/v0.4.1...v0.4.2) (2022-01-10)
### Features
* **MySQL:** ability to cancel queries ([a59f77f](https://github.com/Fabio286/antares/commit/a59f77f618aea6156fc80fb832d3efcb9848411f))
* **PostgreSQL:** ability to cancel queries ([0c00291](https://github.com/Fabio286/antares/commit/0c002918eb0226f6b3f21ed62117495f86396fb1))
* save window state ([8f9385d](https://github.com/Fabio286/antares/commit/8f9385d50815635d091758ecd5d00884e3297ca0))
* **UI:** textarea autofocus selecting a query tab, closes [#166](https://github.com/Fabio286/antares/issues/166) ([b4545b1](https://github.com/Fabio286/antares/commit/b4545b178f795712c781a3f4fc35eec31b5ad902))
### Bug Fixes
* **SQLite:** exception with some fields ([e7a1858](https://github.com/Fabio286/antares/commit/e7a18580915e7739bfa97948c6a0c4fc90a7e78a))
### Improvements
* hash for foreign key default names ([48c3e6a](https://github.com/Fabio286/antares/commit/48c3e6afc43c51f70a16703f1a71194f43da7a3e))
* **MySQL:** support to ANSI_QUOTES sql_mode, closes [#158](https://github.com/Fabio286/antares/issues/158) ([d9a3eab](https://github.com/Fabio286/antares/commit/d9a3eab015302e9f23112f659658073ab3242191))
### [0.4.1](https://github.com/Fabio286/antares/compare/v0.4.0...v0.4.1) (2021-12-11)
### Features
* language format detection for text fields ([a5fdcc1](https://github.com/Fabio286/antares/commit/a5fdcc1a85aa188ff1b9a15b1a768aced026f360))
### Bug Fixes
* cell disappear on edit in one column tables ([aaa5549](https://github.com/Fabio286/antares/commit/aaa5549609664665bd4513632d621cb249b379c1))
* false positive with Windows Defender ([992a033](https://github.com/Fabio286/antares/commit/992a033cb2bede3d1eb52e19482d810f6692de1e))
* **MySQL:** wrong datetime fields default in table filler in some cases ([8da0224](https://github.com/Fabio286/antares/commit/8da022487650039b7f34a9c86a7bd9045eba65e2))
* **MySQL:** wrong value for fields "on update" in some conditions ([359e14a](https://github.com/Fabio286/antares/commit/359e14a9ebd48f86069ba7762fe00a7056f52d47))
* select all rows with ctrl+a when editing a cell ([35cb7e1](https://github.com/Fabio286/antares/commit/35cb7e1dc48d3a74e9d106cb1a37f454c1b4a4d1))
* **SQLite:** update rows with a text primary key ([d7f1aa9](https://github.com/Fabio286/antares/commit/d7f1aa97af32a4c51fc7022498bd47e15fa08430))
### Improvements
* **UI:** avoid columns size change when editing cells or scrolling results ([813aa32](https://github.com/Fabio286/antares/commit/813aa320d9ab799efea38a7110b7c0bdf7549123))
* **UI:** disable save button in table creation when no fields are added ([e8af2d2](https://github.com/Fabio286/antares/commit/e8af2d24a869f7667c069936648808952d2062ab))
## [0.4.0](https://github.com/Fabio286/antares/compare/v0.3.9...v0.4.0) (2021-11-24)
### [0.3.10](https://github.com/Fabio286/antares/compare/v0.3.9...v0.3.10) (2021-11-24)
### Features

View File

@@ -31,9 +31,10 @@ We are actively working on it, hoping to provide new cool features, improvements
- Query suggestions and auto complete.
- Query history: search through the last 1000 queries.
- SSH tunnel support.
- Manual commit mode.
- Dark and light theme.
- Editor themes.
- Scratchpad.
- Secure password storage.
## Philosophy
@@ -129,11 +130,6 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
<td align="center"><a href="https://github.com/IsamuSugi"><img src="https://avatars.githubusercontent.com/u/7746658?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Isamu Sugiura</b></sub></a><br /><a href="#translation-IsamuSugi" title="Translation">🌍</a></td>
<td align="center"><a href="http://rsacchetto.nexxontech.it/"><img src="https://avatars.githubusercontent.com/u/18429412?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Riccardo Sacchetto</b></sub></a><br /><a href="#platform-Occhioverde" title="Packaging/porting to new platform">📦</a></td>
<td align="center"><a href="https://kilianstallinger.com"><img src="https://avatars.githubusercontent.com/u/5290318?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Kilian Stallinger</b></sub></a><br /><a href="https://github.com/Fabio286/antares/commits?author=kilianstallz" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/wenj91"><img src="https://avatars.githubusercontent.com/u/12549338?v=4?s=100" width="100px;" alt=""/><br /><sub><b>文杰</b></sub></a><br /><a href="https://github.com/Fabio286/antares/commits?author=wenj91" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/goYou"><img src="https://avatars.githubusercontent.com/u/62732795?v=4?s=100" width="100px;" alt=""/><br /><sub><b>goYou</b></sub></a><br /><a href="#translation-goYou" title="Translation">🌍</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/raliqala"><img src="https://avatars.githubusercontent.com/u/30502407?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Topollo</b></sub></a><br /><a href="https://github.com/Fabio286/antares/commits?author=raliqala" title="Code">💻</a></td>
</tr>
</table>

BIN
assets/appx/LargeTile.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

BIN
assets/appx/SmallTile.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.3 KiB

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.3 KiB

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.1 KiB

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.4 KiB

After

Width:  |  Height:  |  Size: 17 KiB

View File

@@ -1,25 +1,24 @@
{
"name": "antares",
"productName": "Antares",
"version": "0.5.0",
"version": "0.3.10",
"description": "A modern, fast and productivity driven SQL client with a focus in UX.",
"license": "MIT",
"repository": "https://github.com/Fabio286/antares.git",
"scripts": {
"debug": "npm run rebuild:electron && npm run debug-runner",
"debug-runner": "node scripts/devRunner.js --remote-debug",
"compile": "npm run compile:main && npm run compile:workers && npm run compile:renderer",
"compile": "npm run compile:main && npm run compile:renderer",
"compile:main": "webpack --mode=production --config webpack.main.config.js",
"compile:workers": "webpack --mode=production --config webpack.workers.config.js",
"compile:renderer": "webpack --mode=production --config webpack.renderer.config.js",
"build": "cross-env NODE_ENV=production npm run compile",
"build:local": "npm run build && electron-builder",
"build:appx": "npm run build:local -- --win appx",
"rebuild:electron": "rimraf ./dist && npm run postinstall",
"rebuild:electron": "npm run postinstall",
"release": "standard-version",
"release:pre": "npm run release -- --prerelease alpha",
"postinstall": "electron-builder install-app-deps",
"test": "npm run compile && node tests/app.spec.js",
"test": "npm run lint",
"lint": "eslint . --ext .js,.vue && stylelint \"./src/**/*.{css,scss,sass,vue}\"",
"lint:fix": "eslint . --ext .js,.vue --fix && stylelint \"./src/**/*.{css,scss,sass,vue}\" --fix",
"contributors:add": "all-contributors add",
@@ -52,8 +51,7 @@
"target": {
"target": "default",
"arch": [
"x64",
"arm64"
"x64"
]
}
},
@@ -84,7 +82,6 @@
"appx": {
"displayName": "Antares SQL",
"backgroundColor": "transparent",
"showNameOnTiles": true,
"identityName": "62514FabioDiStasio.AntaresSQLClient",
"publisher": "CN=1A2729ED-865C-41D2-9038-39AE2A63AA52",
"applicationId": "FabioDiStasio.AntaresSQLClient"
@@ -107,16 +104,12 @@
"dependencies": {
"@electron/remote": "^2.0.1",
"@mdi/font": "^6.1.95",
"@turf/helpers": "^6.5.0",
"@vscode/vscode-languagedetection": "^1.0.21",
"ace-builds": "^1.4.13",
"better-sqlite3": "^7.5.0",
"better-sqlite3": "^7.4.4",
"electron-log": "^4.4.1",
"electron-store": "^8.0.1",
"electron-updater": "^4.6.1",
"electron-window-state": "^5.0.3",
"electron-updater": "^4.3.9",
"faker": "^5.5.3",
"leaflet": "^1.7.1",
"marked": "^4.0.0",
"moment": "^2.29.1",
"mysql2": "^2.3.2",
@@ -137,24 +130,23 @@
"all-contributors-cli": "^6.20.0",
"babel-loader": "^8.2.3",
"chalk": "^4.1.2",
"clean-webpack-plugin": "^4.0.0",
"cross-env": "^7.0.2",
"css-loader": "^6.5.0",
"electron": "^17.0.1",
"electron-builder": "^22.14.11",
"electron": "^16.0.1",
"electron-builder": "^22.13.1",
"electron-devtools-installer": "^3.2.0",
"eslint": "^7.32.0",
"eslint-config-standard": "^16.0.3",
"eslint-plugin-import": "^2.24.2",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^5.2.0",
"eslint-plugin-promise": "^5.1.0",
"eslint-plugin-vue": "^8.0.3",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.5.0",
"mini-css-extract-plugin": "~2.4.5",
"mini-css-extract-plugin": "^2.4.3",
"node-loader": "^2.0.0",
"playwright": "^1.18.1",
"progress-webpack-plugin": "^1.0.12",
"rimraf": "^3.0.2",
"sass": "^1.42.1",
"sass-loader": "^12.3.0",
"standard-version": "^9.3.1",

View File

@@ -12,7 +12,7 @@ const { spawn } = require('child_process');
const mainConfig = require('../webpack.main.config');
const rendererConfig = require('../webpack.renderer.config');
const workersConfig = require('../webpack.workers.config');
// const workersConfig = require('../webpack.workers.config');
let electronProcess = null;
let manualRestart = null;
@@ -64,7 +64,7 @@ async function restartElectron () {
}
function startMain () {
const webpackSetup = webpack([mainConfig, workersConfig]);
const webpackSetup = webpack(mainConfig);
webpackSetup.compilers.forEach((compiler) => {
const { name } = compiler;

View File

@@ -134,7 +134,7 @@ export default class {
{ name: 'phoneNumberFormat', group: 'phone', types: ['string'] },
{ name: 'phoneFormats', group: 'phone', types: ['string'] },
{ name: 'number', group: 'datatype', types: ['string', 'number'], params: ['min', 'max'] },
{ name: 'number', group: 'random', types: ['string', 'number'], params: ['min', 'max'] },
{ name: 'float', group: 'random', types: ['string', 'float'], params: ['min', 'max'] },
{ name: 'arrayElement', group: 'random', types: ['string'] },
{ name: 'arrayElements', group: 'random', types: ['string'] },

View File

@@ -11,7 +11,6 @@ module.exports = {
sslConnection: false,
sshConnection: false,
fileConnection: false,
cancelQueries: false,
// Tools
processesList: false,
usersManagement: false,
@@ -38,8 +37,6 @@ module.exports = {
databaseEdit: false,
schemaEdit: false,
schemaDrop: false,
schemaExport: false,
schemaImport: false,
tableSettings: false,
tableOptions: false,
tableArray: false,

View File

@@ -12,7 +12,6 @@ module.exports = {
engines: true,
sslConnection: true,
sshConnection: true,
cancelQueries: true,
// Tools
processesList: true,
// Structure
@@ -34,8 +33,6 @@ module.exports = {
schedulerAdd: true,
schemaEdit: true,
schemaDrop: true,
schemaExport: true,
schemaImport: true,
tableSettings: true,
viewSettings: true,
triggerSettings: true,

View File

@@ -10,7 +10,6 @@ module.exports = {
database: true,
sslConnection: true,
sshConnection: true,
cancelQueries: true,
// Tools
processesList: true,
// Structure
@@ -32,8 +31,6 @@ module.exports = {
functionAdd: true,
schemaDrop: true,
databaseEdit: false,
schemaExport: false,
schemaImport: false,
tableSettings: true,
viewSettings: true,
triggerSettings: true,

View File

@@ -7,8 +7,8 @@ module.exports = {
views: true,
triggers: true,
// Settings
elementsWrapper: '"',
stringsWrapper: '\'',
elementsWrapper: '',
stringsWrapper: '"',
tableAdd: true,
viewAdd: true,
triggerAdd: true,

View File

@@ -66,7 +66,6 @@ module.exports = [
{
name: 'DECIMAL',
length: true,
scale: true,
collation: false,
unsigned: false,
zerofill: false
@@ -121,7 +120,7 @@ module.exports = [
{
name: 'JSON',
length: false,
collation: false,
collation: true,
unsigned: false,
zerofill: false
}
@@ -219,56 +218,56 @@ module.exports = [
types: [
{
name: 'POINT',
length: false,
length: true,
collation: false,
unsigned: false,
zerofill: false
},
{
name: 'LINESTRING',
length: false,
length: true,
collation: false,
unsigned: false,
zerofill: false
},
{
name: 'POLYGON',
length: false,
length: true,
collation: false,
unsigned: false,
zerofill: false
},
{
name: 'GEOMETRY',
length: false,
length: true,
collation: false,
unsigned: false,
zerofill: false
},
{
name: 'MULTIPOINT',
length: false,
length: true,
collation: false,
unsigned: false,
zerofill: false
},
{
name: 'MULTILINESTRING',
length: false,
length: true,
collation: false,
unsigned: false,
zerofill: false
},
{
name: 'MULTIPOLYGON',
length: false,
length: true,
collation: false,
unsigned: false,
zerofill: false
},
{
name: 'GEOMCOLLECTION',
length: false,
name: 'GEOMETRYCOLLECTION',
length: true,
collation: false,
unsigned: false,
zerofill: false

View File

@@ -22,6 +22,11 @@ module.exports = [
length: false,
unsigned: true
},
{
name: 'NUMERIC',
length: true,
unsigned: true
},
{
name: 'SMALLSERIAL',
length: false,
@@ -47,12 +52,6 @@ module.exports = [
length: false,
unsigned: true
},
{
name: 'NUMERIC',
length: true,
unsigned: true,
scale: true
},
{
name: 'DOUBLE PRECISION',
length: false,

View File

@@ -8,9 +8,7 @@ export const TEXT = [
export const LONG_TEXT = [
'TEXT',
'MEDIUMTEXT',
'LONGTEXT',
'JSON',
'VARBINARY'
'LONGTEXT'
];
export const ARRAY = [
@@ -41,7 +39,6 @@ export const NUMBER = [
export const FLOAT = [
'FLOAT',
'DECIMAL',
'DOUBLE',
'REAL',
'DOUBLE PRECISION',
@@ -85,24 +82,3 @@ export const BIT = [
'BIT',
'BIT VARYING'
];
export const SPATIAL = [
'POINT',
'LINESTRING',
'POLYGON',
'GEOMETRY',
'MULTIPOINT',
'MULTILINESTRING',
'MULTIPOLYGON',
'GEOMCOLLECTION',
'GEOMETRYCOLLECTION'
];
// Used to check multi spatial fields only
export const IS_MULTI_SPATIAL = [
'MULTIPOINT',
'MULTILINESTRING',
'MULTIPOLYGON',
'GEOMCOLLECTION',
'GEOMETRYCOLLECTION'
];

View File

@@ -1,10 +0,0 @@
/**
*
* @param {any[]} array
* @returns {number}
*/
export function getArrayDepth (array) {
return Array.isArray(array)
? 1 + Math.max(0, ...array.map(getArrayDepth))
: 0;
}

View File

@@ -33,7 +33,7 @@ const lookup = {
*/
export default function hexToBinary (hex) {
let binary = '';
for (let i = 0; i < hex.length; i++)
for (let i = 0, len = hex.length; i < len; i++)
binary += lookup[hex[i]];
return binary;

View File

@@ -23,7 +23,7 @@ export function mimeFromHex (hex) {
case '425A68':
return { ext: 'bz2', mime: 'application/x-bzip2' };
default:
switch (hex) { // 4 bytes
switch (hex) { // 4 bites
case '89504E47':
return { ext: 'png', mime: 'image/png' };
case '47494638':

View File

@@ -1,93 +0,0 @@
import { Transform } from 'stream';
export default class SqlParser extends Transform {
constructor (opts) {
opts = {
delimiter: ';',
encoding: 'utf8',
writableObjectMode: true,
readableObjectMode: true,
...opts
};
super(opts);
this._buffer = '';
this._lastChar = '';
this._last9Chars = '';
this.encoding = opts.encoding;
this.delimiter = opts.delimiter;
this.isEscape = false;
this.currentQuote = null;
this.isDelimiter = false;
}
_transform (chunk, encoding, next) {
for (const char of chunk.toString(this.encoding)) {
this.checkEscape();
this._buffer += char;
this._lastChar = char;
this._last9Chars += char.trim().toLocaleLowerCase();
if (this._last9Chars.length > 9)
this._last9Chars = this._last9Chars.slice(-9);
this.checkNewDelimiter(char);
this.checkQuote(char);
const query = this.getQuery();
if (query)
this.push(query);
}
next();
}
checkEscape () {
if (this._buffer.length > 0) {
this.isEscape = this._lastChar === '\\'
? !this.isEscape
: false;
}
}
checkNewDelimiter (char) {
if (this.currentQuote === null && this._last9Chars === 'delimiter') {
this.isDelimiter = true;
this._buffer = '';
}
else {
const isNewLine = char === '\n' || char === '\r';
if (isNewLine && this.isDelimiter) {
this.isDelimiter = false;
this.delimiter = this._buffer.trim();
this._buffer = '';
}
}
}
checkQuote (char) {
const isQuote = !this.isEscape && (char === '\'' || char === '"');
if (isQuote && this.currentQuote === char)
this.currentQuote = null;
else if (isQuote && this.currentQuote === null)
this.currentQuote = char;
}
getQuery () {
if (this.isDelimiter)
return false;
let query = false;
let demiliterFound = false;
if (this.currentQuote === null && this._buffer.length >= this.delimiter.length)
demiliterFound = this._last9Chars.slice(-this.delimiter.length) === this.delimiter;
if (demiliterFound) {
const parsedStr = this._buffer.trim();
query = parsedStr.slice(0, parsedStr.length - this.delimiter.length);
this._buffer = '';
}
return query;
}
}

View File

@@ -1,4 +1,4 @@
import { app, ipcMain, dialog } from 'electron';
import { app, ipcMain } from 'electron';
export default () => {
ipcMain.on('close-app', () => {
@@ -9,12 +9,4 @@ export default () => {
const key = false;
event.returnValue = key;
});
ipcMain.handle('showOpenDialog', (event, options) => {
return dialog.showOpenDialog(options);
});
ipcMain.handle('get-download-dir-path', () => {
return app.getPath('downloads');
});
};

View File

@@ -40,7 +40,7 @@ export default connections => {
}
try {
const connection = await ClientsFactory.getClient({
const connection = await ClientsFactory.getConnection({
client: conn.client,
params
});
@@ -52,7 +52,7 @@ export default connections => {
return { status: 'success' };
}
catch (err) {
return { status: 'error', response: err.toString() };
return { status: 'error', response: err };
}
});
@@ -100,7 +100,7 @@ export default connections => {
}
try {
const connection = ClientsFactory.getClient({
const connection = ClientsFactory.getConnection({
client: conn.client,
params,
poolSize: 5

View File

@@ -1,15 +1,7 @@
import fs from 'fs';
import path from 'path';
import { fork } from 'child_process';
import { ipcMain, dialog } from 'electron';
// @TODO: need some factories
const isDevelopment = process.env.NODE_ENV !== 'production';
import { ipcMain } from 'electron';
export default connections => {
let exporter = null;
let importer = null;
ipcMain.handle('create-schema', async (event, params) => {
try {
await connections[params.uid].createSchema(params);
@@ -45,16 +37,9 @@ export default connections => {
ipcMain.handle('get-schema-collation', async (event, params) => {
try {
const collation = await connections[params.uid].getDatabaseCollation(
params
);
const collation = await connections[params.uid].getDatabaseCollation(params);
return {
status: 'success',
response: collation.rows.length
? collation.rows[0].DEFAULT_COLLATION_NAME
: ''
};
return { status: 'success', response: collation.rows.length ? collation.rows[0].DEFAULT_COLLATION_NAME : '' };
}
catch (err) {
return { status: 'error', response: err.toString() };
@@ -63,9 +48,7 @@ export default connections => {
ipcMain.handle('get-structure', async (event, params) => {
try {
const structure = await connections[params.uid].getStructure(
params.schemas
);
const structure = await connections[params.uid].getStructure(params.schemas);
return { status: 'success', response: structure };
}
@@ -152,7 +135,7 @@ export default connections => {
}
});
ipcMain.handle('raw-query', async (event, { uid, query, schema, tabUid, autocommit }) => {
ipcMain.handle('raw-query', async (event, { uid, query, schema }) => {
if (!query) return;
try {
@@ -160,8 +143,6 @@ export default connections => {
nest: true,
details: true,
schema,
tabUid,
autocommit,
comments: false
});
@@ -171,215 +152,4 @@ export default connections => {
return { status: 'error', response: err.toString() };
}
});
ipcMain.handle('export', (event, { uid, type, tables, ...rest }) => {
if (exporter !== null) return;
return new Promise((resolve, reject) => {
(async () => {
if (fs.existsSync(rest.outputFile)) { // If file exists ask for replace
const result = await dialog.showMessageBox({
type: 'warning',
message: `File ${rest.outputFile} already exists. Do you want to replace it?`,
detail: 'A file with the same name already exists in the target folder. Replacing it will overwrite its current contents.',
buttons: ['Cancel', 'Replace'],
defaultId: 0,
cancelId: 0
});
if (result.response !== 1) {
resolve({
type: 'error',
response: 'Operation aborted'
});
return;
}
}
// Init exporter process
exporter = fork(isDevelopment ? './dist/exporter.js' : path.resolve(__dirname, './exporter.js'), [], {
execArgv: isDevelopment ? ['--inspect=9224'] : undefined
});
exporter.send({
type: 'init',
client: {
name: type,
config: await connections[uid].getDbConfig()
},
tables,
options: rest
});
// Exporter message listener
exporter.on('message', ({ type, payload }) => {
switch (type) {
case 'export-progress':
event.sender.send('export-progress', payload);
break;
case 'end':
setTimeout(() => { // Ensures that writing process has finished
exporter.kill();
exporter = null;
}, 2000);
resolve({ status: 'success', response: payload });
break;
case 'cancel':
exporter.kill();
exporter = null;
resolve({ status: 'error', response: 'Operation cancelled' });
break;
case 'error':
exporter.kill();
exporter = null;
resolve({ status: 'error', response: payload });
break;
}
});
exporter.on('exit', code => {
exporter = null;
resolve({ status: 'error', response: `Operation ended with code: ${code}` });
});
})();
});
});
ipcMain.handle('abort-export', async event => {
let willAbort = false;
if (exporter) {
const result = await dialog.showMessageBox({
type: 'warning',
message: 'Are you sure you want to abort the export',
buttons: ['Cancel', 'Abort'],
defaultId: 0,
cancelId: 0
});
if (result.response === 1) {
willAbort = true;
exporter.send({ type: 'cancel' });
}
}
return { status: 'success', response: { willAbort } };
});
ipcMain.handle('import-sql', async (event, options) => {
if (importer !== null) return;
return new Promise((resolve, reject) => {
(async () => {
const dbConfig = await connections[options.uid].getDbConfig();
// Init importer process
importer = fork(isDevelopment ? './dist/importer.js' : path.resolve(__dirname, './importer.js'), [], {
execArgv: isDevelopment ? ['--inspect=9224'] : undefined
});
importer.send({
type: 'init',
dbConfig,
options
});
// Importer message listener
importer.on('message', ({ type, payload }) => {
switch (type) {
case 'import-progress':
event.sender.send('import-progress', payload);
break;
case 'query-error':
event.sender.send('query-error', payload);
break;
case 'end':
setTimeout(() => { // Ensures that writing process has finished
importer?.kill();
importer = null;
}, 2000);
resolve({ status: 'success', response: payload });
break;
case 'cancel':
importer.kill();
importer = null;
resolve({ status: 'error', response: 'Operation cancelled' });
break;
case 'error':
importer.kill();
importer = null;
resolve({ status: 'error', response: payload });
break;
}
});
})();
});
});
ipcMain.handle('abort-import-sql', async event => {
let willAbort = false;
if (importer) {
const result = await dialog.showMessageBox({
type: 'warning',
message: 'Are you sure you want to abort the import',
buttons: ['Cancel', 'Abort'],
defaultId: 0,
cancelId: 0
});
if (result.response === 1) {
willAbort = true;
importer.send({ type: 'cancel' });
}
}
return { status: 'success', response: { willAbort } };
});
ipcMain.handle('kill-tab-query', async (event, { uid, tabUid }) => {
if (!tabUid) return;
try {
await connections[uid].killTabQuery(tabUid);
return { status: 'success' };
}
catch (err) {
return { status: 'error', response: err.toString() };
}
});
ipcMain.handle('commit-tab', async (event, { uid, tabUid }) => {
if (!tabUid) return;
try {
await connections[uid].commitTab(tabUid);
return { status: 'success' };
}
catch (err) {
return { status: 'error', response: err.toString() };
}
});
ipcMain.handle('rollback-tab', async (event, { uid, tabUid }) => {
if (!tabUid) return;
try {
await connections[uid].rollbackTab(tabUid);
return { status: 'success' };
}
catch (err) {
return { status: 'error', response: err.toString() };
}
});
ipcMain.handle('destroy-connection-to-commit', async (event, { uid, tabUid }) => {
if (!tabUid) return;
try {
await connections[uid].destroyConnectionToCommit(tabUid);
return { status: 'success' };
}
catch (err) {
return { status: 'error', response: err.toString() };
}
});
};

View File

@@ -3,7 +3,6 @@ import faker from 'faker';
import moment from 'moment';
import { sqlEscaper } from 'common/libs/sqlEscaper';
import { TEXT, LONG_TEXT, ARRAY, TEXT_SEARCH, NUMBER, FLOAT, BLOB, BIT, DATE, DATETIME } from 'common/fieldTypes';
import * as customizations from 'common/customizations';
import fs from 'fs';
export default (connections) => {
@@ -86,12 +85,11 @@ export default (connections) => {
ipcMain.handle('update-table-cell', async (event, params) => {
delete params.row._antares_id;
const { stringsWrapper: sw } = customizations[connections[params.uid]._client];
try { // TODO: move to client classes
let escapedParam;
let reload = false;
const id = typeof params.id === 'number' ? params.id : `${sw}${params.id}${sw}`;
const id = typeof params.id === 'number' ? params.id : `"${params.id}"`;
if ([...NUMBER, ...FLOAT].includes(params.type))
escapedParam = params.content;
@@ -149,7 +147,7 @@ export default (connections) => {
}
}
}
else if (BIT.includes(params.type)) {
else if ([...BIT].includes(params.type)) {
escapedParam = `b'${sqlEscaper(params.content)}'`;
reload = true;
}

View File

@@ -1,10 +1,4 @@
'use strict';
const queryLogger = sql => {
// Remove comments, newlines and multiple spaces
const escapedSql = sql.replace(/(\/\*(.|[\r\n])*?\*\/)|(--(.*|[\r\n]))/gm, '').replace(/\s\s+/g, ' ');
console.log(escapedSql);
};
/**
* As Simple As Possible Query Builder Core
*
@@ -23,7 +17,7 @@ export class AntaresCore {
this._poolSize = args.poolSize || false;
this._connection = null;
this._ssh = null;
this._logger = args.logger || queryLogger;
this._logger = args.logger || console.log;
this._queryDefaults = {
schema: '',

View File

@@ -2,6 +2,13 @@
import { MySQLClient } from './clients/MySQLClient';
import { PostgreSQLClient } from './clients/PostgreSQLClient';
import { SQLiteClient } from './clients/SQLiteClient';
const queryLogger = sql => {
// Remove comments, newlines and multiple spaces
const escapedSql = sql.replace(/(\/\*(.|[\r\n])*?\*\/)|(--(.*|[\r\n]))/gm, '').replace(/\s\s+/g, ' ');
console.log(escapedSql);
};
export class ClientsFactory {
/**
* Returns a database connection based on received args.
@@ -22,7 +29,9 @@ export class ClientsFactory {
* @returns Database Connection
* @memberof ClientsFactory
*/
static getClient (args) {
static getConnection (args) {
args.logger = queryLogger;
switch (args.client) {
case 'mysql':
case 'maria':

View File

@@ -9,8 +9,6 @@ export class MySQLClient extends AntaresCore {
super(args);
this._schema = null;
this._runningConnections = new Map();
this._connectionsToCommit = new Map();
this.types = {
0: 'DECIMAL',
@@ -101,32 +99,10 @@ export class MySQLClient extends AntaresCore {
.filter(_type => _type.name === type.toUpperCase())[0];
}
_reducer (acc, curr) {
const type = typeof curr;
switch (type) {
case 'number':
case 'string':
return [...acc, curr];
case 'object':
if (Array.isArray(curr))
return [...acc, ...curr];
else {
const clausoles = [];
for (const key in curr)
clausoles.push(`\`${key}\` ${curr[key]}`);
return clausoles;
}
}
}
/**
*
* @returns dbConfig
* @memberof MySQLClient
*/
async getDbConfig () {
async connect () {
delete this._params.application_name;
const dbConfig = {
@@ -134,9 +110,7 @@ export class MySQLClient extends AntaresCore {
port: this._params.port,
user: this._params.user,
password: this._params.password,
ssl: null,
supportBigNumbers: true,
bigNumberStrings: true
ssl: null
};
if (this._params.schema?.length) dbConfig.database = this._params.schema;
@@ -159,17 +133,30 @@ export class MySQLClient extends AntaresCore {
}
}
return dbConfig;
}
if (!this._poolSize) {
this._connection = await mysql.createConnection(dbConfig);
/**
* @memberof MySQLClient
*/
async connect () {
if (!this._poolSize)
this._connection = await this.getConnection();
else
this._connection = await this.getConnectionPool();
if (this._params.readonly)
await this.raw('SET SESSION TRANSACTION READ ONLY');
}
else {
this._connection = mysql.createPool({
...dbConfig,
connectionLimit: this._poolSize,
typeCast: (field, next) => {
if (field.type === 'DATETIME')
return field.string();
else
return next();
}
});
if (this._params.readonly) {
this._connection.on('connection', connection => {
connection.query('SET SESSION TRANSACTION READ ONLY');
});
}
}
}
/**
@@ -180,64 +167,6 @@ export class MySQLClient extends AntaresCore {
if (this._ssh) this._ssh.close();
}
async getConnection () {
const dbConfig = await this.getDbConfig();
const connection = await mysql.createConnection({
...dbConfig,
typeCast: (field, next) => {
if (field.type === 'DATETIME')
return field.string();
else
return next();
}
});
// ANSI_QUOTES check
const [res] = await connection.query('SHOW GLOBAL VARIABLES LIKE \'%sql_mode%\'');
const sqlMode = res[0]?.Variable_name?.split(',');
const hasAnsiQuotes = sqlMode.includes('ANSI_QUOTES');
if (this._params.readonly)
await connection.query('SET SESSION TRANSACTION READ ONLY');
if (hasAnsiQuotes)
await connection.query(`SET SESSION sql_mode = "${sqlMode.filter(m => m !== 'ANSI_QUOTES').join(',')}"`);
return connection;
}
async getConnectionPool () {
const dbConfig = await this.getDbConfig();
const connection = mysql.createPool({
...dbConfig,
connectionLimit: this._poolSize,
typeCast: (field, next) => {
if (field.type === 'DATETIME')
return field.string();
else
return next();
}
});
// ANSI_QUOTES check
const [res] = await connection.query('SHOW GLOBAL VARIABLES LIKE \'%sql_mode%\'');
const sqlMode = res[0]?.Variable_name?.split(',');
const hasAnsiQuotes = sqlMode.includes('ANSI_QUOTES');
if (hasAnsiQuotes)
await connection.query(`SET SESSION sql_mode = "${sqlMode.filter(m => m !== 'ANSI_QUOTES').join(',')}"`);
connection.on('connection', conn => {
if (this._params.readonly)
conn.query('SET SESSION TRANSACTION READ ONLY');
if (hasAnsiQuotes)
conn.query(`SET SESSION sql_mode = "${sqlMode.filter(m => m !== 'ANSI_QUOTES').join(',')}"`);
});
return connection;
}
/**
* Executes an USE query
*
@@ -306,7 +235,7 @@ export class MySQLClient extends AntaresCore {
break;
}
const tableSize = Number(table.Data_length) + Number(table.Index_length);
const tableSize = table.Data_length + table.Index_length;
schemaSize += tableSize;
return {
@@ -447,7 +376,7 @@ export class MySQLClient extends AntaresCore {
return acc;
}, '')
.replaceAll('\n', '')
.split(/,\s?(?![^(]*\))/)
.split(',')
.map(f => {
try {
const fieldArr = f.trim().split(' ');
@@ -487,25 +416,18 @@ export class MySQLClient extends AntaresCore {
return rows.map(field => {
let numLength = field.COLUMN_TYPE.match(/int\(([^)]+)\)/);
numLength = numLength ? +numLength.pop() : field.NUMERIC_PRECISION || null;
numLength = numLength ? +numLength.pop() : null;
const enumValues = /(enum|set)/.test(field.COLUMN_TYPE)
? field.COLUMN_TYPE.match(/\(([^)]+)\)/)[0].slice(1, -1)
: null;
const defaultValue = (remappedFields && remappedFields[field.COLUMN_NAME])
? remappedFields[field.COLUMN_NAME].default
: field.COLUMN_DEFAULT;
return {
name: field.COLUMN_NAME,
key: field.COLUMN_KEY.toLowerCase(),
type: (remappedFields && remappedFields[field.COLUMN_NAME])
? remappedFields[field.COLUMN_NAME].type
: field.DATA_TYPE.toUpperCase(),
type: remappedFields ? remappedFields[field.COLUMN_NAME].type : field.DATA_TYPE,
schema: field.TABLE_SCHEMA,
table: field.TABLE_NAME,
numPrecision: field.NUMERIC_PRECISION,
numScale: field.NUMERIC_SCALE,
numLength,
enumValues,
datePrecision: field.DATETIME_PRECISION,
@@ -514,14 +436,11 @@ export class MySQLClient extends AntaresCore {
unsigned: field.COLUMN_TYPE.includes('unsigned'),
zerofill: field.COLUMN_TYPE.includes('zerofill'),
order: field.ORDINAL_POSITION,
default: defaultValue,
default: remappedFields ? remappedFields[field.COLUMN_NAME].default : field.COLUMN_DEFAULT,
charset: field.CHARACTER_SET_NAME,
collation: field.COLLATION_NAME,
autoIncrement: field.EXTRA.includes('auto_increment'),
generated: field.EXTRA.toLowerCase().includes('generated'),
onUpdate: field.EXTRA.toLowerCase().includes('on update')
? field.EXTRA.substr(field.EXTRA.indexOf('on update') + 9, field.EXTRA.length).trim()
: '',
onUpdate: field.EXTRA.toLowerCase().includes('on update') ? field.EXTRA.replace('on update', '') : '',
comment: field.COLUMN_COMMENT
};
});
@@ -1218,26 +1137,6 @@ export class MySQLClient extends AntaresCore {
});
}
/**
* SHOW VARIABLES LIKE %variable%
*
* @param {String} variable
* @param {'global'|'session'|null} level
* @returns {Object} variable
* @memberof MySQLClient
*/
async getVariable (variable, level) {
const sql = `SHOW${level ? ' ' + level.toUpperCase() : ''} VARIABLES LIKE '%${variable}%'`;
const results = await this.raw(sql);
if (results.rows.length) {
return {
name: results.rows[0].Variable_name,
value: results.rows[0].Value
};
}
}
/**
* SHOW ENGINES
*
@@ -1309,56 +1208,10 @@ export class MySQLClient extends AntaresCore {
});
}
/**
*
* @param {number} id
* @returns {Promise<null>}
*/
async killProcess (id) {
return await this.raw(`KILL ${id}`);
}
/**
*
* @param {string} tabUid
* @returns {Promise<null>}
*/
async killTabQuery (tabUid) {
const id = this._runningConnections.get(tabUid);
if (id)
return await this.killProcess(id);
}
/**
*
* @param {string} tabUid
* @returns {Promise<null>}
*/
async commitTab (tabUid) {
const connection = this._connectionsToCommit.get(tabUid);
if (connection)
return await connection.query('COMMIT');
}
/**
*
* @param {string} tabUid
* @returns {Promise<null>}
*/
async rollbackTab (tabUid) {
const connection = this._connectionsToCommit.get(tabUid);
if (connection)
return await connection.query('ROLLBACK');
}
destroyConnectionToCommit (tabUid) {
const connection = this._connectionsToCommit.get(tabUid);
if (connection) {
connection.destroy();
this._connectionsToCommit.delete(tabUid);
}
}
/**
* CREATE TABLE
*
@@ -1385,7 +1238,7 @@ export class MySQLClient extends AntaresCore {
const length = typeInfo.length ? field.enumValues || field.numLength || field.charLength || field.datePrecision : false;
newColumns.push(`\`${field.name}\`
${field.type.toUpperCase()}${length ? `(${length}${field.numScale ? `,${field.numScale}` : ''})` : ''}
${field.type.toUpperCase()}${length ? `(${length})` : ''}
${field.unsigned ? 'UNSIGNED' : ''}
${field.zerofill ? 'ZEROFILL' : ''}
${field.nullable ? 'NULL' : 'NOT NULL'}
@@ -1454,7 +1307,7 @@ export class MySQLClient extends AntaresCore {
const length = typeInfo.length ? addition.enumValues || addition.numLength || addition.charLength || addition.datePrecision : false;
alterColumns.push(`ADD COLUMN \`${addition.name}\`
${addition.type.toUpperCase()}${length ? `(${length}${addition.numScale ? `,${addition.numScale}` : ''})` : ''}
${addition.type.toUpperCase()}${length ? `(${length})` : ''}
${addition.unsigned ? 'UNSIGNED' : ''}
${addition.zerofill ? 'ZEROFILL' : ''}
${addition.nullable ? 'NULL' : 'NOT NULL'}
@@ -1492,7 +1345,7 @@ export class MySQLClient extends AntaresCore {
const length = typeInfo.length ? change.enumValues || change.numLength || change.charLength || change.datePrecision : false;
alterColumns.push(`CHANGE COLUMN \`${change.orgName}\` \`${change.name}\`
${change.type.toUpperCase()}${length ? `(${length}${change.numScale ? `,${change.numScale}` : ''})` : ''}
${change.type.toUpperCase()}${length ? `(${length})` : ''}
${change.unsigned ? 'UNSIGNED' : ''}
${change.zerofill ? 'ZEROFILL' : ''}
${change.nullable ? 'NULL' : 'NOT NULL'}
@@ -1623,7 +1476,7 @@ export class MySQLClient extends AntaresCore {
let insertRaw = '';
if (this._query.insert.length) {
const fieldsList = Object.keys(this._query.insert[0]).map(col => '`' + col + '`');
const fieldsList = Object.keys(this._query.insert[0]);
const rowsList = this._query.insert.map(el => `(${Object.values(el).join(', ')})`);
insertRaw = `(${fieldsList.join(', ')}) VALUES ${rowsList.join(', ')} `;
@@ -1663,7 +1516,6 @@ export class MySQLClient extends AntaresCore {
details: false,
split: true,
comments: true,
autocommit: true,
...args
};
@@ -1678,24 +1530,8 @@ export class MySQLClient extends AntaresCore {
.filter(Boolean)
.map(q => q.trim())
: [sql];
let connection;
const isPool = typeof this._connection.getConnection === 'function';
if (!args.autocommit && args.tabUid) { // autocommit OFF
if (this._connectionsToCommit.has(args.tabUid))
connection = this._connectionsToCommit.get(args.tabUid);
else {
connection = await this.getConnection();
await connection.query('SET SESSION autocommit=0');
this._connectionsToCommit.set(args.tabUid, connection);
}
}
else// autocommit ON
connection = isPool ? await this._connection.getConnection() : this._connection;
if (args.tabUid && isPool)
this._runningConnections.set(args.tabUid, connection.connection.connectionId);
const connection = isPool ? await this._connection.getConnection() : this._connection;
if (args.schema)
await connection.query(`USE \`${args.schema}\``);
@@ -1757,10 +1593,7 @@ export class MySQLClient extends AntaresCore {
});
}
catch (err) {
if (isPool && args.autocommit) {
connection.release();
this._runningConnections.delete(args.tabUid);
}
if (isPool) connection.release();
reject(err);
}
@@ -1769,10 +1602,7 @@ export class MySQLClient extends AntaresCore {
keysArr = keysArr ? [...keysArr, ...response] : response;
}
catch (err) {
if (isPool && args.autocommit) {
connection.release();
this._runningConnections.delete(args.tabUid);
}
if (isPool) connection.release();
reject(err);
}
}
@@ -1787,10 +1617,7 @@ export class MySQLClient extends AntaresCore {
keys: keysArr
});
}).catch((err) => {
if (isPool && args.autocommit) {
connection.release();
this._runningConnections.delete(args.tabUid);
}
if (isPool) connection.release();
reject(err);
});
});
@@ -1798,10 +1625,7 @@ export class MySQLClient extends AntaresCore {
resultsArr.push({ rows, report, fields, keys, duration });
}
if (isPool && args.autocommit) {
connection.release();
this._runningConnections.delete(args.tabUid);
}
if (isPool) connection.release();
return resultsArr.length === 1 ? resultsArr[0] : resultsArr;
}

View File

@@ -9,6 +9,7 @@ function pgToString (value) {
return value.toString();
}
types.setTypeParser(20, a => parseInt(a));// bigint string to number
types.setTypeParser(1082, pgToString); // date
types.setTypeParser(1083, pgToString); // time
types.setTypeParser(1114, pgToString); // timestamp
@@ -20,8 +21,6 @@ export class PostgreSQLClient extends AntaresCore {
super(args);
this._schema = null;
this._runningConnections = new Map();
this._connectionsToCommit = new Map();
this.types = {};
for (const key in types.builtins)
@@ -71,11 +70,9 @@ export class PostgreSQLClient extends AntaresCore {
}
/**
*
* @returns dbConfig
* @memberof PostgreSQLClient
*/
async getDbConfig () {
async connect () {
const dbConfig = {
host: this._params.host,
port: this._params.port,
@@ -104,43 +101,24 @@ export class PostgreSQLClient extends AntaresCore {
}
}
return dbConfig;
}
if (!this._poolSize) {
const client = new Client(dbConfig);
await client.connect();
this._connection = client;
/**
* @memberof PostgreSQLClient
*/
async connect () {
if (!this._poolSize)
this._connection = await this.getConnection();
else
this._connection = await this.getConnectionPool();
}
async getConnection () {
const dbConfig = await this.getDbConfig();
const client = new Client(dbConfig);
await client.connect();
const connection = client;
if (this._params.readonly)
await connection.query('SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY');
return connection;
}
async getConnectionPool () {
const dbConfig = await this.getDbConfig();
const pool = new Pool({ ...dbConfig, max: this._poolSize });
const connection = pool;
if (this._params.readonly) {
connection.on('connect', conn => {
conn.query('SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY');
});
if (this._params.readonly)
await this.raw('SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY');
}
else {
const pool = new Pool({ ...dbConfig, max: this._poolSize });
this._connection = pool;
return connection;
if (this._params.readonly) {
this._connection.on('connect', connection => {
connection.query('SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY');
});
}
}
}
/**
@@ -152,23 +130,15 @@ export class PostgreSQLClient extends AntaresCore {
}
/**
* Executes an 'SET search_path TO "${schema}"' query
* Executes an "USE" query
*
* @param {String} schema
* @param {Object?} connection optional
* @memberof PostgreSQLClient
*/
use (schema, connection) {
use (schema) {
this._schema = schema;
if (schema) {
const sql = `SET search_path TO "${schema}"`;
if (connection === undefined)
return this.raw(sql);
else
return connection.query(sql);
}
if (schema)
return this.raw(`SET search_path TO "${schema}"`);
}
/**
@@ -238,7 +208,7 @@ export class PostgreSQLClient extends AntaresCore {
if (schemas.has(db.database)) {
// TABLES
const remappedTables = tablesArr.filter(table => table.Db === db.database).map(table => {
const tableSize = Number(table.data_length) + Number(table.index_length);
const tableSize = +table.data_length + table.index_length;
schemaSize += tableSize;
return {
@@ -347,7 +317,6 @@ export class PostgreSQLClient extends AntaresCore {
isArray,
schema: field.table_schema,
table: field.table_name,
numScale: field.numeric_scale,
numPrecision: field.numeric_precision,
datePrecision: field.datetime_precision,
charLength: field.character_maximum_length,
@@ -1119,60 +1088,10 @@ export class PostgreSQLClient extends AntaresCore {
});
}
/**
*
* @param {number} id
* @returns {Promise<null>}
*/
async killProcess (id) {
return await this.raw(`SELECT pg_terminate_backend(${id})`);
}
/**
*
* @param {string} tabUid
* @returns {Promise<null>}
*/
async killTabQuery (tabUid) {
const id = this._runningConnections.get(tabUid);
if (id)
return await this.raw(`SELECT pg_cancel_backend(${id})`);
}
/**
*
* @param {string} tabUid
* @returns {Promise<null>}
*/
async commitTab (tabUid) {
const connection = this._connectionsToCommit.get(tabUid);
if (connection) {
await connection.query('COMMIT');
return this.destroyConnectionToCommit(tabUid);
}
}
/**
*
* @param {string} tabUid
* @returns {Promise<null>}
*/
async rollbackTab (tabUid) {
const connection = this._connectionsToCommit.get(tabUid);
if (connection) {
await connection.query('ROLLBACK');
return this.destroyConnectionToCommit(tabUid);
}
}
destroyConnectionToCommit (tabUid) {
const connection = this._connectionsToCommit.get(tabUid);
if (connection) {
connection.end();
this._connectionsToCommit.delete(tabUid);
}
}
/**
* CREATE TABLE
*
@@ -1200,7 +1119,7 @@ export class PostgreSQLClient extends AntaresCore {
const length = typeInfo.length ? field.enumValues || field.numLength || field.charLength || field.datePrecision : false;
newColumns.push(`"${field.name}"
${field.type.toUpperCase()}${length ? `(${length}${field.numScale !== null ? `,${field.numScale}` : ''})` : ''}
${field.type.toUpperCase()}${length ? `(${length})` : ''}
${field.unsigned ? 'UNSIGNED' : ''}
${field.zerofill ? 'ZEROFILL' : ''}
${field.nullable ? 'NULL' : 'NOT NULL'}
@@ -1264,7 +1183,7 @@ export class PostgreSQLClient extends AntaresCore {
const length = typeInfo.length ? addition.numLength || addition.charLength || addition.datePrecision : false;
alterColumns.push(`ADD COLUMN "${addition.name}"
${addition.type.toUpperCase()}${length ? `(${length}${addition.numScale !== null ? `,${addition.numScale}` : ''})` : ''}${addition.isArray ? '[]' : ''}
${addition.type.toUpperCase()}${length ? `(${length})` : ''}${addition.isArray ? '[]' : ''}
${addition.unsigned ? 'UNSIGNED' : ''}
${addition.zerofill ? 'ZEROFILL' : ''}
${addition.nullable ? 'NULL' : 'NOT NULL'}
@@ -1310,7 +1229,7 @@ export class PostgreSQLClient extends AntaresCore {
localType = change.type.toLowerCase();
}
alterColumns.push(`ALTER COLUMN "${change.name}" TYPE ${localType}${length ? `(${length}${change.numScale ? `,${change.numScale}` : ''})` : ''}${change.isArray ? '[]' : ''} USING "${change.name}"::${localType}`);
alterColumns.push(`ALTER COLUMN "${change.name}" TYPE ${localType}${length ? `(${length})` : ''}${change.isArray ? '[]' : ''} USING "${change.name}"::${localType}`);
alterColumns.push(`ALTER COLUMN "${change.name}" ${change.nullable ? 'DROP NOT NULL' : 'SET NOT NULL'}`);
alterColumns.push(`ALTER COLUMN "${change.name}" ${change.default ? `SET DEFAULT ${change.default}` : 'DROP DEFAULT'}`);
@@ -1477,17 +1396,17 @@ export class PostgreSQLClient extends AntaresCore {
* @memberof PostgreSQLClient
*/
async raw (sql, args) {
if (process.env.NODE_ENV === 'development') this._logger(sql);// TODO: replace BLOB content with a placeholder
args = {
nest: false,
details: false,
split: true,
comments: true,
autocommit: true,
...args
};
if (args.schema && args.schema !== 'public')
await this.use(args.schema);
if (!args.comments)
sql = sql.replace(/(\/\*(.|[\r\n])*?\*\/)|(--(.*|[\r\n]))/gm, '');// Remove comments
@@ -1499,26 +1418,7 @@ export class PostgreSQLClient extends AntaresCore {
.map(q => q.trim())
: [sql];
let connection;
const isPool = this._connection instanceof Pool;
if (!args.autocommit && args.tabUid) { // autocommit OFF
if (this._connectionsToCommit.has(args.tabUid))
connection = this._connectionsToCommit.get(args.tabUid);
else {
connection = await this.getConnection();
await connection.query('START TRANSACTION');
this._connectionsToCommit.set(args.tabUid, connection);
}
}
else// autocommit ON
connection = isPool ? await this._connection.connect() : this._connection;
if (args.tabUid && isPool)
this._runningConnections.set(args.tabUid, connection.processID);
if (args.schema && args.schema !== 'public')
await this.use(args.schema, connection);
if (process.env.NODE_ENV === 'development') this._logger(sql);// TODO: replace BLOB content with a placeholder
for (const query of queries) {
if (!query) continue;
@@ -1528,12 +1428,15 @@ export class PostgreSQLClient extends AntaresCore {
let keysArr = [];
const { rows, report, fields, keys, duration } = await new Promise((resolve, reject) => {
(async () => {
try {
const res = await connection.query({ rowMode: args.nest ? 'array' : null, text: query });
timeStop = new Date();
this._connection.query({
rowMode: args.nest ? 'array' : null,
text: query
}, async (err, res) => {
timeStop = new Date();
if (err)
reject(err);
else {
let ast;
try {
@@ -1622,10 +1525,6 @@ export class PostgreSQLClient extends AntaresCore {
});
}
catch (err) {
if (isPool && args.autocommit) {
connection.release();
this._runningConnections.delete(args.tabUid);
}
reject(err);
}
@@ -1634,10 +1533,6 @@ export class PostgreSQLClient extends AntaresCore {
keysArr = keysArr ? [...keysArr, ...response] : response;
}
catch (err) {
if (isPool && args.autocommit) {
connection.release();
this._runningConnections.delete(args.tabUid);
}
reject(err);
}
}
@@ -1652,24 +1547,12 @@ export class PostgreSQLClient extends AntaresCore {
keys: keysArr
});
}
catch (err) {
if (isPool && args.autocommit) {
connection.release();
this._runningConnections.delete(args.tabUid);
}
reject(err);
}
})();
});
});
resultsArr.push({ rows, report, fields, keys, duration });
}
if (isPool && args.autocommit) {
connection.release();
this._runningConnections.delete(args.tabUid);
}
return resultsArr.length === 1 ? resultsArr[0] : resultsArr;
}
}

View File

@@ -1,7 +1,7 @@
'use strict';
import sqlite from 'better-sqlite3';
import { AntaresCore } from '../AntaresCore';
import dataTypes from 'common/data-types/sqlite';
import dataTypes from 'common/data-types/mysql';
import { NUMBER, FLOAT, TIME, DATETIME } from 'common/fieldTypes';
export class SQLiteClient extends AntaresCore {
@@ -9,7 +9,6 @@ export class SQLiteClient extends AntaresCore {
super(args);
this._schema = null;
this._connectionsToCommit = new Map();
}
_getTypeInfo (type) {
@@ -22,11 +21,7 @@ export class SQLiteClient extends AntaresCore {
* @memberof SQLiteClient
*/
async connect () {
this._connection = this.getConnection();
}
getConnection () {
return sqlite(this._params.databasePath, {
this._connection = sqlite(this._params.databasePath, {
fileMustExist: true,
readonly: this._params.readonly
});
@@ -163,7 +158,7 @@ export class SQLiteClient extends AntaresCore {
nullable: !field.notnull,
unsigned: null,
zerofill: null,
order: typeof field.cid === 'string' ? +field.cid + 1 : field.cid + 1,
order: field.cid + 1,
default: field.dflt_value,
charset: null,
collation: null,
@@ -451,40 +446,6 @@ export class SQLiteClient extends AntaresCore {
async killProcess () {}
/**
*
* @param {string} tabUid
* @returns {Promise<null>}
*/
async commitTab (tabUid) {
const connection = this._connectionsToCommit.get(tabUid);
if (connection) {
connection.prepare('COMMIT').run();
return this.destroyConnectionToCommit(tabUid);
}
}
/**
*
* @param {string} tabUid
* @returns {Promise<null>}
*/
async rollbackTab (tabUid) {
const connection = this._connectionsToCommit.get(tabUid);
if (connection) {
connection.prepare('ROLLBACK').run();
return this.destroyConnectionToCommit(tabUid);
}
}
destroyConnectionToCommit (tabUid) {
const connection = this._connectionsToCommit.get(tabUid);
if (connection) {
connection.close();
this._connectionsToCommit.delete(tabUid);
}
}
/**
* CREATE TABLE
*
@@ -705,7 +666,6 @@ export class SQLiteClient extends AntaresCore {
details: false,
split: true,
comments: true,
autocommit: true,
...args
};
@@ -719,20 +679,7 @@ export class SQLiteClient extends AntaresCore {
.filter(Boolean)
.map(q => q.trim())
: [sql];
let connection;
if (!args.autocommit && args.tabUid) { // autocommit OFF
if (this._connectionsToCommit.has(args.tabUid))
connection = this._connectionsToCommit.get(args.tabUid);
else {
connection = this.getConnection();
connection.prepare('BEGIN TRANSACTION').run();
this._connectionsToCommit.set(args.tabUid, connection);
}
}
else// autocommit ON
connection = this._connection;
const connection = this._connection;
for (const query of queries) {
if (!query) continue;
@@ -785,7 +732,7 @@ export class SQLiteClient extends AntaresCore {
if ([...TIME, ...DATETIME].includes(parsedType)) {
const firstNotNull = queryResult.find(res => res[field.name] !== null);
if (firstNotNull && firstNotNull[field.name].includes('.'))
if (firstNotNull[field.name].includes('.'))
length = firstNotNull[field.name].split('.').pop().length;
}

View File

@@ -1,77 +0,0 @@
import fs from 'fs';
import path from 'path';
import EventEmitter from 'events';
export class BaseExporter extends EventEmitter {
constructor (tables, options) {
super();
this._tables = tables;
this._options = options;
this._isCancelled = false;
this._outputStream = fs.createWriteStream(this._options.outputFile, {
flags: 'w'
});
this._state = {};
this._outputStream.once('error', err => {
this._isCancelled = true;
this.emit('error', err);
});
}
async run () {
try {
this.emit('start', this);
await this.dump();
}
catch (err) {
this.emit('error', err);
throw err;
}
finally {
this._outputStream.end();
this.emit('end');
}
}
get isCancelled () {
return this._isCancelled;
}
get outputFile () {
return this._options.outputFile;
}
outputFileExists () {
return fs.existsSync(this._options.outputFile);
}
cancel () {
this._isCancelled = true;
this.emit('cancel');
this.emitUpdate({ op: 'cancelling' });
}
emitUpdate (state) {
this.emit('progress', { ...this._state, ...state });
}
writeString (data) {
if (this._isCancelled) return;
try {
fs.accessSync(this._options.outputFile);
}
catch (err) {
this._isCancelled = true;
const fileName = path.basename(this._options.outputFile);
this.emit('error', `The file ${fileName} is not accessible`);
}
this._outputStream.write(data);
}
dump () {
throw new Error('Exporter must implement the "dump" method');
}
}

View File

@@ -1,412 +0,0 @@
import { SqlExporter } from './SqlExporter';
import { BLOB, BIT, DATE, DATETIME, FLOAT, SPATIAL, IS_MULTI_SPATIAL, NUMBER } from 'common/fieldTypes';
import hexToBinary from 'common/libs/hexToBinary';
import { getArrayDepth } from 'common/libs/getArrayDepth';
import moment from 'moment';
import { lineString, point, polygon } from '@turf/helpers';
export default class MysqlExporter extends SqlExporter {
async getSqlHeader () {
let dump = await super.getSqlHeader();
dump += `
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
SET NAMES utf8mb4;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;`;
return dump;
}
async getFooter () {
const footer = await super.getFooter();
return `/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
${footer}
`;
}
async getCreateTable (tableName) {
const { rows } = await this._client.raw(
`SHOW CREATE TABLE \`${this.schemaName}\`.\`${tableName}\``
);
if (rows.length !== 1) return '';
const col = 'Create View' in rows[0] ? 'Create View' : 'Create Table';
return rows[0][col] + ';';
}
getDropTable (tableName) {
return `DROP TABLE IF EXISTS \`${tableName}\`;`;
}
async * getTableInsert (tableName) {
let rowCount = 0;
let sqlStr = '';
const countResults = await this._client.raw(`SELECT COUNT(1) as count FROM \`${this.schemaName}\`.\`${tableName}\``);
if (countResults.rows.length === 1) rowCount = countResults.rows[0].count;
if (rowCount > 0) {
let queryLength = 0;
let rowsWritten = 0;
let rowIndex = 0;
const { sqlInsertDivider, sqlInsertAfter } = this._options;
const columns = await this._client.getTableColumns({
table: tableName,
schema: this.schemaName
});
const notGeneratedColumns = columns.filter(col => !col.generated);
const columnNames = notGeneratedColumns.map(col => '`' + col.name + '`');
const insertStmt = `INSERT INTO \`${tableName}\` (${columnNames.join(
', '
)}) VALUES`;
sqlStr += `LOCK TABLES \`${tableName}\` WRITE;\n`;
sqlStr += `/*!40000 ALTER TABLE \`${tableName}\` DISABLE KEYS */;`;
sqlStr += '\n\n';
yield sqlStr;
yield insertStmt;
const stream = await this._queryStream(
`SELECT ${columnNames.join(', ')} FROM \`${this.schemaName}\`.\`${tableName}\``
);
for await (const row of stream) {
if (this.isCancelled) {
stream.destroy();
yield null;
return;
}
let sqlInsertString = '';
if (
(sqlInsertDivider === 'bytes' && queryLength >= sqlInsertAfter * 1024) ||
(sqlInsertDivider === 'rows' && rowsWritten === sqlInsertAfter)
) {
sqlInsertString += `;\n${insertStmt}\n\t(`;
queryLength = 0;
rowsWritten = 0;
}
else if (parseInt(rowIndex) === 0) sqlInsertString += '\n\t(';
else sqlInsertString += ',\n\t(';
for (const i in notGeneratedColumns) {
const column = notGeneratedColumns[i];
const val = row[column.name];
if (val === null) sqlInsertString += 'NULL';
else if (DATE.includes(column.type)) {
sqlInsertString += moment(val).isValid()
? this.escapeAndQuote(moment(val).format('YYYY-MM-DD'))
: val;
}
else if (DATETIME.includes(column.type)) {
let datePrecision = '';
for (let i = 0; i < column.precision; i++)
datePrecision += i === 0 ? '.S' : 'S';
sqlInsertString += moment(val).isValid()
? this.escapeAndQuote(moment(val).format(`YYYY-MM-DD HH:mm:ss${datePrecision}`))
: this.escapeAndQuote(val);
}
else if (BIT.includes(column.type))
sqlInsertString += `b'${hexToBinary(Buffer.from(val).toString('hex'))}'`;
else if (BLOB.includes(column.type))
sqlInsertString += `X'${val.toString('hex').toUpperCase()}'`;
else if (NUMBER.includes(column.type))
sqlInsertString += val;
else if (FLOAT.includes(column.type))
sqlInsertString += parseFloat(val);
else if (SPATIAL.includes(column.type)) {
let geoJson;
if (IS_MULTI_SPATIAL.includes(column.type)) {
const features = [];
for (const element of val)
features.push(this.getMarkers(element));
geoJson = {
type: 'FeatureCollection',
features
};
}
else
geoJson = this._getGeoJSON(val);
sqlInsertString += `ST_GeomFromGeoJSON('${JSON.stringify(geoJson)}')`;
}
else if (val === '') sqlInsertString += '\'\'';
else {
sqlInsertString += typeof val === 'string'
? this.escapeAndQuote(val)
: typeof val === 'object'
? this.escapeAndQuote(JSON.stringify(val))
: val;
}
if (parseInt(i) !== notGeneratedColumns.length - 1)
sqlInsertString += ', ';
}
sqlInsertString += ')';
queryLength += sqlInsertString.length;
rowsWritten++;
rowIndex++;
yield sqlInsertString;
}
sqlStr = ';\n\n';
sqlStr += `/*!40000 ALTER TABLE \`${tableName}\` ENABLE KEYS */;\n`;
sqlStr += 'UNLOCK TABLES;';
yield sqlStr;
}
}
async getViews () {
const { rows: views } = await this._client.raw(
`SHOW TABLE STATUS FROM \`${this.schemaName}\` WHERE Comment = 'VIEW'`
);
let sqlString = '';
for (const view of views) {
sqlString += `DROP VIEW IF EXISTS \`${view.Name}\`;\n`;
const viewSyntax = await this.getCreateTable(view.Name);
sqlString += viewSyntax.replaceAll('`' + this.schemaName + '`.', '');
sqlString += '\n';
}
return sqlString;
}
async getTriggers () {
const { rows: triggers } = await this._client.raw(
`SHOW TRIGGERS FROM \`${this.schemaName}\``
);
const generatedTables = this._tables
.filter(t => t.includeStructure)
.map(t => t.table);
let sqlString = '';
for (const trigger of triggers) {
const {
Trigger: name,
Timing: timing,
Event: event,
Table: table,
Statement: statement,
sql_mode: sqlMode
} = trigger;
if (!generatedTables.includes(table)) continue;
const definer = this.getEscapedDefiner(trigger.Definer);
sqlString += '/*!50003 SET @OLD_SQL_MODE=@@SQL_MODE*/;;\n';
sqlString += `/*!50003 SET SQL_MODE="${sqlMode}" */;\n`;
sqlString += 'DELIMITER ;;\n';
sqlString += '/*!50003 CREATE*/ ';
sqlString += `/*!50017 DEFINER=${definer}*/ `;
sqlString += `/*!50003 TRIGGER \`${name}\` ${timing} ${event} ON \`${table}\` FOR EACH ROW ${statement}*/;;\n`;
sqlString += 'DELIMITER ;\n';
sqlString += '/*!50003 SET SQL_MODE=@OLD_SQL_MODE */;\n\n';
}
return sqlString;
}
async getSchedulers () {
const { rows: schedulers } = await this._client.raw(
`SELECT *, EVENT_SCHEMA AS \`Db\`, EVENT_NAME AS \`Name\` FROM information_schema.\`EVENTS\` WHERE EVENT_SCHEMA = '${this.schemaName}'`
);
let sqlString = '';
for (const scheduler of schedulers) {
const {
EVENT_NAME: name,
SQL_MODE: sqlMode,
EVENT_TYPE: type,
INTERVAL_VALUE: intervalValue,
INTERVAL_FIELD: intervalField,
STARTS: starts,
ENDS: ends,
EXECUTE_AT: at,
ON_COMPLETION: onCompletion,
STATUS: status,
EVENT_DEFINITION: definition
} = scheduler;
const definer = this.getEscapedDefiner(scheduler.DEFINER);
const comment = this.escapeAndQuote(scheduler.EVENT_COMMENT);
sqlString += `/*!50106 DROP EVENT IF EXISTS \`${name}\` */;\n`;
sqlString += '/*!50003 SET @OLD_SQL_MODE=@@SQL_MODE*/;;\n';
sqlString += `/*!50003 SET SQL_MODE='${sqlMode}' */;\n`;
sqlString += 'DELIMITER ;;\n';
sqlString += '/*!50106 CREATE*/ ';
sqlString += `/*!50117 DEFINER=${definer}*/ `;
sqlString += `/*!50106 EVENT \`${name}\` ON SCHEDULE `;
if (type === 'RECURRING') {
sqlString += `EVERY ${intervalValue} ${intervalField} STARTS '${starts}' `;
if (ends) sqlString += `ENDS '${ends}' `;
}
else sqlString += `AT '${at}' `;
sqlString += `ON COMPLETION ${onCompletion} ${
status === 'disabled' ? 'DISABLE' : 'ENABLE'
} COMMENT ${comment || '\'\''} DO ${definition}*/;;\n`;
sqlString += 'DELIMITER ;\n';
sqlString += '/*!50003 SET SQL_MODE=@OLD_SQL_MODE*/;;\n';
}
return sqlString;
}
async getFunctions () {
const { rows: functions } = await this._client.raw(
`SHOW FUNCTION STATUS WHERE \`Db\` = '${this.schemaName}';`
);
let sqlString = '';
for (const func of functions) {
const definer = this.getEscapedDefiner(func.Definer);
sqlString += await this.getRoutineSyntax(
func.Name,
func.Type,
definer
);
}
return sqlString;
}
async getRoutines () {
const { rows: routines } = await this._client.raw(
`SHOW PROCEDURE STATUS WHERE \`Db\` = '${this.schemaName}';`
);
let sqlString = '';
for (const routine of routines) {
const definer = this.getEscapedDefiner(routine.Definer);
sqlString += await this.getRoutineSyntax(
routine.Name,
routine.Type,
definer
);
}
return sqlString;
}
async getRoutineSyntax (name, type, definer) {
const { rows: routines } = await this._client.raw(
`SHOW CREATE ${type} \`${this.schemaName}\`.\`${name}\``
);
if (routines.length === 0) return '';
const routine = routines[0];
const fieldName = `Create ${type === 'PROCEDURE' ? 'Procedure' : 'Function'}`;
const sqlMode = routine.sql_mode;
const createProcedure = routine[fieldName];
let sqlString = '';
if (createProcedure) { // If procedure body not empty
const startOffset = createProcedure.indexOf(type);
const procedureBody = createProcedure.substring(startOffset);
sqlString += `/*!50003 DROP ${type} IF EXISTS ${name}*/;;\n`;
sqlString += '/*!50003 SET @OLD_SQL_MODE=@@SQL_MODE*/;;\n';
sqlString += `/*!50003 SET SQL_MODE="${sqlMode}"*/;;\n`;
sqlString += 'DELIMITER ;;\n';
sqlString += `/*!50003 CREATE*/ /*!50020 DEFINER=${definer}*/ /*!50003 ${procedureBody}*/;;\n`;
sqlString += 'DELIMITER ;\n';
sqlString += '/*!50003 SET SQL_MODE=@OLD_SQL_MODE*/;\n';
}
return sqlString;
}
async _queryStream (sql) {
if (process.env.NODE_ENV === 'development') console.log('EXPORTER:', sql);
const isPool = typeof this._client._connection.getConnection === 'function';
const connection = isPool ? await this._client._connection.getConnection() : this._client._connection;
const stream = connection.connection.query(sql).stream();
const dispose = () => connection.destroy();
stream.on('end', dispose);
stream.on('error', dispose);
stream.on('close', dispose);
return stream;
}
getEscapedDefiner (definer) {
return definer
.split('@')
.map(part => '`' + part + '`')
.join('@');
}
escapeAndQuote (val) {
// eslint-disable-next-line no-control-regex
const CHARS_TO_ESCAPE = /[\0\b\t\n\r\x1a"'\\]/g;
const CHARS_ESCAPE_MAP = {
'\0': '\\0',
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\r': '\\r',
'\x1a': '\\Z',
'"': '\\"',
'\'': '\\\'',
'\\': '\\\\'
};
let chunkIndex = CHARS_TO_ESCAPE.lastIndex = 0;
let escapedVal = '';
let match;
while ((match = CHARS_TO_ESCAPE.exec(val))) {
escapedVal += val.slice(chunkIndex, match.index) + CHARS_ESCAPE_MAP[match[0]];
chunkIndex = CHARS_TO_ESCAPE.lastIndex;
}
if (chunkIndex === 0)
return `'${val}'`;
if (chunkIndex < val.length)
return `'${escapedVal + val.slice(chunkIndex)}'`;
return `'${escapedVal}'`;
}
_getGeoJSON (val) {
if (Array.isArray(val)) {
if (getArrayDepth(val) === 1)
return lineString(val.reduce((acc, curr) => [...acc, [curr.x, curr.y]], []));
else
return polygon(val.map(arr => arr.reduce((acc, curr) => [...acc, [curr.x, curr.y]], [])));
}
else
return point([val.x, val.y]);
}
}

View File

@@ -1,162 +0,0 @@
import moment from 'moment';
import { BaseExporter } from '../BaseExporter';
export class SqlExporter extends BaseExporter {
constructor (client, tables, options) {
super(tables, options);
this._client = client;
this._commentChar = '#';
}
get schemaName () {
return this._options.schema;
}
get host () {
return this._client._params.host;
}
async getServerVersion () {
const version = await this._client.getVersion();
return `${version.name} ${version.number}`;
}
async dump () {
const { includes } = this._options;
const extraItems = Object.keys(includes).filter(key => includes[key]);
const totalTableToProcess = this._tables.filter(
t => t.includeStructure || t.includeContent || t.includeDropStatement
).length;
const processingItemCount = totalTableToProcess + extraItems.length;
const exportState = {
totalItems: processingItemCount,
currentItemIndex: 0,
currentItem: '',
op: ''
};
const header = await this.getSqlHeader();
this.writeString(header);
this.writeString('\n\n\n');
for (const item of this._tables) {
// user abort operation
if (this.isCancelled) return;
// skip item if not set to output any detail for them
if (
!item.includeStructure &&
!item.includeContent &&
!item.includeDropStatement
)
continue;
exportState.currentItemIndex++;
exportState.currentItem = item.table;
exportState.op = 'FETCH';
this.emitUpdate(exportState);
const tableHeader = this.buildComment(
`Dump of table ${item.table}\n------------------------------------------------------------`
);
this.writeString(tableHeader);
this.writeString('\n\n');
if (item.includeDropStatement) {
const dropTableSyntax = this.getDropTable(item.table);
this.writeString(dropTableSyntax);
this.writeString('\n\n');
}
if (item.includeStructure) {
const createTableSyntax = await this.getCreateTable(item.table);
this.writeString(createTableSyntax);
this.writeString('\n\n');
}
if (item.includeContent) {
exportState.op = 'WRITE';
this.emitUpdate(exportState);
for await (const sqlStr of this.getTableInsert(item.table)) {
if (this.isCancelled) return;
this.writeString(sqlStr);
}
this.writeString('\n\n');
}
this.writeString('\n\n');
}
for (const item of extraItems) {
const processingMethod = `get${item.charAt(0).toUpperCase() + item.slice(1)}`;
exportState.currentItemIndex++;
exportState.currentItem = item;
exportState.op = 'PROCESSING';
this.emitUpdate(exportState);
if (this[processingMethod]) {
const data = await this[processingMethod]();
if (data !== '') {
const header =
this.buildComment(
`Dump of ${item}\n------------------------------------------------------------`
) + '\n\n';
this.writeString(header);
this.writeString(data);
this.writeString('\n\n');
}
}
}
const footer = await this.getFooter();
this.writeString(footer);
}
buildComment (text) {
return text
.split('\n')
.map(txt => `${this._commentChar} ${txt}`)
.join('\n');
}
async getSqlHeader () {
const serverVersion = await this.getServerVersion();
const header = `************************************************************
Antares - SQL Client
Version ${process.env.PACKAGE_VERSION}
https://antares-sql.app/
https://github.com/Fabio286/antares
Host: ${this.host} (${serverVersion})
Database: ${this.schemaName}
Generation time: ${moment().format()}
************************************************************`;
return this.buildComment(header);
}
async getFooter () {
return this.buildComment(`Dump completed on ${moment().format()}`);
}
getCreateTable (tableName) {
throw new Error(
'Sql Exporter must implement the "getCreateTable" method'
);
}
getDropTable (tableName) {
throw new Error('Sql Exporter must implement the "getDropTable" method');
}
getTableInsert (tableName) {
throw new Error(
'Sql Exporter must implement the "getTableInsert" method'
);
}
}

View File

@@ -1,53 +0,0 @@
import fs from 'fs';
import EventEmitter from 'events';
export class BaseImporter extends EventEmitter {
constructor (options) {
super();
this._options = options;
this._isCancelled = false;
this._fileHandler = fs.createReadStream(this._options.file, {
flags: 'r',
highWaterMark: 4 * 1024
});
this._state = {};
this._fileHandler.once('error', err => {
this._isCancelled = true;
this.emit('error', err);
});
}
async run () {
try {
this.emit('start', this);
await this.import();
}
catch (err) {
this.emit('error', err);
throw err;
}
finally {
this._fileHandler.close();
this.emit('end');
}
}
get isCancelled () {
return this._isCancelled;
}
cancel () {
this._isCancelled = true;
this.emit('cancel');
this.emitUpdate({ op: 'cancelling' });
}
emitUpdate (state) {
this.emit('progress', { ...this._state, ...state });
}
import () {
throw new Error('Exporter must implement the "import" method');
}
}

View File

@@ -1,85 +0,0 @@
import fs from 'fs/promises';
import SqlParser from '../../../../common/libs/sqlParser';
import { BaseImporter } from '../BaseImporter';
export default class MysqlImporter extends BaseImporter {
constructor (client, options) {
super(options);
this._client = client;
}
async import () {
try {
const { size: totalFileSize } = await fs.stat(this._options.file);
const parser = new SqlParser();
let readPosition = 0;
let queryCount = 0;
this.emitUpdate({
fileSize: totalFileSize,
readPosition: 0,
percentage: 0,
queryCount: 0
});
// 1. detect file encoding
// 2. set fh encoding
// 3. detect sql mode
// 4. restore sql mode in case of exception
return new Promise((resolve, reject) => {
this._fileHandler.pipe(parser);
parser.on('error', reject);
parser.on('close', async () => {
console.log('TOTAL QUERIES', queryCount);
console.log('import end');
resolve();
});
parser.on('data', async (query) => {
queryCount++;
parser.pause();
try {
await this._client.query(query);
}
catch (error) {
this.emit('query-error', {
sql: query,
message: error.sqlMessage,
sqlSnippet: error.sql,
time: new Date().getTime()
});
}
this.emitUpdate({
queryCount,
readPosition,
percentage: readPosition / totalFileSize * 100
});
this._fileHandler.pipe(parser);
parser.resume();
});
parser.on('pause', () => {
this._fileHandler.unpipe(parser);
this._fileHandler.readableFlowing = false;
});
this._fileHandler.on('data', (chunk) => {
readPosition += chunk.length;
});
this._fileHandler.on('error', (err) => {
console.log(err);
reject(err);
});
});
}
catch (err) {
console.log(err);
}
}
}

View File

@@ -3,7 +3,6 @@
import { app, BrowserWindow, /* session, */ nativeImage, Menu } from 'electron';
import * as path from 'path';
import Store from 'electron-store';
import * as windowStateKeeper from 'electron-window-state';
import * as remoteMain from '@electron/remote/main';
import ipcHandlers from './ipc-handlers';
@@ -19,15 +18,12 @@ process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = 'true';
// global reference to mainWindow (necessary to prevent window from being garbage collected)
let mainWindow;
let mainWindowState;
async function createMainWindow () {
const icon = require('../renderer/images/logo-32.png');
const window = new BrowserWindow({
width: mainWindowState.width,
height: mainWindowState.height,
x: mainWindowState.x,
y: mainWindowState.y,
width: 1024,
height: 800,
minWidth: 900,
minHeight: 550,
title: 'Antares SQL',
@@ -45,9 +41,6 @@ async function createMainWindow () {
backgroundColor: '#1d1d1d'
});
mainWindowState.manage(window);
window.on('moved', saveWindowState);
remoteMain.enable(window.webContents);
try {
@@ -77,10 +70,16 @@ async function createMainWindow () {
}
window.on('closed', () => {
window.removeListener('moved', saveWindowState);
mainWindow = null;
});
window.webContents.on('devtools-opened', () => {
window.focus();
setImmediate(() => {
window.focus();
});
});
return window;
}
@@ -105,11 +104,6 @@ else {
// create main BrowserWindow when electron is ready
app.on('ready', async () => {
mainWindowState = windowStateKeeper({
defaultWidth: 1024,
defaultHeight: 800
});
mainWindow = await createMainWindow();
createAppMenu();
@@ -166,7 +160,3 @@ function createAppMenu () {
Menu.setApplicationMenu(menu);
}
function saveWindowState () {
mainWindowState.saveState(mainWindow);
}

View File

@@ -1,60 +0,0 @@
import { ClientsFactory } from '../libs/ClientsFactory';
import MysqlExporter from '../libs/exporters/sql/MysqlExporter.js';
import fs from 'fs';
let exporter;
process.on('message', async ({ type, client, tables, options }) => {
if (type === 'init') {
const connection = await ClientsFactory.getClient({
client: client.name,
params: client.config,
poolSize: 5
});
await connection.connect();
switch (client.name) {
case 'mysql':
case 'maria':
exporter = new MysqlExporter(connection, tables, options);
break;
default:
process.send({
type: 'error',
payload: `"${client.name}" exporter not aviable`
});
return;
}
exporter.once('error', err => {
console.error(err);
process.send({
type: 'error',
payload: err.toString()
});
});
exporter.once('end', () => {
process.send({
type: 'end',
payload: { cancelled: exporter.isCancelled }
});
connection.destroy();
});
exporter.once('cancel', () => {
fs.unlinkSync(exporter.outputFile);
process.send({ type: 'cancel' });
});
exporter.on('progress', state => {
process.send({
type: 'export-progress',
payload: state
});
});
exporter.run();
}
else if (type === 'cancel')
exporter.cancel();
});

View File

@@ -1,68 +0,0 @@
import { ClientsFactory } from '../libs/ClientsFactory';
import MysqlImporter from '../libs/importers/sql/MysqlImporter';
let importer;
process.on('message', async ({ type, dbConfig, options }) => {
if (type === 'init') {
const connection = await ClientsFactory.getClient({
client: options.type,
params: {
...dbConfig,
schema: options.schema
},
poolSize: 1
});
const pool = await connection.getConnectionPool();
switch (options.type) {
case 'mysql':
case 'maria':
importer = new MysqlImporter(pool, options);
break;
default:
process.send({
type: 'error',
payload: `"${options.type}" importer not aviable`
});
return;
}
importer.once('error', err => {
console.error(err);
process.send({
type: 'error',
payload: err.toString()
});
});
importer.once('end', () => {
process.send({
type: 'end',
payload: { cancelled: importer.isCancelled }
});
});
importer.once('cancel', () => {
process.send({ type: 'cancel' });
});
importer.on('progress', state => {
process.send({
type: 'import-progress',
payload: state
});
});
importer.on('query-error', state => {
process.send({
type: 'query-error',
payload: state
});
});
importer.run();
}
else if (type === 'cancel')
importer.cancel();
});

View File

@@ -110,4 +110,5 @@ export default {
.modal.modal-sm .modal-container {
padding: 0;
}
</style>

View File

@@ -1,108 +0,0 @@
<template>
<div id="map" class="map" />
</template>
<script>
import L from 'leaflet';
import {
point,
lineString,
polygon
} from '@turf/helpers';
import { getArrayDepth } from 'common/libs/getArrayDepth';
export default {
name: 'BaseMap',
props: {
points: [Object, Array],
isMultiSpatial: Boolean
},
data () {
return {
map: null,
markers: [],
center: null
};
},
mounted () {
if (this.isMultiSpatial) {
for (const element of this.points)
this.markers.push(this.getMarkers(element));
}
else {
this.markers = this.getMarkers(this.points);
if (!Array.isArray(this.points))
this.center = [this.points.y, this.points.x];
}
this.map = L.map('map', {
center: this.center || [0, 0],
zoom: 15,
minZoom: 1,
attributionControl: false
});
L.control.attribution({ prefix: '<b>Leaflet</b>' }).addTo(this.map);
const geoJsonObj = L.geoJSON(this.markers, {
style: function () {
return {
weight: 2,
fillColor: '#ff7800',
color: '#ff7800',
opacity: 0.8,
fillOpacity: 0.4
};
},
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng, {
radius: 7,
weight: 2,
fillColor: '#ff7800',
color: '#ff7800',
opacity: 0.8,
fillOpacity: 0.4
});
}
}).addTo(this.map);
const southWest = L.latLng(-90, -180);
const northEast = L.latLng(90, 180);
const bounds = L.latLngBounds(southWest, northEast);
this.map.setMaxBounds(bounds);
if (!this.center) this.map.fitBounds(geoJsonObj.getBounds());
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '&copy; <b>OpenStreetMap</b>'
}).addTo(this.map);
},
methods: {
getMarkers (points) {
if (Array.isArray(points)) {
if (getArrayDepth(points) === 1)
return lineString(points.reduce((acc, curr) => [...acc, [curr.x, curr.y]], []));
else
return polygon(points.map(arr => arr.reduce((acc, curr) => [...acc, [curr.x, curr.y]], [])));
}
else
return point([points.x, points.y]);
}
}
};
</script>
<style lang="scss">
.map {
height: 400px;
}
.marker-icon {
display: flex;
justify-content: center;
align-items: center;
background: $primary-color;
border-radius: 50%;
box-shadow: 0 0 5px 1px darken($body-font-color-dark, 40%);
}
</style>

View File

@@ -7,7 +7,7 @@
@blur="$emit('blur')"
>
<option v-if="!isValidDefault" :value="value">
{{ value === null ? 'NULL' : value }}
{{ value }} - {{ $t('message.invalidDefault') }}
</option>
<option
v-for="row in foreignList"

View File

@@ -6,13 +6,13 @@
@confirm="runRoutine"
@hide="closeModal"
>
<template #header>
<template slot="header">
<div class="d-flex">
<i class="mdi mdi-24px mdi-play mr-1" />
<span class="cut-text">{{ $t('word.parameters') }}: {{ localRoutine.name }}</span>
</div>
</template>
<template #body>
<div slot="body">
<div class="content">
<form class="form-horizontal">
<div
@@ -43,7 +43,7 @@
</div>
</form>
</div>
</template>
</div>
</ConfirmModal>
</template>

View File

@@ -5,16 +5,16 @@
@confirm="$emit('confirm')"
@hide="$emit('close')"
>
<template #header>
<template slot="header">
<div class="d-flex">
<i class="mdi mdi-24px mdi-content-save-alert mr-1" /> {{ $t('message.unsavedChanges') }}
</div>
</template>
<template #body>
<div slot="body">
<div>
{{ $t('message.discardUnsavedChanges') }}
</div>
</template>
</div>
</ConfirmModal>
</template>

View File

@@ -1,491 +0,0 @@
<template>
<div class="modal active">
<a class="modal-overlay" @click.stop="closeModal" />
<div class="modal-container p-0">
<div class="modal-header pl-2">
<div class="modal-title h6">
<div class="d-flex">
<i class="mdi mdi-24px mdi-database-arrow-down mr-1" />
<span class="cut-text">{{ $t('message.exportSchema') }}</span>
</div>
</div>
<a class="btn btn-clear c-hand" @click.stop="closeModal" />
</div>
<div class="modal-body pb-0">
<div class="container">
<div class="columns">
<div class="col-3">
<label class="form-label">{{ $t('message.directoryPath') }}</label>
</div>
<div class="col-9">
<fieldset class="input-group">
<input
v-model="basePath"
class="form-input"
type="text"
required
readonly
:placeholder="$t('message.schemaName')"
>
<button
type="button"
class="btn btn-primary input-group-btn"
@click.prevent="openPathDialog"
>
{{ $t('word.change') }}
</button>
</fieldset>
</div>
</div>
</div>
<div class="columns export-options">
<div class="column col-8 left">
<div class="columns mb-2">
<div class="column col-auto d-flex text-italic ">
<i class="mdi mdi-file-document-outline mr-2" />
{{ filename }}
</div>
<div class="column col-auto col-ml-auto ">
<button
class="btn btn-dark btn-sm"
:title="$t('word.refresh')"
@click="refresh"
>
<i class="mdi mdi-database-refresh" />
</button>
<button
class="btn btn-dark btn-sm"
:title="$t('message.uncheckAllTables')"
:disabled="isRefreshing"
@click="uncheckAllTables"
>
<i class="mdi mdi-file-tree-outline" />
</button>
<button
class="btn btn-dark btn-sm"
:title="$t('message.checkAllTables')"
:disabled="isRefreshing"
@click="checkAllTables"
>
<i class="mdi mdi-file-tree" />
</button>
</div>
</div>
<div class="workspace-query-results">
<div ref="table" class="table table-hover">
<div class="thead">
<div class="tr text-center">
<div class="th no-border" style="width: 50%;" />
<div class="th no-border">
<label
class="form-checkbox m-0 px-2 form-inline"
@click.prevent="toggleAllTablesOption('includeStructure')"
>
<input
type="checkbox"
:indeterminate.prop="includeStructureStatus === 2"
:checked.prop="!!includeStructureStatus"
>
<i class="form-icon" />
</label>
</div>
<div class="th no-border">
<label
class="form-checkbox m-0 px-2 form-inline"
@click.prevent="toggleAllTablesOption('includeContent')"
>
<input
type="checkbox"
:indeterminate.prop="includeContentStatus === 2"
:checked.prop="!!includeContentStatus"
>
<i class="form-icon" />
</label>
</div>
<div class="th no-border">
<label
class="form-checkbox m-0 px-2 form-inline"
@click.prevent="toggleAllTablesOption('includeDropStatement')"
>
<input
type="checkbox"
:indeterminate.prop="includeDropStatementStatus === 2"
:checked.prop="!!includeDropStatementStatus"
>
<i class="form-icon" />
</label>
</div>
</div>
<div class="tr">
<div class="th" style="width: 50%;">
<div class="table-column-title">
<span>{{ $t('word.table') }}</span>
</div>
</div>
<div class="th text-center">
<div class="table-column-title">
<span>{{ $t('word.structure') }}</span>
</div>
</div>
<div class="th text-center">
<div class="table-column-title">
<span>{{ $t('word.content') }}</span>
</div>
</div>
<div class="th text-center">
<div class="table-column-title">
<span>{{ $t('word.drop') }}</span>
</div>
</div>
</div>
</div>
<div class="tbody">
<div
v-for="item in tables"
:key="item.name"
class="tr"
>
<div class="td">
{{ item.table }}
</div>
<div class="td text-center">
<label class="form-checkbox m-0 px-2 form-inline">
<input
v-model="item.includeStructure"
type="checkbox"
><i class="form-icon" />
</label>
</div>
<div class="td text-center">
<label class="form-checkbox m-0 px-2 form-inline">
<input
v-model="item.includeContent"
type="checkbox"
><i class="form-icon" />
</label>
</div>
<div class="td text-center">
<label class="form-checkbox m-0 px-2 form-inline">
<input
v-model="item.includeDropStatement"
type="checkbox"
><i class="form-icon" />
</label>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="column col-4">
<h4>
{{ $t('word.options') }}
</h4>
<span>{{ $t('word.includes') }}:</span>
<label
v-for="(_, key) in options.includes"
:key="key"
class="form-checkbox"
>
<input v-model="options.includes[key]" type="checkbox"><i class="form-icon" /> {{ $t(`word.${key}`) }}
</label>
<div class="mt-4 mb-2">
{{ $t('message.newInserStmtEvery') }}:
</div>
<div class="columns">
<div class="column col-6">
<input
v-model.number="options.sqlInsertAfter"
type="number"
class="form-input"
value="250"
>
</div>
<div class="column col-6">
<select v-model="options.sqlInsertDivider" class="form-select">
<option value="bytes">
KiB
</option>
<option value="rows">
{{ $tc('word.row', 2) }}
</option>
</select>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer columns">
<div class="column col modal-progress-wrapper text-left">
<div v-if="progressPercentage > 0" class="export-progress">
<span class="progress-status">
{{ progressPercentage }}% - {{ progressStatus }}
</span>
<progress
class="progress d-block"
:value="progressPercentage"
max="100"
/>
</div>
</div>
<div class="column col-auto px-0">
<button class="btn btn-link" @click.stop="closeModal">
{{ $t('word.close') }}
</button>
<button
class="btn btn-primary mr-2"
:class="{'loading': isExporting}"
:disabled="isExporting || isRefreshing"
autofocus
@click.prevent="startExport"
>
{{ $t('word.export') }}
</button>
</div>
</div>
</div>
</div>
</template>
<script>
import { ipcRenderer } from 'electron';
import { mapActions, mapGetters } from 'vuex';
import moment from 'moment';
import customizations from 'common/customizations';
import Application from '@/ipc-api/Application';
import Schema from '@/ipc-api/Schema';
export default {
name: 'ModalExportSchema',
props: {
selectedSchema: String
},
data () {
return {
isExporting: false,
isRefreshing: false,
progressPercentage: 0,
progressStatus: '',
tables: [],
options: {
includes: {},
sqlInsertAfter: 250,
sqlInsertDivider: 'bytes'
},
basePath: ''
};
},
computed: {
...mapGetters({
selectedWorkspace: 'workspaces/getSelected',
getWorkspace: 'workspaces/getWorkspace',
getDatabaseVariable: 'workspaces/getDatabaseVariable'
}),
currentWorkspace () {
return this.getWorkspace(this.selectedWorkspace);
},
schemaItems () {
const db = this.currentWorkspace.structure.find(db => db.name === this.selectedSchema);
if (db)
return db.tables.filter(table => table.type === 'table');
return [];
},
filename () {
const date = moment().format('YYYY-MM-DD');
return `${this.selectedSchema}_${date}.sql`;
},
dumpFilePath () {
return `${this.basePath}/${this.filename}`;
},
includeStructureStatus () {
if (this.tables.every(item => item.includeStructure)) return 1;
else if (this.tables.some(item => item.includeStructure)) return 2;
else return 0;
},
includeContentStatus () {
if (this.tables.every(item => item.includeContent)) return 1;
else if (this.tables.some(item => item.includeContent)) return 2;
else return 0;
},
includeDropStatementStatus () {
if (this.tables.every(item => item.includeDropStatement)) return 1;
else if (this.tables.some(item => item.includeDropStatement)) return 2;
else return 0;
}
},
async created () {
if (!this.schemaItems.length) await this.refresh();
window.addEventListener('keydown', this.onKey);
this.basePath = await Application.getDownloadPathDirectory();
this.tables = this.schemaItems.map(item => ({
table: item.name,
includeStructure: true,
includeContent: true,
includeDropStatement: true
}));
const structure = ['views', 'triggers', 'routines', 'functions', 'schedulers', 'triggerFunctions'];
structure.forEach(feat => {
const val = customizations[this.currentWorkspace.client][feat];
if (val)
this.$set(this.options.includes, feat, true);
});
ipcRenderer.on('export-progress', this.updateProgress);
},
beforeDestroy () {
window.removeEventListener('keydown', this.onKey);
ipcRenderer.off('export-progress', this.updateProgress);
},
methods: {
...mapActions({
addNotification: 'notifications/addNotification',
refreshSchema: 'workspaces/refreshSchema'
}),
async startExport () {
this.isExporting = true;
const { uid, client } = this.currentWorkspace;
const params = {
uid,
type: client,
schema: this.selectedSchema,
outputFile: this.dumpFilePath,
tables: [...this.tables],
...this.options
};
try {
const { status, response } = await Schema.export(params);
if (status === 'success')
this.progressStatus = response.cancelled ? this.$t('word.aborted') : this.$t('word.completed');
else {
this.progressStatus = response;
this.addNotification({ status: 'error', message: response });
}
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
this.isExporting = false;
},
updateProgress (event, state) {
this.progressPercentage = Number((state.currentItemIndex / state.totalItems * 100).toFixed(1));
switch (state.op) {
case 'PROCESSING':
this.progressStatus = this.$t('message.processingTableExport', { table: state.currentItem });
break;
case 'FETCH':
this.progressStatus = this.$t('message.fechingTableExport', { table: state.currentItem });
break;
case 'WRITE':
this.progressStatus = this.$t('message.writingTableExport', { table: state.currentItem });
break;
}
},
async closeModal () {
let willClose = true;
if (this.isExporting) {
willClose = false;
const { response } = await Schema.abortExport();
willClose = response.willAbort;
}
if (willClose)
this.$emit('close');
},
onKey (e) {
e.stopPropagation();
if (e.key === 'Escape')
this.closeModal();
},
checkAllTables () {
this.tables = this.tables.map(item => ({ ...item, includeStructure: true, includeContent: true, includeDropStatement: true }));
},
uncheckAllTables () {
this.tables = this.tables.map(item => ({ ...item, includeStructure: false, includeContent: false, includeDropStatement: false }));
},
toggleAllTablesOption (option) {
const options = ['includeStructure', 'includeContent', 'includeDropStatement'];
if (!options.includes(option)) return;
if (this[`${option}Status`] !== 1)
this.tables = this.tables.map(item => ({ ...item, [option]: true }));
else
this.tables = this.tables.map(item => ({ ...item, [option]: false }));
},
async refresh () {
this.isRefreshing = true;
await this.refreshSchema({ uid: this.currentWorkspace.uid, schema: this.selectedSchema });
this.isRefreshing = false;
},
async openPathDialog () {
const result = await Application.showOpenDialog({ properties: ['openDirectory'] });
if (result && !result.canceled)
this.basePath = result.filePaths[0];
}
}
};
</script>
<style lang="scss" scoped>
.export-options {
flex: 1;
overflow: hidden;
.left {
display: flex;
flex-direction: column;
flex: 1;
}
}
.workspace-query-results {
flex: 1 0 1px;
.table {
width: 100% !important;
}
.form-checkbox {
min-height: 0.8rem;
padding: 0;
.form-icon {
top: 0.1rem;
}
}
}
.modal {
.modal-container {
max-width: 800px;
}
.modal-body {
max-height: 60vh;
display: flex;
flex-direction: column;
}
.modal-footer {
display: flex;
}
}
.progress-status {
font-style: italic;
font-size: 80%;
}
</style>

View File

@@ -6,7 +6,7 @@
<div class="modal-title h6">
<div class="d-flex">
<i class="mdi mdi-24px mdi-playlist-plus mr-1" />
<span class="cut-text">{{ $tc('message.insertRow', 2) }}</span>
<span class="cut-text">{{ $t('message.tableFiller') }}</span>
</div>
</div>
<a class="btn btn-clear c-hand" @click.stop="closeModal" />
@@ -41,7 +41,7 @@
<label class="form-checkbox ml-3" :title="$t('word.insert')">
<input
type="checkbox"
:checked="!fieldsToExclude.includes(field.name)"
:checked="!field.autoIncrement"
@change.prevent="toggleFields($event, field)"
><i class="form-icon" />
</label>
@@ -264,7 +264,7 @@ export default {
else if (BIT.includes(field.type))
fieldDefault = field.default.replaceAll('\'', '').replaceAll('b', '');
else if (DATETIME.includes(field.type)) {
if (field.default && ['current_timestamp', 'now()'].some(term => field.default.toLowerCase().includes(term))) {
if (field.default && ['current_timestamp', 'now()'].includes(field.default.toLowerCase())) {
let datePrecision = '';
for (let i = 0; i < field.datePrecision; i++)
datePrecision += i === 0 ? '.S' : 'S';
@@ -281,7 +281,7 @@ export default {
rowObj[field.name] = { value: fieldDefault };
if (field.autoIncrement || !!field.onUpdate)// Disable by default auto increment or "on update" fields
if (field.autoIncrement)// Disable by default auto increment fields
this.fieldsToExclude = [...this.fieldsToExclude, field.name];
}

View File

@@ -1,181 +0,0 @@
<template>
<div class="modal active">
<a class="modal-overlay" @click.stop="closeModal" />
<div class="modal-container p-0">
<div class="modal-header pl-2">
<div class="modal-title h6">
<div class="d-flex">
<i class="mdi mdi-24px mdi-database-arrow-up mr-1" />
<span class="cut-text">{{ $t('message.importSchema') }}</span>
</div>
</div>
<a class="btn btn-clear c-hand" @click.stop="closeModal" />
</div>
<div class="modal-body pb-0">
{{ sqlFile }}
<div v-if="queryErrors.length > 0" class="mt-2">
<label>{{ $tc('message.importQueryErrors', queryErrors.length) }}</label>
<textarea
v-model="formattedQueryErrors"
class="form-input"
rows="5"
readonly
/>
</div>
</div>
<div class="modal-footer columns">
<div class="column col modal-progress-wrapper text-left">
<div class="import-progress">
<span class="progress-status">
{{ progressPercentage }}% - {{ progressStatus }} - {{ $tc('message.executedQueries', queryCount) }}
</span>
<progress
class="progress d-block"
:value="progressPercentage"
max="100"
/>
</div>
</div>
<div class="column col-auto px-0">
<button class="btn btn-link" @click.stop="closeModal">
{{ completed ? $t('word.close') : $t('word.cancel') }}
</button>
</div>
</div>
</div>
</div>
</template>
<script>
import { ipcRenderer } from 'electron';
import { mapActions, mapGetters } from 'vuex';
import moment from 'moment';
import Schema from '@/ipc-api/Schema';
export default {
name: 'ModalImportSchema',
props: {
selectedSchema: String
},
data () {
return {
sqlFile: '',
isImporting: false,
progressPercentage: 0,
queryCount: 0,
completed: false,
progressStatus: 'Reading',
queryErrors: []
};
},
computed: {
...mapGetters({
selectedWorkspace: 'workspaces/getSelected',
getWorkspace: 'workspaces/getWorkspace'
}),
currentWorkspace () {
return this.getWorkspace(this.selectedWorkspace);
},
formattedQueryErrors () {
return this.queryErrors.map(err =>
`Time: ${moment(err.time).format('HH:mm:ss.S')} (${err.time})\nError: ${err.message}`
).join('\n\n');
}
},
async created () {
window.addEventListener('keydown', this.onKey);
ipcRenderer.on('import-progress', this.updateProgress);
ipcRenderer.on('query-error', this.handleQueryError);
},
beforeDestroy () {
window.removeEventListener('keydown', this.onKey);
ipcRenderer.off('import-progress', this.updateProgress);
ipcRenderer.off('query-error', this.handleQueryError);
},
methods: {
...mapActions({
addNotification: 'notifications/addNotification',
refreshSchema: 'workspaces/refreshSchema'
}),
async startImport (sqlFile) {
this.isImporting = true;
this.sqlFile = sqlFile;
const { uid, client } = this.currentWorkspace;
const params = {
uid,
type: client,
schema: this.selectedSchema,
file: sqlFile
};
try {
this.completed = false;
const { status, response } = await Schema.import(params);
if (status === 'success')
this.progressStatus = response.cancelled ? this.$t('word.aborted') : this.$t('word.completed');
else {
this.progressStatus = response;
this.addNotification({ status: 'error', message: response });
}
this.refreshSchema({ uid, schema: this.selectedSchema });
this.completed = true;
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
this.isImporting = false;
},
updateProgress (event, state) {
this.progressPercentage = Number(state.percentage).toFixed(1);
this.queryCount = Number(state.queryCount);
},
handleQueryError (event, err) {
this.queryErrors.push(err);
},
async closeModal () {
let willClose = true;
if (this.isImporting) {
willClose = false;
const { response } = await Schema.abortImport();
willClose = response.willAbort;
}
if (willClose)
this.$emit('close');
},
onKey (e) {
e.stopPropagation();
if (e.key === 'Escape')
this.closeModal();
}
}
};
</script>
<style lang="scss" scoped>
.modal {
.modal-container {
max-width: 800px;
}
.modal-body {
max-height: 60vh;
display: flex;
flex-direction: column;
}
.modal-footer {
display: flex;
}
}
.progress-status {
font-style: italic;
font-size: 80%;
}
</style>

View File

@@ -22,12 +22,12 @@
:hide-footer="true"
@hide="hideInfoModal"
>
<template #header>
<template :slot="'header'">
<div class="d-flex">
<i class="mdi mdi-24px mdi-information-outline mr-1" /> {{ $t('message.processInfo') }}
</div>
</template>
<template #body>
<div :slot="'body'">
<div>
<div>
<TextEditor
@@ -38,7 +38,7 @@
/>
</div>
</div>
</template>
</div>
</ConfirmModal>
</div>
</template>

View File

@@ -282,18 +282,12 @@
<div class="text-center">
<img src="../images/logo.svg" width="128">
<h4>{{ appName }}</h4>
<p class="mb-2">
<p>
{{ $t('word.version') }} {{ appVersion }}<br>
<a class="c-hand" @click="openOutside('https://github.com/Fabio286/antares')"><i class="mdi mdi-github d-inline" /> GitHub</a> <a class="c-hand" @click="openOutside('https://twitter.com/AntaresSQL')"><i class="mdi mdi-twitter d-inline" /> Twitter</a> <a class="c-hand" @click="openOutside('https://antares-sql.app/')"><i class="mdi mdi-web d-inline" /> Website</a><br>
<small>{{ $t('word.author') }} <a class="c-hand" @click="openOutside('https://github.com/Fabio286')">{{ appAuthor }}</a></small><br>
</p>
<div class="mb-2">
<small class="d-block text-uppercase">{{ $t('word.contributors') }}:</small>
<div class="d-block py-1">
<small v-for="(contributor, i) in otherContributors" :key="i">{{ i !== 0 ? ', ' : '' }}{{ contributor }}</small>
</div>
<small>{{ $t('word.author') }} <a class="c-hand" @click="openOutside('https://github.com/Fabio286')">Fabio Di Stasio</a></small><br>
<small>{{ $t('message.madeWithJS') }}</small>
</div>
</p>
</div>
</div>
</div>
@@ -319,7 +313,6 @@ export default {
},
data () {
return {
appAuthor: 'Fabio Di Stasio',
localLocale: null,
localPageSize: null,
localTimeout: null,
@@ -374,8 +367,7 @@ export default {
{ code: 'vibrant_ink', name: 'Vibrant Ink' }
]
}
],
contributors: process.env.APP_CONTRIBUTORS
]
};
},
computed: {
@@ -425,12 +417,6 @@ GROUP BY
ORDER BY
employee.id ASC;
`;
},
otherContributors () {
return this.contributors
.split(',')
.filter(c => !c.includes(this.appAuthor))
.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
}
},
created () {

View File

@@ -15,16 +15,16 @@
@confirm="confirmDeleteConnection"
@hide="hideConfirmModal"
>
<template #header>
<template :slot="'header'">
<div class="d-flex">
<i class="mdi mdi-24px mdi-server-remove mr-1" /> {{ $t('message.deleteConnection') }}
</div>
</template>
<template #body>
<div :slot="'body'">
<div class="mb-2">
{{ $t('message.deleteCorfirm') }} <b>{{ connectionName }}</b>?
</div>
</template>
</div>
</ConfirmModal>
</BaseContextMenu>
</template>

View File

@@ -11,9 +11,9 @@
<div class="footer-right-elements">
<ul class="footer-elements">
<li class="footer-element footer-link" @click="openOutside('https://www.paypal.com/paypalme/fabiodistasio')">
<i class="mdi mdi-18px mdi-coffee mr-1" />
<small>{{ $t('word.donate') }}</small>
<li class="footer-element footer-link" @click="openOutside('https://www.treedom.net/en/user/fabio-di-stasio/event/antares-for-the-planet')">
<i class="mdi mdi-18px mdi-tree mr-1" />
<small>{{ $t('message.plantATree') }}</small>
</li>
<li class="footer-element footer-link" @click="openOutside('https://github.com/Fabio286/antares/issues')">
<i class="mdi mdi-18px mdi-bug" />

View File

@@ -6,12 +6,12 @@
:hide-footer="true"
@hide="hideScratchpad"
>
<template #header>
<template :slot="'header'">
<div class="d-flex">
<i class="mdi mdi-24px mdi-notebook-edit-outline mr-1" /> {{ $t('word.scratchpad') }}
</div>
</template>
<template #body>
<div :slot="'body'">
<div>
<div>
<TextEditor
@@ -24,7 +24,7 @@
</div>
<small class="text-gray">{{ $t('message.markdownSupported') }}</small>
</div>
</template>
</div>
</ConfirmModal>
</template>

View File

@@ -200,7 +200,7 @@ export default {
}
&::before {
content: "";
content: '';
height: 0;
width: 3px;
transition: height 0.2s;

View File

@@ -18,17 +18,14 @@
<li
v-for="(tab, i) of draggableTabs"
:key="i"
:ref="selectedTab === tab.uid ? 'tab-selected' : ''"
class="tab-item tab-draggable"
draggable="true"
:class="{'active': selectedTab === tab.uid}"
@mousedown.left="selectTab({uid: workspace.uid, tab: tab.uid})"
@mouseup.middle="closeTab(tab)"
>
<a
v-if="tab.type === 'query'"
class="tab-link"
:class="{'badge': tab.isChanged}"
>
<a v-if="tab.type === 'query'" class="tab-link">
<i class="mdi mdi-18px mdi-code-tags mr-1" />
<span>
<span>{{ tab.content || 'Query' | cutText }} #{{ tab.index }}</span>
@@ -259,59 +256,56 @@
</span>
</a>
</li>
<template #header>
<li
v-if="workspace.customizations.processesList"
class="tab-item dropdown tools-dropdown"
<li
v-if="workspace.customizations.processesList"
slot="header"
class="tab-item dropdown tools-dropdown"
>
<a
class="tab-link workspace-tools-link dropdown-toggle"
tabindex="0"
:title="$t('word.tools')"
>
<a
class="tab-link workspace-tools-link dropdown-toggle"
tabindex="0"
:title="$t('word.tools')"
<i class="mdi mdi-24px mdi-tools" />
</a>
<ul v-if="hasTools" class="menu text-left text-uppercase">
<li class="menu-item">
<a class="c-hand p-vcentered" @click="showProcessesModal">
<i class="mdi mdi-memory mr-1 tool-icon" />
<span>{{ $t('message.processesList') }}</span>
</a>
</li>
<li
v-if="workspace.customizations.variables"
class="menu-item"
title="Coming..."
>
<i class="mdi mdi-24px mdi-tools" />
</a>
<ul v-if="hasTools" class="menu text-left text-uppercase">
<li class="menu-item">
<a class="c-hand p-vcentered" @click="showProcessesModal">
<i class="mdi mdi-memory mr-1 tool-icon" />
<span>{{ $t('message.processesList') }}</span>
</a>
</li>
<li
v-if="workspace.customizations.variables"
class="menu-item"
title="Coming..."
>
<a class="c-hand p-vcentered disabled">
<i class="mdi mdi-shape mr-1 tool-icon" />
<span>{{ $t('word.variables') }}</span>
</a>
</li>
<li
v-if="workspace.customizations.usersManagement"
class="menu-item"
title="Coming..."
>
<a class="c-hand p-vcentered disabled">
<i class="mdi mdi-account-group mr-1 tool-icon" />
<span>{{ $t('message.manageUsers') }}</span>
</a>
</li>
</ul>
</li>
</template>
<template #footer>
<li class="tab-item">
<a
class="tab-add"
:title="$t('message.openNewTab')"
@click="addQueryTab"
<a class="c-hand p-vcentered disabled">
<i class="mdi mdi-shape mr-1 tool-icon" />
<span>{{ $t('word.variables') }}</span>
</a>
</li>
<li
v-if="workspace.customizations.usersManagement"
class="menu-item"
title="Coming..."
>
<i class="mdi mdi-24px mdi-plus" />
</a>
</li>
</template>
<a class="c-hand p-vcentered disabled">
<i class="mdi mdi-account-group mr-1 tool-icon" />
<span>{{ $t('message.manageUsers') }}</span>
</a>
</li>
</ul>
</li>
<li slot="footer" class="tab-item">
<a
class="tab-add"
:title="$t('message.openNewTab')"
@click="addQueryTab"
>
<i class="mdi mdi-24px mdi-plus" />
</a>
</li>
</Draggable>
<WorkspaceEmptyState v-if="!workspace.tabs.length" @new-tab="addQueryTab" />
<template v-for="tab of workspace.tabs">
@@ -571,7 +565,7 @@ export default {
return this.workspace ? this.workspace.selectedTab : null;
},
queryTabs () {
return this.workspace ? this.workspace.tabs.filter(tab => tab.type === 'query') : [];
return this.workspace.tabs.filter(tab => tab.type === 'query');
},
schemaChild () {
for (const key in this.workspace.breadcrumbs) {
@@ -587,12 +581,16 @@ export default {
}
},
watch: {
queryTabs: function (newVal, oldVal) {
if (newVal.length > oldVal.length) {
selectedTab (newVal, oldVal) {
if (newVal !== oldVal) {
setTimeout(() => {
const scroller = this.$refs.tabWrap;
if (scroller) scroller.$el.scrollLeft = scroller.$el.scrollWidth;
}, 0);
const element = this.$refs['tab-selected'] ? this.$refs['tab-selected'][0] : null;
if (element) {
element.setAttribute('tabindex', '-1');
element.focus();
element.removeAttribute('tabindex');
}
}, 50);
}
}
},

View File

@@ -61,19 +61,6 @@
</select>
</div>
</div>
<div v-if="connection.client === 'pg'" class="form-group columns">
<div class="column col-4 col-sm-12">
<label class="form-label">{{ $t('word.connectionString') }}</label>
</div>
<div class="column col-8 col-sm-12">
<input
ref="pgString"
v-model="connection.pgConnString"
class="form-input"
type="text"
>
</div>
</div>
<div v-if="!customizations.fileConnection" class="form-group columns">
<div class="column col-4 col-sm-12">
<label class="form-label">{{ $t('word.hostName') }}/IP</label>
@@ -425,8 +412,7 @@ export default {
sshUser: '',
sshPass: '',
sshKey: '',
sshPort: 22,
pgConnString: ''
sshPort: 22
},
isConnecting: false,
isTesting: false,

View File

@@ -61,19 +61,6 @@
</select>
</div>
</div>
<div v-if="connection.client === 'pg'" class="form-group columns">
<div class="column col-4 col-sm-12">
<label class="form-label">{{ $t('word.connectionString') }}</label>
</div>
<div class="column col-8 col-sm-12">
<input
ref="pgString"
v-model="localConnection.pgConnString"
class="form-input"
type="text"
>
</div>
</div>
<div v-if="!customizations.fileConnection" class="form-group columns">
<div class="column col-4 col-sm-12">
<label class="form-label">{{ $t('word.hostName') }}/IP</label>

View File

@@ -42,17 +42,17 @@
@confirm="deleteMisc"
@hide="hideDeleteModal"
>
<template #header>
<template slot="header">
<div class="d-flex">
<i class="mdi mdi-24px mdi-delete mr-1" />
<span class="cut-text">{{ deleteMessage }}</span>
</div>
</template>
<template #body>
<div slot="body">
<div class="mb-2">
{{ $t('message.deleteCorfirm') }} "<b>{{ selectedMisc.name }}</b>"?
</div>
</template>
</div>
</ConfirmModal>
<ModalAskParameters
v-if="isAskingParameters"

View File

@@ -452,9 +452,9 @@ export default {
top: 0;
z-index: 2;
.schema-size {
visibility: hidden;
width: 22.5px;
.schema-size{
visibility: hidden;
width: 22.5px;
}
}
@@ -502,8 +502,8 @@ export default {
&:hover {
border-radius: $border-radius;
.schema-size {
visibility: visible;
.schema-size{
visibility: visible;
}
}
}

View File

@@ -58,20 +58,6 @@
</div>
</div>
</div>
<div
v-if="workspace.customizations.schemaExport"
class="context-element"
@click="showExportSchemaModal"
>
<span class="d-flex"><i class="mdi mdi-18px mdi-database-arrow-down text-light pr-1" /> {{ $t('word.export') }}</span>
</div>
<div
v-if="workspace.customizations.schemaImport"
class="context-element"
@click="initImport"
>
<span class="d-flex"><i class="mdi mdi-18px mdi-database-arrow-up text-light pr-1" /> {{ $t('word.import') }}</span>
</div>
<div
v-if="workspace.customizations.schemaEdit"
class="context-element"
@@ -92,34 +78,23 @@
@confirm="deleteSchema"
@hide="hideDeleteModal"
>
<template #header>
<template slot="header">
<div class="d-flex">
<i class="mdi mdi-24px mdi-database-remove mr-1" />
<span class="cut-text">{{ $t('message.deleteSchema') }}</span>
</div>
</template>
<template #body>
<div slot="body">
<div class="mb-2">
{{ $t('message.deleteCorfirm') }} "<b>{{ selectedSchema }}</b>"?
</div>
</template>
</div>
</ConfirmModal>
<ModalEditSchema
v-if="isEditModal"
:selected-schema="selectedSchema"
@close="hideEditModal"
/>
<ModalExportSchema
v-if="isExportSchemaModal"
:selected-schema="selectedSchema"
@close="hideExportSchemaModal"
/>
<ModalImportSchema
v-if="isImportSchemaModal"
ref="importModalRef"
:selected-schema="selectedSchema"
@close="hideImportSchemaModal"
/>
</BaseContextMenu>
</template>
@@ -128,19 +103,14 @@ import { mapGetters, mapActions } from 'vuex';
import BaseContextMenu from '@/components/BaseContextMenu';
import ConfirmModal from '@/components/BaseConfirmModal';
import ModalEditSchema from '@/components/ModalEditSchema';
import ModalExportSchema from '@/components/ModalExportSchema';
import ModalImportSchema from '@/components/ModalImportSchema';
import Schema from '@/ipc-api/Schema';
import Application from '@/ipc-api/Application';
export default {
name: 'WorkspaceExploreBarSchemaContext',
components: {
BaseContextMenu,
ConfirmModal,
ModalEditSchema,
ModalExportSchema,
ModalImportSchema
ModalEditSchema
},
props: {
contextEvent: MouseEvent,
@@ -149,9 +119,7 @@ export default {
data () {
return {
isDeleteModal: false,
isEditModal: false,
isExportSchemaModal: false,
isImportSchemaModal: false
isEditModal: false
};
},
computed: {
@@ -202,30 +170,6 @@ export default {
this.isEditModal = false;
this.closeContext();
},
showExportSchemaModal () {
this.isExportSchemaModal = true;
},
hideExportSchemaModal () {
this.isExportSchemaModal = false;
this.closeContext();
},
showImportSchemaModal () {
this.isImportSchemaModal = true;
},
hideImportSchemaModal () {
this.isImportSchemaModal = false;
this.closeContext();
},
async initImport () {
const result = await Application.showOpenDialog({ properties: ['openFile'], filters: [{ name: 'SQL', extensions: ['sql'] }] });
if (result && !result.canceled) {
const file = result.filePaths[0];
this.showImportSchemaModal();
this.$nextTick(() => {
this.$refs.importModalRef.startImport(file);
});
}
},
closeContext () {
this.$emit('close-context');
},

View File

@@ -40,33 +40,33 @@
@confirm="emptyTable"
@hide="hideEmptyModal"
>
<template #header>
<template slot="header">
<div class="d-flex">
<i class="mdi mdi-24px mdi-table-off mr-1" /> <span class="cut-text">{{ $t('message.emptyTable') }}</span>
</div>
</template>
<template #body>
<div slot="body">
<div class="mb-2">
{{ $t('message.emptyCorfirm') }} "<b>{{ selectedTable.name }}</b>"?
</div>
</template>
</div>
</ConfirmModal>
<ConfirmModal
v-if="isDeleteModal"
@confirm="deleteTable"
@hide="hideDeleteModal"
>
<template #header>
<template slot="header">
<div class="d-flex">
<i class="mdi mdi-24px mdi-table-remove mr-1" />
<span class="cut-text">{{ selectedTable.type === 'table' ? $t('message.deleteTable') : $t('message.deleteView') }}</span>
</div>
</template>
<template #body>
<div slot="body">
<div class="mb-2">
{{ $t('message.deleteCorfirm') }} "<b>{{ selectedTable.name }}</b>"?
</div>
</template>
</div>
</ConfirmModal>
</BaseContextMenu>
</template>

View File

@@ -5,7 +5,7 @@
<div class="workspace-query-buttons">
<button
class="btn btn-primary btn-sm"
:disabled="!isChanged || !isValid"
:disabled="!isChanged"
:class="{'loading':isSaving}"
title="CTRL+S"
@click="saveChanges"
@@ -242,9 +242,6 @@ export default {
JSON.stringify(this.originalKeyUsage) !== JSON.stringify(this.localKeyUsage) ||
JSON.stringify(this.originalIndexes) !== JSON.stringify(this.localIndexes) ||
JSON.stringify(this.tableOptions) !== JSON.stringify(this.localOptions);
},
isValid () {
return !!this.localFields.length && !!this.localOptions.name.trim().length;
}
},
watch: {
@@ -290,7 +287,7 @@ export default {
changeBreadcrumbs: 'workspaces/changeBreadcrumbs'
}),
async saveChanges () {
if (this.isSaving || !this.isValid) return;
if (this.isSaving) return;
this.isSaving = true;
const params = {

View File

@@ -6,13 +6,13 @@
@confirm="confirmParametersChange"
@hide="$emit('hide')"
>
<template #header>
<template :slot="'header'">
<div class="d-flex">
<i class="mdi mdi-24px mdi-dots-horizontal mr-1" />
<span class="cut-text">{{ $t('word.parameters') }} "{{ func }}"</span>
</div>
</template>
<template #body>
<div :slot="'body'">
<div class="columns col-gapless">
<div class="column col-5">
<div class="panel" :style="{ height: modalInnerHeight + 'px'}">
@@ -167,7 +167,7 @@
</div>
</div>
</div>
</template>
</div>
</ConfirmModal>
</template>

View File

@@ -6,13 +6,13 @@
@confirm="confirmParametersChange"
@hide="$emit('hide')"
>
<template #header>
<template :slot="'header'">
<div class="d-flex">
<i class="mdi mdi-24px mdi-dots-horizontal mr-1" />
<span class="cut-text">{{ $t('word.parameters') }} "{{ routine }}"</span>
</div>
</template>
<template #body>
<div :slot="'body'">
<div class="columns col-gapless">
<div class="column col-5">
<div class="panel" :style="{ height: modalInnerHeight + 'px'}">
@@ -167,7 +167,7 @@
</div>
</div>
</div>
</template>
</div>
</ConfirmModal>
</template>

View File

@@ -5,13 +5,13 @@
@confirm="confirmOptionsChange"
@hide="$emit('hide')"
>
<template #header>
<template :slot="'header'">
<div class="d-flex">
<i class="mdi mdi-24px mdi-timer mr-1" />
<span class="cut-text">{{ $t('word.timing') }} "{{ localOptions.name }}"</span>
</div>
</template>
<template #body>
<div :slot="'body'">
<form class="form-horizontal">
<div class="form-group">
<label class="form-label col-4">
@@ -133,7 +133,7 @@
</div>
</div>
</form>
</template>
</div>
</ConfirmModal>
</template>

View File

@@ -616,14 +616,6 @@ export default {
},
removeField (uid) {
this.localFields = this.localFields.filter(field => field._antares_id !== uid);
this.localKeyUsage = this.localKeyUsage.filter(fk =>// Clear foreign keys
this.localFields.some(field => field.name === fk.field)
);
this.localIndexes = this.localIndexes.filter(index =>// Clear indexes
this.localFields.some(field =>
index.fields.includes(field.name)
)
);
},
addNewIndex (payload) {
this.localIndexes = [...this.localIndexes, {

View File

@@ -6,13 +6,13 @@
@confirm="confirmForeignsChange"
@hide="$emit('hide')"
>
<template #header>
<template :slot="'header'">
<div class="d-flex">
<i class="mdi mdi-24px mdi-key-link mr-1" />
<span class="cut-text">{{ $t('word.foreignKeys') }} "{{ table }}"</span>
</div>
</template>
<template #body>
<div :slot="'body'">
<div class="columns col-gapless">
<div class="column col-5">
<div class="panel" :style="{ height: modalInnerHeight + 'px'}">
@@ -197,7 +197,7 @@
</div>
</div>
</div>
</template>
</div>
</ConfirmModal>
</template>
@@ -289,7 +289,7 @@ export default {
addForeign () {
this.foreignProxy = [...this.foreignProxy, {
_antares_id: uidGen(),
constraintName: `FK_${uidGen()}`,
constraintName: `FK_${this.foreignProxy.length + 1}`,
refSchema: this.schema,
table: this.table,
refTable: '',

View File

@@ -6,13 +6,13 @@
@confirm="confirmIndexesChange"
@hide="$emit('hide')"
>
<template #header>
<template :slot="'header'">
<div class="d-flex">
<i class="mdi mdi-24px mdi-key mdi-rotate-45 mr-1" />
<span class="cut-text">{{ $t('word.indexes') }} "{{ table }}"</span>
</div>
</template>
<template #body>
<div :slot="'body'">
<div class="columns col-gapless">
<div class="column col-5">
<div class="panel" :style="{ height: modalInnerHeight + 'px'}">
@@ -133,7 +133,7 @@
</div>
</div>
</div>
</template>
</div>
</ConfirmModal>
</template>

View File

@@ -99,9 +99,6 @@
<span v-if="localRow.enumValues">
{{ localRow.enumValues }}
</span>
<span v-else-if="localRow.numScale">
{{ localLength }}, {{ localRow.numScale }}
</span>
<span v-else>
{{ localLength }}
</span>
@@ -115,16 +112,6 @@
class="editable-field form-input input-sm px-1"
@blur="editOFF"
>
<input
v-else-if="fieldType.scale"
ref="editField"
v-model="editingContent"
type="text"
autofocus
class="editable-field form-input input-sm px-1"
@keypress="checkLengthScale"
@blur="editOFF"
>
<input
v-else
ref="editField"
@@ -243,13 +230,13 @@
@confirm="editOFF"
@hide="hideDefaultModal"
>
<template #header>
<template :slot="'header'">
<div class="d-flex">
<i class="mdi mdi-24px mdi-playlist-edit mr-1" />
<span class="cut-text">{{ $t('word.default') }} "{{ row.name }}"</span>
</div>
</template>
<template #body>
<div :slot="'body'">
<form class="form-horizontal">
<div class="mb-2">
<label class="form-radio form-inline">
@@ -337,7 +324,7 @@
</div>
</div>
</form>
</template>
</div>
</ConfirmModal>
</div>
</template>
@@ -493,11 +480,6 @@ export default {
this.editingContent = this.localRow.enumValues;
this.originalContent = this.localRow.enumValues;
}
else if (this.fieldType.scale && field === 'length') {
const scale = this.localRow.numScale !== null ? this.localRow.numScale : 0;
this.editingContent = `${content}, ${scale}`;
this.originalContent = `${content}, ${scale}`;
}
else {
this.editingContent = content;
this.originalContent = content;
@@ -520,17 +502,10 @@ export default {
if (this.editingField === 'name')
this.$emit('rename-field', { old: this.localRow[this.editingField], new: this.editingContent });
if (this.editingField === 'numLength' && this.fieldType.scale) {
const [length, scale] = this.editingContent.split(',');
this.localRow.numLength = +length;
this.localRow.numScale = scale ? +scale : null;
}
else
this.localRow[this.editingField] = this.editingContent;
this.localRow[this.editingField] = this.editingContent;
if (this.editingField === 'type' && this.editingContent !== this.originalContent) {
this.localRow.numLength = null;
this.localRow.numScale = null;
this.localRow.charLength = null;
this.localRow.datePrecision = null;
this.localRow.enumValues = '';
@@ -585,15 +560,6 @@ export default {
this.originalContent = null;
this.editingField = null;
},
checkLengthScale (e) {
e = (e) || window.event;
const charCode = (e.which) ? e.which : e.keyCode;
if (((charCode > 31 && (charCode < 48 || charCode > 57)) && charCode !== 44) || (charCode === 44 && e.target.value.includes(',')))
e.preventDefault();
else
return true;
},
hideDefaultModal () {
this.isDefaultModal = false;
}

View File

@@ -4,7 +4,6 @@
class="workspace-query-tab column col-12 columns col-gapless no-outline p-0"
tabindex="0"
@keydown.116="runQuery(query)"
@keydown.75="killTabQuery"
@keydown.ctrl.alt.87="clear"
@keydown.ctrl.66="beautify"
@keydown.ctrl.71="openHistoryModal"
@@ -23,46 +22,15 @@
<div ref="resizer" class="query-area-resizer" />
<div class="workspace-query-runner-footer">
<div class="workspace-query-buttons">
<div @mouseenter="setCancelButtonVisibility(true)" @mouseleave="setCancelButtonVisibility(false)">
<button
v-if="showCancel && isQuering"
class="btn btn-primary btn-sm cancellable"
:disabled="!query"
:title="$t('word.cancel')"
@click="killTabQuery()"
>
<i class="mdi mdi-24px mdi-window-close" />
<span class="d-invisible pr-1">{{ $t('word.run') }}</span>
</button>
<button
v-else
class="btn btn-primary btn-sm"
:class="{'loading':isQuering}"
:disabled="!query"
title="F5"
@click="runQuery(query)"
>
<i class="mdi mdi-24px mdi-play pr-1" />
<span>{{ $t('word.run') }}</span>
</button>
</div>
<button
v-if="!autocommit"
class="btn btn-dark btn-sm"
class="btn btn-primary btn-sm"
:class="{'loading':isQuering}"
@click="commitTab()"
:disabled="!query"
title="F5"
@click="runQuery(query)"
>
<i class="mdi mdi-24px mdi-cube-send pr-1" />
<span>{{ $t('word.commit') }}</span>
</button>
<button
v-if="!autocommit"
class="btn btn-dark btn-sm"
:class="{'loading':isQuering}"
@click="rollbackTab()"
>
<i class="mdi mdi-24px mdi-undo-variant pr-1" />
<span>{{ $t('word.rollback') }}</span>
<i class="mdi mdi-24px mdi-play pr-1" />
<span>{{ $t('word.run') }}</span>
</button>
<button
class="btn btn-link btn-sm mr-0"
@@ -96,7 +64,7 @@
</button>
<div class="dropdown table-dropdown pr-2">
<button
:disabled="!hasResults || isQuering"
:disabled="!results.length || isQuering"
class="btn btn-dark btn-sm dropdown-toggle mr-0 pr-0"
tabindex="0"
>
@@ -113,17 +81,6 @@
</li>
</ul>
</div>
<div class="input-group pr-2" :title="$t('message.commitMode')">
<i class="input-group-addon addon-sm mdi mdi-24px mdi-source-commit p-0" />
<select v-model="autocommit" class="form-select select-sm text-bold">
<option :value="true">
{{ $t('message.autoCommit') }}
</option>
<option :value="false">
{{ $t('message.manualCommit') }}
</option>
</select>
</div>
</div>
<div class="workspace-query-info">
<div
@@ -133,19 +90,11 @@
>
<i class="mdi mdi-timer-sand mdi-rotate-180 pr-1" /> <b>{{ durationsCount / 1000 }}s</b>
</div>
<div
v-if="resultsCount"
class="d-flex"
:title="$t('word.results')"
>
<i class="mdi mdi-equal pr-1" /> <b>{{ resultsCount.toLocaleString() }}</b>
<div v-if="resultsCount">
{{ $t('word.results') }}: <b>{{ resultsCount.toLocaleString() }}</b>
</div>
<div
v-if="hasAffected"
class="d-flex"
:title="$t('message.affectedRows')"
>
<i class="mdi mdi-target pr-1" /> <b>{{ affectedCount }}</b>
<div v-if="affectedCount !== null">
{{ $t('message.affectedRows') }}: <b>{{ affectedCount }}</b>
</div>
<div class="input-group" :title="$t('word.schema')">
<i class="input-group-addon addon-sm mdi mdi-24px mdi-database" />
@@ -161,7 +110,7 @@
</div>
</div>
</div>
<WorkspaceTabQueryEmptyState v-if="!results.length && !isQuering" :customizations="workspace.customizations" />
<WorkspaceTabQueryEmptyState v-if="!results.length && !isQuering" />
<div class="workspace-query-results p-relative column col-12">
<BaseLoader v-if="isQuering" />
<WorkspaceTabQueryTable
@@ -217,9 +166,6 @@ export default {
query: '',
lastQuery: '',
isQuering: false,
isCancelling: false,
showCancel: false,
autocommit: true,
results: [],
selectedSchema: null,
resultsCount: 0,
@@ -238,9 +184,6 @@ export default {
workspace () {
return this.getWorkspace(this.connection.uid);
},
tabUid () {
return this.$vnode.key;
},
breadcrumbsSchema () {
return this.workspace.breadcrumbs.schema || null;
},
@@ -255,23 +198,12 @@ export default {
},
history () {
return this.getHistoryByWorkspace(this.connection.uid) || [];
},
hasResults () {
return this.results.length && this.results[0].rows;
},
hasAffected () {
return this.affectedCount || (!this.resultsCount && this.affectedCount !== null);
}
},
watch: {
isSelected (val) {
if (val) {
if (val)
this.changeBreadcrumbs({ schema: this.selectedSchema, query: `Query #${this.tab.index}` });
setTimeout(() => {
if (this.$refs.queryEditor)
this.$refs.queryEditor.editor.focus();
}, 0);
}
},
selectedSchema () {
this.changeBreadcrumbs({ schema: this.selectedSchema, query: `Query #${this.tab.index}` });
@@ -298,18 +230,12 @@ export default {
},
beforeDestroy () {
window.removeEventListener('keydown', this.onKey);
const params = {
uid: this.connection.uid,
tabUid: this.tab.uid
};
Schema.destroyConnectionToCommit(params);
},
methods: {
...mapActions({
addNotification: 'notifications/addNotification',
changeBreadcrumbs: 'workspaces/changeBreadcrumbs',
updateTabContent: 'workspaces/updateTabContent',
setUnsavedChanges: 'workspaces/setUnsavedChanges',
saveHistory: 'history/saveHistory'
}),
async runQuery (query) {
@@ -322,8 +248,6 @@ export default {
const params = {
uid: this.connection.uid,
schema: this.selectedSchema,
tabUid: this.tab.uid,
autocommit: this.autocommit,
query
};
@@ -348,8 +272,6 @@ export default {
content: query
});
this.saveHistory(params);
if (!this.autocommit)
this.setUnsavedChanges({ uid: this.connection.uid, tUid: this.tabUid, isChanged: true });
}
else
this.addNotification({ status: 'error', message: response });
@@ -361,29 +283,6 @@ export default {
this.isQuering = false;
this.lastQuery = query;
},
async killTabQuery () {
if (this.isCancelling) return;
this.isCancelling = true;
try {
const params = {
uid: this.connection.uid,
tabUid: this.tab.uid
};
await Schema.killTabQuery(params);
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
this.isCancelling = false;
},
setCancelButtonVisibility (val) {
if (this.workspace.customizations.cancelQueries)
this.showCancel = val;
},
reloadTable () {
this.runQuery(this.lastQuery);
},
@@ -447,42 +346,6 @@ export default {
},
downloadTable (format) {
this.$refs.queryTable.downloadTable(format, `${this.tab.type}-${this.tab.index}`);
},
async commitTab () {
this.isQuering = true;
try {
const params = {
uid: this.connection.uid,
tabUid: this.tab.uid
};
await Schema.commitTab(params);
this.setUnsavedChanges({ uid: this.connection.uid, tUid: this.tabUid, isChanged: false });
this.addNotification({ status: 'success', message: this.$t('message.actionSuccessful', { action: 'COMMIT' }) });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
this.isQuering = false;
},
async rollbackTab () {
this.isQuering = true;
try {
const params = {
uid: this.connection.uid,
tabUid: this.tab.uid
};
await Schema.rollbackTab(params);
this.setUnsavedChanges({ uid: this.connection.uid, tUid: this.tabUid, isChanged: false });
this.addNotification({ status: 'success', message: this.$t('message.actionSuccessful', { action: 'ROLLBACK' }) });
}
catch (err) {
this.addNotification({ status: 'error', message: err.stack });
}
this.isQuering = false;
}
}
};
@@ -511,12 +374,10 @@ export default {
.workspace-query-runner-footer {
display: flex;
flex-wrap: wrap;
row-gap: 0.4rem;
justify-content: space-between;
padding: 0.3rem 0.6rem 0.4rem;
align-items: center;
min-height: 42px;
height: 42px;
.workspace-query-buttons,
.workspace-query-info {

View File

@@ -5,9 +5,6 @@
<div class="mb-4">
{{ $t('message.runQuery') }}
</div>
<div v-if="customizations.cancelQueries" class="mb-4">
{{ $t('message.killQuery') }}
</div>
<div class="mb-4">
{{ $t('word.format') }}
</div>
@@ -28,9 +25,6 @@
<div class="mb-4">
<code>F5</code>
</div>
<div v-if="customizations.cancelQueries" class="mb-4">
<code>CTRL</code> + <code>K</code>
</div>
<div class="mb-4">
<code>CTRL</code> + <code>B</code>
</div>
@@ -53,10 +47,7 @@
<script>
export default {
name: 'WorkspaceTabQueryEmptyState',
props: {
customizations: Object
}
name: 'WorkspaceTabQueryEmptyState'
};
</script>

View File

@@ -5,7 +5,7 @@
tabindex="0"
:style="{'height': resultsSize+'px'}"
@keyup.46="showDeleteConfirmModal"
@keydown.ctrl.65="selectAllRows($event)"
@keydown.ctrl.65="selectAllRows"
@keydown.esc="deselectRows"
>
<TableContext
@@ -53,7 +53,6 @@
class="mdi sort-icon"
:class="currentSortDir === 'asc' ? 'mdi-sort-ascending':'mdi-sort-descending'"
/>
<i v-else class="mdi sort-icon mdi-minus d-invisible" />
</div>
</div>
</div>
@@ -63,7 +62,7 @@
v-if="resultsWithRows[resultsetIndex] && resultsWithRows[resultsetIndex].rows"
ref="resultTable"
:items="sortedResults"
:item-height="rowHeight"
:item-height="23"
class="tbody"
:visible-height="resultsSize"
:scroll-element="scrollElement"
@@ -72,7 +71,6 @@
<WorkspaceTabQueryTableRow
v-for="row in items"
:key="row._antares_id"
:item-height="rowHeight"
:row="row"
:fields="fieldsObj"
:key-usage="keyUsage"
@@ -91,17 +89,17 @@
@confirm="deleteSelected"
@hide="hideDeleteConfirmModal"
>
<template #header>
<template :slot="'header'">
<div class="d-flex">
<i class="mdi mdi-24px mdi-delete mr-1" />
<span class="cut-text">{{ $tc('message.deleteRows', selectedRows.length) }}</span>
</div>
</template>
<template #body>
<div :slot="'body'">
<div class="mb-2">
{{ $tc('message.confirmToDeleteRows', selectedRows.length) }}
</div>
</template>
</div>
</ConfirmModal>
</div>
</template>
@@ -144,8 +142,7 @@ export default {
currentSort: '',
currentSortDir: 'asc',
resultsetIndex: 0,
scrollElement: null,
rowHeight: 23
scrollElement: null
};
},
computed: {
@@ -175,10 +172,8 @@ export default {
if (this.currentSort && !this.isHardSort) {
return [...this.localResults].sort((a, b) => {
let modifier = 1;
let valA = typeof a[this.currentSort] === 'string' ? a[this.currentSort].toLowerCase() : a[this.currentSort];
if (!isNaN(valA)) valA = Number(valA);
let valB = typeof b[this.currentSort] === 'string' ? b[this.currentSort].toLowerCase() : b[this.currentSort];
if (!isNaN(valB)) valB = Number(valB);
const valA = typeof a[this.currentSort] === 'string' ? a[this.currentSort].toLowerCase() : a[this.currentSort];
const valB = typeof b[this.currentSort] === 'string' ? b[this.currentSort].toLowerCase() : b[this.currentSort];
if (this.currentSortDir === 'desc') modifier = -1;
if (valA < valB) return -1 * modifier;
if (valA > valB) return 1 * modifier;
@@ -247,11 +242,6 @@ export default {
if (this.$refs.tableWrapper)
this.scrollElement = this.$refs.tableWrapper;
document.querySelectorAll('.column-resizable').forEach(element => {
if (element.clientWidth !== 0)
element.style.width = element.clientWidth + 'px';
});
},
mounted () {
window.addEventListener('resize', this.resizeResults);
@@ -282,7 +272,6 @@ export default {
fieldLength (field) {
if ([...BLOB, ...LONG_TEXT].includes(field.type)) return null;
else if (TEXT.includes(field.type)) return field.charLength;
else if (field.numScale) return `${field.numPrecision}, ${field.numScale}`;
return field.length;
},
keyName (key) {
@@ -410,13 +399,10 @@ export default {
const row = this.localResults.find(row => this.selectedRows.includes(row._antares_id));
const cellName = Object.keys(row).find(prop => [
this.selectedCell.field,
this.selectedCell.orgField,
`${this.fields[0].table}.${this.selectedCell.field}`,
`${this.fields[0].tableAlias}.${this.selectedCell.field}`
].includes(prop));
let valueToCopy = row[cellName];
if (typeof valueToCopy === 'object')
valueToCopy = JSON.stringify(valueToCopy);
const valueToCopy = row[cellName];
navigator.clipboard.writeText(valueToCopy);
},
copyRow () {
@@ -464,9 +450,7 @@ export default {
else
this.selectedRows = [row];
},
selectAllRows (e) {
if (e.target.classList.contains('editable-field')) return;
selectAllRows () {
this.selectedRows = this.localResults.reduce((acc, curr) => {
acc.push(curr._antares_id);
return acc;

View File

@@ -61,6 +61,8 @@ export default {
selectedRows: Array,
selectedCell: Object
},
computed: {
},
methods: {
showConfirmModal () {
this.$emit('show-delete-modal');

View File

@@ -1,16 +1,12 @@
<template>
<div
class="tr"
:style="{height: itemHeight+'px'}"
@click="selectRow($event, row._antares_id)"
>
<div class="tr" @click="selectRow($event, row._antares_id)">
<div
v-for="(col, cKey) in row"
v-show="cKey !== '_antares_id'"
:key="cKey"
class="td p-0"
tabindex="0"
@contextmenu.prevent="openContext($event, { id: row._antares_id, orgField: cKey })"
@contextmenu.prevent="openContext($event, { id: row._antares_id, field: cKey })"
>
<template v-if="cKey !== '_antares_id'">
<span
@@ -76,12 +72,12 @@
@confirm="editOFF"
@hide="hideEditorModal"
>
<template #header>
<template :slot="'header'">
<div class="d-flex">
<i class="mdi mdi-24px mdi-playlist-edit mr-1" /> <span class="cut-text">{{ $t('word.edit') }} "{{ editingField }}"</span>
</div>
</template>
<template #body>
<div :slot="'body'">
<div class="mb-2">
<div>
<TextEditor
@@ -100,12 +96,23 @@
v-model="editorMode"
class="form-select select-sm"
>
<option
v-for="language in availableLanguages"
:key="language.slug"
:value="language.slug"
>
{{ language.name }}
<option value="text">
TEXT
</option>
<option value="html">
HTML
</option>
<option value="xml">
XML
</option>
<option value="json">
JSON
</option>
<option value="svg">
SVG
</option>
<option value="yaml">
YAML
</option>
</select>
</div>
@@ -121,22 +128,7 @@
</div>
</div>
</div>
</template>
</ConfirmModal>
<ConfirmModal
v-if="isMapModal"
:hide-footer="true"
size="medium"
@hide="hideEditorModal"
>
<template #header>
<div class="d-flex">
<i class="mdi mdi-24px mdi-map mr-1" /> <span class="cut-text">"{{ editingField }}"</span>
</div>
</template>
<template #body>
<BaseMap :points="editingContent" :is-multi-spatial="isMultiSpatial" />
</template>
</div>
</ConfirmModal>
<ConfirmModal
v-if="isBlobEditor"
@@ -144,13 +136,13 @@
@confirm="editOFF"
@hide="hideEditorModal"
>
<template #header>
<template :slot="'header'">
<div class="d-flex">
<i class="mdi mdi-24px mdi-playlist-edit mr-1" />
<span class="cut-text">{{ $t('word.edit') }} "{{ editingField }}"</span>
</div>
</template>
<template #body>
<div :slot="'body'">
<div class="mb-2">
<transition name="jump-down">
<div v-if="contentInfo.size">
@@ -190,39 +182,21 @@
>
</div>
</div>
</template>
</div>
</ConfirmModal>
</div>
</template>
<script>
import moment from 'moment';
import { ModelOperations } from '@vscode/vscode-languagedetection';
import { mimeFromHex } from 'common/libs/mimeFromHex';
import { formatBytes } from 'common/libs/formatBytes';
import { bufferToBase64 } from 'common/libs/bufferToBase64';
import hexToBinary from 'common/libs/hexToBinary';
import {
TEXT,
LONG_TEXT,
ARRAY,
TEXT_SEARCH,
NUMBER,
FLOAT,
BOOLEAN,
DATE,
TIME,
DATETIME,
BLOB,
BIT,
HAS_TIMEZONE,
SPATIAL,
IS_MULTI_SPATIAL
} from 'common/fieldTypes';
import { TEXT, LONG_TEXT, ARRAY, TEXT_SEARCH, NUMBER, FLOAT, BOOLEAN, DATE, TIME, DATETIME, BLOB, BIT, HAS_TIMEZONE } from 'common/fieldTypes';
import { VueMaskDirective } from 'v-mask';
import ConfirmModal from '@/components/BaseConfirmModal';
import TextEditor from '@/components/BaseTextEditor';
import BaseMap from '@/components/BaseMap';
import ForeignKeySelect from '@/components/ForeignKeySelect';
export default {
@@ -230,8 +204,7 @@ export default {
components: {
ConfirmModal,
TextEditor,
ForeignKeySelect,
BaseMap
ForeignKeySelect
},
directives: {
mask: VueMaskDirective
@@ -272,8 +245,7 @@ export default {
if (BIT.includes(type)) {
if (typeof val === 'number') val = [val];
const hex = Buffer.from(val).toString('hex');
const bitString = hexToBinary(hex);
return parseInt(bitString).toString().padStart(precision, '0');
return hexToBinary(hex);
}
if (ARRAY.includes(type)) {
@@ -282,17 +254,13 @@ export default {
return val;
}
if (SPATIAL.includes(type))
return val;
return typeof val === 'object' ? JSON.stringify(val) : val;
return val;
}
},
props: {
row: Object,
fields: Object,
keyUsage: Array,
itemHeight: Number,
elementType: { type: String, default: 'table' }
},
data () {
@@ -300,8 +268,6 @@ export default {
isInlineEditor: {},
isTextareaEditor: false,
isBlobEditor: false,
isMapModal: false,
isMultiSpatial: false,
willBeDeleted: false,
originalContent: null,
editingContent: null,
@@ -314,17 +280,7 @@ export default {
mime: '',
size: null
},
fileToUpload: null,
availableLanguages: [
{ name: 'TEXT', slug: 'text', id: 'text' },
{ name: 'HTML', slug: 'html', id: 'html' },
{ name: 'XML', slug: 'xml', id: 'xml' },
{ name: 'JSON', slug: 'json', id: 'json' },
{ name: 'SVG', slug: 'svg', id: 'svg' },
{ name: 'INI', slug: 'ini', id: 'ini' },
{ name: 'MARKDOWN', slug: 'markdown', id: 'md' },
{ name: 'YAML', slug: 'yaml', id: 'yaml' }
]
fileToUpload: null
};
},
computed: {
@@ -370,9 +326,6 @@ export default {
if (BOOLEAN.includes(this.editingType))
return { type: 'boolean', mask: false };
if (SPATIAL.includes(this.editingType))
return { type: 'map', mask: false };
return { type: 'text', mask: false };
},
isImage () {
@@ -409,21 +362,6 @@ export default {
Object.keys(this.fields).forEach(field => {
this.isInlineEditor[field.name] = false;
});
},
isTextareaEditor (val) {
if (val) {
const modelOperations = new ModelOperations();
(async () => {
const detected = await modelOperations.runModel(this.editingContent);
const filteredLanguages = detected.filter(dLang =>
this.availableLanguages.some(aLang => aLang.id === dLang.languageId) &&
dLang.confidence > 0.1
);
if (filteredLanguages.length)
this.editorMode = this.availableLanguages.find(lang => lang.id === filteredLanguages[0].languageId).slug;
})();
}
}
},
methods: {
@@ -445,7 +383,7 @@ export default {
return bufferToBase64(val);
},
editON (event, content, field) {
if (!this.isEditable || this.editingType === 'none') return;
if (!this.isEditable) return;
window.addEventListener('keydown', this.onKey);
@@ -461,15 +399,6 @@ export default {
return;
}
if (SPATIAL.includes(type)) {
if (content) {
this.isMultiSpatial = IS_MULTI_SPATIAL.includes(type);
this.isMapModal = true;
this.editingContent = this.$options.filters.typeFormat(content, type);
}
return;
}
if (BLOB.includes(type)) {
this.isBlobEditor = true;
this.editingContent = content || '';
@@ -541,8 +470,6 @@ export default {
hideEditorModal () {
this.isTextareaEditor = false;
this.isBlobEditor = false;
this.isMapModal = false;
this.isMultiSpatial = false;
},
downloadFile () {
const downloadLink = document.createElement('a');
@@ -579,7 +506,7 @@ export default {
return this.keyUsage.find(key => key.field === keyName);
},
openContext (event, payload) {
payload.field = this.fields[payload.orgField].name;// Ensures field name only
payload.field = this.fields[payload.field].name;// Ensures field name only
payload.isEditable = this.isEditable;
this.$emit('contextmenu', event, payload);
},

View File

@@ -85,7 +85,7 @@
@click="showFakerModal"
>
<i class="mdi mdi-24px mdi-playlist-plus mr-1" />
<span>{{ $tc('message.insertRow', 2) }}</span>
<span>{{ $t('message.tableFiller') }}</span>
</button>
<div class="dropdown table-dropdown pr-2">

View File

@@ -80,7 +80,6 @@ module.exports = {
deterministic: 'Deterministic',
context: 'Context',
export: 'Export',
import: 'Import',
returns: 'Returns',
timing: 'Timing',
state: 'State',
@@ -123,23 +122,9 @@ module.exports = {
select: 'Select',
passphrase: 'Passphrase',
filter: 'Filter',
change: 'Change',
views: 'Views',
triggers: 'Triggers',
routines: 'Routines',
functions: 'Functions',
schedulers: 'Schedulers',
includes: 'Includes',
drop: 'Drop',
completed: 'Completed',
aborted: 'Aborted',
disabled: 'Disabled',
enable: 'Enable',
disable: 'Disable',
commit: 'Commit',
rollback: 'Rollback',
connectionString: 'Connection string',
contributors: 'Contributors'
disable: 'Disable'
},
message: {
appWelcome: 'Welcome to Antares SQL Client!',
@@ -265,25 +250,8 @@ module.exports = {
searchForQueries: 'Search for queries',
killProcess: 'Kill process',
closeTab: 'Close tab',
exportSchema: 'Export schema',
importSchema: 'Import schema',
directoryPath: 'Directory path',
newInserStmtEvery: 'New INSERT statement every',
processingTableExport: 'Processing {table}',
fechingTableExport: 'Fetching {table} data',
writingTableExport: 'Writing {table} data',
checkAllTables: 'Check all tables',
uncheckAllTables: 'Uncheck all tables',
goToDownloadPage: 'Go to download page',
readOnlyMode: 'Read-only mode',
killQuery: 'Kill query',
insertRow: 'Insert row | Insert rows',
commitMode: 'Commit mode',
autoCommit: 'Auto commit',
manualCommit: 'Manual commit',
actionSuccessful: '{action} successful',
importQueryErrors: 'Warning: {n} error has accurrend | Warning: {n} errors occurred',
executedQueries: '{n} query executed | {n} queries executed'
readOnlyMode: 'Read-only mode'
},
faker: {
address: 'Address',

View File

@@ -13,8 +13,7 @@ const i18n = new VueI18n({
'pt-BR': require('./pt-BR'),
'de-DE': require('./de-DE'),
'vi-VN': require('./vi-VN'),
'ja-JP': require('./ja-JP'),
'zh-CN': require('./zh-CN')
'ja-JP': require('./ja-JP')
}
});
export default i18n;

View File

@@ -80,7 +80,6 @@ module.exports = {
deterministic: 'Deterministico',
context: 'Contesto',
export: 'Esporta',
import: 'Importa',
returns: 'Ritorna',
timing: 'Temporizzazione',
state: 'Stato',
@@ -123,16 +122,6 @@ module.exports = {
select: 'Seleziona',
passphrase: 'Passphrase',
filter: 'Filtra',
change: 'Cambia',
views: 'Viste',
triggers: 'Trigger',
routines: 'Routine',
functions: 'Function',
schedulers: 'Scheduler',
includes: 'Includi',
drop: 'Drop',
completed: 'Completato',
aborted: 'Annullato',
disabled: 'Disabilitato',
enable: 'Abilita',
disable: 'Disabilita'
@@ -248,15 +237,6 @@ module.exports = {
noOpenTabs: 'Non ci sono tab aperte, naviga nella barra sinistra o:',
noSchema: 'Nessuno schema',
restorePreviourSession: 'Ripristina sessione precedente',
exportSchema: 'Esporta schema',
importSchema: 'Importa schema',
directoryPath: 'Percorso directory',
newInserStmtEvery: 'Nuova istruzione INSERT ogni',
processingTableExport: 'Processo {table}',
fechingTableExport: 'Ricavo i dati {table}',
writingTableExport: 'Scrittura dati {table}',
checkAllTables: 'Seleziona tutte le tabelle',
uncheckAllTables: 'Deseleziona tutte le tabelle',
runQuery: 'Esegui query',
thereAreNoTableFields: 'Non ci sono campi della tabella',
newTable: 'Nuova tabella',
@@ -271,9 +251,7 @@ module.exports = {
killProcess: 'Uccidi processo',
closeTab: 'Chiudi tab',
goToDownloadPage: 'Vai alla pagina di download',
readOnlyMode: 'Modalità sola lettura',
importQueryErrors: 'Attenzione: si è verificato un errore | Attenzione si sono verificati {n} errori',
executedQueries: '{n} query eseguite | {n} query eseguite'
readOnlyMode: 'Modalità sola lettura'
},
faker: {
address: 'Indirizzo',

View File

@@ -7,6 +7,5 @@ export default {
'pt-BR': 'Português (Brasil)',
'de-DE': 'Deutsch (Deutschland)',
'vi-VN': 'Tiếng Việt',
'ja-JP': '日本語',
'zh-CN': '简体中文'
'ja-JP': '日本語'
};

View File

@@ -120,11 +120,7 @@ module.exports = {
new: 'Mới',
history: 'Lịch sử',
select: 'Chọn',
passphrase: 'Cụm mật khẩu',
filter: 'Bộ lọc',
disabled: 'Đã tắt',
enable: 'Bật',
disable: 'Tắt'
passphrase: 'Cụm mật khẩu'
},
message: {
appWelcome: 'Chào bạn đến với Antares SQL Client!',
@@ -248,10 +244,7 @@ module.exports = {
newTriggerFunction: 'Chức năng kích hoạt mới',
thereIsNoQueriesYet: 'Không có truy vấn nào',
searchForQueries: 'Tìm kiếm truy vấn',
killProcess: 'Huỷ quá trình',
closeTab: 'Đóng tab',
goToDownloadPage: 'Tới trang tải về',
readOnlyMode: 'Chế độ chỉ đọc'
killProcess: 'Huỷ quá trình'
},
faker: {
address: 'Địa chỉ',

View File

@@ -1,421 +0,0 @@
module.exports = {
word: {
edit: '编辑',
save: '保存',
close: '关闭',
delete: '删除',
confirm: '确定',
cancel: '取消',
send: '发送',
connectionName: '连接名称',
client: 'Client',
hostName: '主机名',
port: '端口',
user: '用户',
password: '密码',
credentials: '凭据',
connect: '连接',
connected: '已连接',
disconnect: '断开连接',
disconnected: '已断开',
refresh: '刷新',
settings: '设置',
general: '一般',
themes: '主题',
update: '更新',
about: '关于',
language: '语言',
version: '版本',
donate: '捐赠',
run: '运行',
schema: 'schema',
results: '结果',
size: '尺寸',
seconds: '秒',
type: '类型',
mimeType: 'MIME类型',
download: '下载',
add: '新增',
data: '数据',
properties: '属性',
insert: '插入',
connecting: '连接中',
name: '名称',
collation: '排序规则',
clear: '清除',
options: '选项',
autoRefresh: '自动刷新',
indexes: '索引',
foreignKeys: '外键',
length: '长度',
unsigned: '无符号',
default: '默认',
comment: '注释',
key: '键',
order: 'Order',
expression: '表达式',
autoIncrement: '自动增量',
engine: 'Engine',
field: '字段',
approximately: '大约',
total: '总计',
table: '表',
discard: '弃置',
stay: '等待',
author: '作者',
light: 'Light',
dark: 'Dark',
autoCompletion: '自动完成',
application: '应用程序',
editor: '编辑器',
view: '视图',
definer: '定义者',
algorithm: 'Algorithm',
trigger: '触发器',
storedRoutine: '存储例程',
scheduler: '调度器',
event: '事件',
parameters: '参数',
function: '函数',
deterministic: 'Deterministic',
context: '上下文',
export: '导出',
returns: '返回',
timing: '定时器',
state: '状态',
execution: '执行',
starts: '开始',
ends: '结束',
ssl: 'SSL',
privateKey: '私钥',
certificate: '证书',
caCertificate: 'CA 证书',
ciphers: 'Ciphers',
upload: '上传',
browse: '浏览',
faker: 'Faker',
content: '内容',
cut: '剪切',
copy: '复制',
paste: '粘贴',
tools: '工具',
variables: '变量',
processes: '进程',
database: '数据库',
scratchpad: 'Scratchpad',
array: '数组',
changelog: '更改日志',
format: '格式',
sshTunnel: 'SSH 隧道',
structure: '结构',
small: '小',
medium: '中',
large: '大',
row: '行',
cell: '单元格',
triggerFunction: '触发函数',
all: '全部',
duplicate: '重复',
routine: '例程',
new: 'New',
history: '历史记录',
select: '选择',
passphrase: '密码',
filter: '过滤器',
disabled: '禁用',
enable: '启用',
disable: '是否禁用'
},
message: {
appWelcome: '欢迎来到Antares SQL Client!',
appFirstStep: '你的第一步: 创建一个新的数据库连接.',
addConnection: '添加连接',
createConnection: '创建连接',
createNewConnection: '创建新的连接',
askCredentials: '询问凭证',
testConnection: '测试连接',
editConnection: '编辑连接',
deleteConnection: '删除连接',
deleteCorfirm: '您是否确认取消',
connectionSuccessfullyMade: '连接成功建立!',
madeWithJS: '用💛和JavaScript制造!',
checkForUpdates: '检查更新',
noUpdatesAvailable: '没有可用的更新',
checkingForUpdate: '正在检查更新',
checkFailure: '检查失败,请稍后再试',
updateAvailable: '可用的更新',
downloadingUpdate: '正在下载更新',
updateDownloaded: '更新已下载',
restartToInstall: '重启Antares完成更新',
unableEditFieldWithoutPrimary: '无法编辑一个在结果集中没有主键的字段',
editCell: '编辑单元格',
deleteRows: '删除行 | 删除{count}行',
confirmToDeleteRows: '你是否确认要删除一行? | 您是否确认要删除{count}行?',
notificationsTimeout: '通知超时',
uploadFile: '上传文件',
addNewRow: '添加新行',
numberOfInserts: '插入的数量',
openNewTab: '打开一个新标签',
affectedRows: '受影响的行',
createNewDatabase: '创建新的数据库',
databaseName: '数据库名称',
serverDefault: '默认服务器',
deleteDatabase: '删除数据库',
editDatabase: '编辑数据库',
clearChanges: '清除变化',
addNewField: '添加新字段',
manageIndexes: '管理索引',
manageForeignKeys: '管理外键',
allowNull: '允许NULL',
zeroFill: '填充零',
customValue: '自定义值',
onUpdate: '在更新时',
deleteField: '删除字段',
createNewIndex: '创建新的索引',
addToIndex: '添加到索引',
createNewTable: '创建新表',
emptyTable: '清空表',
deleteTable: '删除表',
emptyCorfirm: '你是否确认清空',
unsavedChanges: '未保存的更改',
discardUnsavedChanges: '你有一些未保存的修改。关闭这个标签,这些变化将被丢弃.',
thereAreNoIndexes: '没有索引',
thereAreNoForeign: '没有外键',
createNewForeign: '创建新的外键',
referenceTable: '参考表',
referenceField: '参考字段',
foreignFields: '外键字段',
invalidDefault: '无效的默认值',
onDelete: '在删除时',
applicationTheme: '应用主题',
editorTheme: '编辑器主题',
wrapLongLines: '超出换行显示',
selectStatement: '选择语句',
triggerStatement: '触发器语句',
sqlSecurity: 'SQL安全',
updateOption: '更新选项',
deleteView: '删除视图',
createNewView: '创建新视图',
deleteTrigger: '删除触发器',
createNewTrigger: '创建新的触发器',
currentUser: '当前用户',
routineBody: '例程主体',
dataAccess: '数据访问',
thereAreNoParameters: '没有参数',
createNewParameter: '创建新参数',
createNewRoutine: '创建新的例程',
deleteRoutine: '删除例程',
functionBody: '函数体',
createNewFunction: '创建新函数',
deleteFunction: '删除函数',
schedulerBody: '调度器主体',
createNewScheduler: '创建新的调度器',
deleteScheduler: '删除调度器',
preserveOnCompletion: '完成时保存',
enableSsl: '启用SSL',
manualValue: '手动值',
tableFiller: '表填充器',
fakeDataLanguage: '伪造的数据语言',
searchForElements: '搜索元素',
selectAll: '选择所有',
queryDuration: '查询时间',
includeBetaUpdates: '包括测试版更新',
setNull: '设置NULL',
processesList: '进程列表',
processInfo: '进程信息',
manageUsers: '管理用户',
createNewSchema: '创建新模式',
schemaName: '模式名称',
editSchema: '编辑模式',
deleteSchema: '删除模式',
markdownSupported: '支持Markdown',
plantATree: '种植一棵树',
dataTabPageSize: '数据标签的页面大小',
enableSsh: '启用SSH',
pageNumber: '页数',
duplicateTable: '重复的表格',
noOpenTabs: '没有打开的标签,在左栏导航或:',
noSchema: '没有模式',
restorePreviourSession: '恢复以前的会话',
runQuery: '运行查询',
thereAreNoTableFields: '没有表的字段',
newTable: '新表',
newView: '新视图',
newTrigger: '新触发器',
newRoutine: '新例程',
newFunction: '新函数',
newScheduler: '新调度器',
newTriggerFunction: '新触发函数',
thereIsNoQueriesYet: '还没有查询',
searchForQueries: '搜索查询',
killProcess: '杀死进程',
closeTab: '关闭标签',
goToDownloadPage: '跳转到下载页面',
readOnlyMode: '只读模式',
killQuery: '停止查询'
},
faker: {
address: '地址',
commerce: '商业',
company: '公司',
database: '数据库',
date: '日期',
finance: '财务',
git: 'Git',
hacker: '黑客',
internet: '互联网',
lorem: 'Lorem',
name: '姓名',
music: '音乐',
phone: '电话',
random: '随机',
system: '系统',
time: '时间',
vehicle: '车辆',
zipCode: '邮政编码',
zipCodeByState: '按州的邮编',
city: '城市',
cityPrefix: '城市前缀',
citySuffix: '城市后缀',
streetName: '街道名称',
streetAddress: '街道地址',
streetSuffix: '街道前缀',
streetPrefix: '街道后缀',
secondaryAddress: '次要地址',
county: '县',
country: '国家',
countryCode: '国家代码',
state: '州',
stateAbbr: '州的缩写',
latitude: '纬度',
longitude: '经度',
direction: '方向',
cardinalDirection: 'Cardinal direction',
ordinalDirection: 'Ordinal direction',
nearbyGPSCoordinate: '附近的GPS坐标',
timeZone: '时区',
color: '颜色',
department: '部门',
productName: '产品名称',
price: '价格',
productAdjective: '产品形容词',
productMaterial: '产品材料',
product: '产品',
productDescription: '产品描述',
suffixes: '后缀',
companyName: '公司名称',
companySuffix: '公司后缀',
catchPhrase: 'Catch phrase',
bs: 'BS',
catchPhraseAdjective: 'Catch phrase adjective',
catchPhraseDescriptor: 'Catch phrase descriptor',
catchPhraseNoun: 'Catch phrase noun',
bsAdjective: 'BS adjective',
bsBuzz: 'BS buzz',
bsNoun: 'BS noun',
column: '列',
type: '类型',
collation: '校对',
engine: 'Engine',
past: '过去',
future: '未来',
between: '之间',
recent: '最近',
soon: '很快',
month: '月',
weekday: '工作日',
account: '账户',
accountName: '账户名称',
routingNumber: '路由号码',
mask: '掩码',
amount: '金额',
transactionType: '交易类型',
currencyCode: '货币代码',
currencyName: '货币名称',
currencySymbol: '货币符号',
bitcoinAddress: '比特币地址',
litecoinAddress: '莱特币地址',
creditCardNumber: '信用卡号码',
creditCardCVV: '信用卡CVV',
ethereumAddress: '以太坊地址',
iban: 'Iban',
bic: 'Bic',
transactionDescription: '交易描述',
branch: '分支',
commitEntry: '提交条目',
commitMessage: '提交信息',
commitSha: '提交 SHA',
shortSha: 'Short SHA',
abbreviation: '缩写',
adjective: '形容词',
noun: '名词',
verb: '动词',
ingverb: 'Ingverb',
phrase: '短语',
avatar: '头像',
email: '电子邮箱',
exampleEmail: '电子邮件例子',
userName: '用户名',
protocol: '协议',
url: 'Url',
domainName: 'Domin name',
domainSuffix: '域名后缀',
domainWord: 'Domain word',
ip: 'Ip',
ipv6: 'Ipv6',
userAgent: 'User agent',
mac: 'Mac',
password: '密码',
word: 'Word',
words: 'Words',
sentence: '句子',
slug: 'Slug',
sentences: '句子',
paragraph: '段落',
paragraphs: '段落',
text: '文本',
lines: '行',
genre: 'Genre',
firstName: '名',
lastName: '姓氏',
middleName: '中间名',
findName: '全名',
jobTitle: '职位名称',
gender: '性别',
prefix: '前缀',
suffix: '后缀',
title: '标题',
jobDescriptor: '工作描述',
jobArea: '工作领域',
jobType: '工作类型',
phoneNumber: '电话号码',
phoneNumberFormat: '电话号码格式',
phoneFormats: '电话格式',
number: 'Number',
float: 'Float',
arrayElement: '数组元素',
arrayElements: '数组元素',
objectElement: '对象元素',
uuid: 'Uuid',
boolean: 'Boolean',
image: 'Image',
locale: 'Locale',
alpha: 'Alpha',
alphaNumeric: 'Alphanumeric',
hexaDecimal: 'Hexadecimal',
fileName: '文件名',
commonFileName: '普通文件名',
mimeType: 'MIME类型',
commonFileType: '常见的文件类型',
commonFileExt: '常见的文件扩展名',
fileType: '文件类型',
fileExt: '文件扩展名',
directoryPath: '目录路径',
filePath: '文件路径',
semver: 'Semver',
manufacturer: '制造商',
model: '型号',
fuel: 'Fuel',
vin: 'Vin'
}
};

View File

@@ -3,7 +3,6 @@
import Vue from 'vue';
import '@mdi/font/css/materialdesignicons.css';
import 'leaflet/dist/leaflet.css';
import '@/scss/main.scss';
import App from '@/App.vue';

View File

@@ -5,12 +5,4 @@ export default class {
static getKey (params) {
return ipcRenderer.sendSync('get-key', params);
}
static showOpenDialog (options) {
return ipcRenderer.invoke('showOpenDialog', options);
}
static getDownloadPathDirectory () {
return ipcRenderer.invoke('get-download-dir-path');
}
}

View File

@@ -1,21 +1,17 @@
'use strict';
import { ipcRenderer } from 'electron';
import connStringConstruct from '../libs/connStringDecode';
export default class {
static makeTest (params) {
params = connStringConstruct(params);
return ipcRenderer.invoke('test-connection', params);
}
static connect (params) {
params = connStringConstruct(params);
return ipcRenderer.invoke('connect', params);
static checkConnection (params) {
return ipcRenderer.invoke('check-connection', params);
}
static checkConnection (uid) {
return ipcRenderer.invoke('check-connection', uid);
static connect (params) {
return ipcRenderer.invoke('connect', params);
}
static disconnect (uid) {

View File

@@ -46,22 +46,6 @@ export default class {
return ipcRenderer.invoke('kill-process', params);
}
static killTabQuery (params) {
return ipcRenderer.invoke('kill-tab-query', params);
}
static commitTab (params) {
return ipcRenderer.invoke('commit-tab', params);
}
static rollbackTab (params) {
return ipcRenderer.invoke('rollback-tab', params);
}
static destroyConnectionToCommit (params) {
return ipcRenderer.invoke('destroy-connection-to-commit', params);
}
static useSchema (params) {
return ipcRenderer.invoke('use-schema', params);
}
@@ -69,20 +53,4 @@ export default class {
static rawQuery (params) {
return ipcRenderer.invoke('raw-query', params);
}
static export (params) {
return ipcRenderer.invoke('export', params);
}
static abortExport () {
return ipcRenderer.invoke('abort-export');
}
static import (params) {
return ipcRenderer.invoke('import-sql', params);
}
static abortImport () {
return ipcRenderer.invoke('abort-import-sql');
}
}

View File

@@ -1,48 +0,0 @@
import formatter from 'pg-connection-string'; // parses a connection string
const formatHost = host => {
const results = host === 'localhost' ? '127.0.0.1' : host;
return results;
};
const checkForSSl = conn => {
return conn.includes('ssl=true');
};
const connStringConstruct = (args) => {
if (!args.pgConnString)
return args;
if (typeof args.pgConnString !== 'string')
return args;
const stringArgs = formatter.parse(args.pgConnString);
const client = args.client || 'pg';
args.client = client;
args.host = formatHost(stringArgs.host);
args.database = stringArgs.database;
args.port = stringArgs.port || '5432';
args.user = stringArgs.user;
args.password = stringArgs.password;
// ssh
args.ssh = stringArgs.ssh || args.ssh;
args.sshHost = stringArgs.sshHost;
args.sshUser = stringArgs.sshUser;
args.sshPass = stringArgs.sshPass;
args.sshKey = stringArgs.sshKey;
args.sshPort = stringArgs.sshPort;
// ssl mode
args.ssl = checkForSSl(args.pgConnString);
args.cert = stringArgs.sslcert;
args.key = stringArgs.sslkey;
args.ca = stringArgs.sslrootcert;
args.ciphers = stringArgs.ciphers;
return args;
};
export default connStringConstruct;

View File

@@ -81,15 +81,6 @@
"tsvector": $array-color,
"tsquery": $array-color,
"pg_node_tree": $array-color,
"point": $array-color,
"linestring": $array-color,
"polygon": $array-color,
"geometry": $array-color,
"multipoint": $array-color,
"multilinestring": $array-color,
"multipolygon": $array-color,
"geomcollection": $array-color,
"geometrycollection": $array-color,
"aclitem": $array-color,
"unknown": $unknown-color,
)

View File

@@ -20,7 +20,7 @@
background-image: url("../images/svg/pg.svg");
}
&.dbi-sqlite {
&.dbi-sqlite {
background-image: url("../images/svg/sqlite.svg");
}

View File

@@ -59,34 +59,6 @@ option:checked {
text-overflow: ellipsis;
}
.cancellable {
color: transparent !important;
min-height: 0.8rem;
position: relative;
> .mdi,
> .span {
visibility: hidden;
}
&::after {
content: "\2715";
color: $light-color;
font-weight: 700;
top: 36%;
display: block;
height: 0.8rem;
left: 50%;
margin-left: -0.4rem;
margin-top: -0.4rem;
opacity: 1;
padding: 0;
position: absolute;
width: 0.8rem;
z-index: 1;
}
}
.workspace-tabs {
align-content: baseline;
@@ -165,15 +137,6 @@ option:checked {
}
}
}
.modal-overlay{
background: rgba( 255, 255, 255, 0.1 );
box-shadow: 0 8px 32px 0 rgba( 31, 38, 135, 0.37 );
backdrop-filter: blur( 4px );
-webkit-backdrop-filter: blur( 4px );
border-radius: 10px;
border: 1px solid rgba( 255, 255, 255, 0.18 );
}
}
.tab {

View File

@@ -1,49 +0,0 @@
const { _electron: electron } = require('playwright');
const { strict: assert } = require('assert');
(async () => {
console.log('Starting tests');
// Launch Electron app.
const electronApp = await electron.launch({ args: ['dist/main.js'] });
/**
* App main window state
* @type {{isVisible: boolean; isDevToolsOpened: boolean; isCrashed: boolean}}
*/
const windowState = await electronApp.evaluate(({ BrowserWindow }) => {
const mainWindow = BrowserWindow.getAllWindows()[0];
const getState = () => ({
isVisible: mainWindow.isVisible(),
isDevToolsOpened: mainWindow.webContents.isDevToolsOpened()
});
return new Promise((resolve) => {
if (mainWindow.isVisible())
resolve(getState());
else
mainWindow.once('ready-to-show', () => setTimeout(() => resolve(getState()), 0));
});
});
// Check main window state
assert.ok(windowState.isVisible, 'Main window not visible');
assert.ok(!windowState.isDevToolsOpened, 'DevTools opened');
assert.ok(!windowState.isCrashed, 'Window crashed');
/**
* Rendered Main window web-page
* @type {Page}
*/
const page = await electronApp.firstWindow();
console.log(await page.title());
// Check web-page content
const element = await page.$('#wrapper', { strict: true });
assert.notStrictEqual(element, null, 'Can\'t find root element');
assert.notStrictEqual((await element.innerHTML()).trim(), '', 'Window content is empty');
// Close app
await electronApp.close();
console.log('Tests finished');
})();

View File

@@ -1,72 +1,70 @@
const path = require('path');
const webpack = require('webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const ProgressPlugin = require('progress-webpack-plugin');
const { dependencies, devDependencies, version } = require('./package.json');
const { dependencies, devDependencies } = require('./package.json');
const externals = Object.keys(dependencies).concat(Object.keys(devDependencies));
const isDevMode = process.env.NODE_ENV === 'development';
const whiteListedModules = [];
module.exports = { // Main
name: 'main',
mode: process.env.NODE_ENV,
devtool: isDevMode ? 'eval-source-map' : false,
entry: {
main: path.join(__dirname, './src/main/main.js')
},
target: 'electron-main',
output: {
libraryTarget: 'commonjs2',
path: path.join(__dirname, 'dist'),
filename: '[name].js'
},
node: {
global: true,
__dirname: isDevMode,
__filename: isDevMode
},
externals: externals.filter((d) => !whiteListedModules.includes(d)),
resolve: {
extensions: ['.js', '.json'],
alias: {
src: path.join(__dirname, 'src/'),
common: path.resolve(__dirname, 'src/common')
module.exports = [
{ // Main
name: 'main',
mode: process.env.NODE_ENV,
devtool: isDevMode ? 'eval-source-map' : false,
entry: {
main: path.join(__dirname, './src/main/main.js')
},
fallback: {
'pg-native': false,
'cpu-features': false,
cardinal: false
}
},
plugins: [
new ProgressPlugin(true),
new webpack.DefinePlugin({
'process.env': {
PACKAGE_VERSION: `"${version}"`
target: 'electron-main',
output: {
libraryTarget: 'commonjs2',
path: path.join(__dirname, 'dist'),
filename: '[name].js'
},
node: {
global: true,
__dirname: isDevMode,
__filename: isDevMode
},
externals: externals.filter((d) => !whiteListedModules.includes(d)),
resolve: {
extensions: ['.js', '.json'],
alias: {
src: path.join(__dirname, 'src/'),
common: path.resolve(__dirname, 'src/common')
},
fallback: {
'pg-native': false,
'cpu-features': false,
cardinal: false
}
})
],
module: {
rules: [
{
test: /\.node$/,
loader: 'node-loader',
options: {
name: '[path][name].[ext]'
},
plugins: [
new ProgressPlugin(true),
new CleanWebpackPlugin({ root: path.join(__dirname, 'dist') })
],
module: {
rules: [
{
test: /\.node$/,
loader: 'node-loader',
options: {
name: '[path][name].[ext]'
}
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.(png|jpg|gif)$/,
use: [{
loader: 'file-loader'
}]
}
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.(png|jpg|gif)$/,
use: [{
loader: 'file-loader'
}]
}
]
]
}
}
};
];

View File

@@ -1,4 +1,3 @@
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
@@ -7,11 +6,6 @@ const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ProgressPlugin = require('progress-webpack-plugin');
const { dependencies, devDependencies, version } = require('./package.json');
const { contributors } = JSON.parse(fs.readFileSync('./.all-contributorsrc', 'utf-8'));
const parsedContributors = contributors.reduce((acc, c) => {
acc.push(c.name);
return acc;
}, []).join(',');
const externals = Object.keys(dependencies).concat(Object.keys(devDependencies));
const isDevMode = process.env.NODE_ENV === 'development';
@@ -70,8 +64,7 @@ const config = {
new VueLoaderPlugin(),
new webpack.DefinePlugin({
'process.env': {
PACKAGE_VERSION: `"${version}"`,
APP_CONTRIBUTORS: `"${parsedContributors}"`
PACKAGE_VERSION: `"${version}"`
}
})
],

View File

@@ -1,81 +0,0 @@
const path = require('path');
const webpack = require('webpack');
const ProgressPlugin = require('progress-webpack-plugin');
const { dependencies, devDependencies, version } = require('./package.json');
const externals = Object.keys(dependencies).concat(Object.keys(devDependencies));
const isDevMode = process.env.NODE_ENV === 'development';
const whiteListedModules = [];
const config = {
name: 'workers',
mode: process.env.NODE_ENV,
devtool: isDevMode ? 'eval-source-map' : false,
entry: {
exporter: path.join(__dirname, './src/main/workers/exporter.js'),
importer: path.join(__dirname, './src/main/workers/importer.js')
},
target: 'node',
output: {
libraryTarget: 'commonjs2',
path: path.join(__dirname, 'dist'),
filename: '[name].js'
},
node: {
global: true,
__dirname: isDevMode,
__filename: isDevMode
},
externals: externals.filter((d) => !whiteListedModules.includes(d)),
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.node$/,
use: 'node-loader'
}
]
},
resolve: {
extensions: ['.js', '.json'],
alias: {
src: path.join(__dirname, 'src/'),
common: path.resolve(__dirname, 'src/common')
},
fallback: {
'pg-native': false,
'cpu-features': false,
cardinal: false
}
},
plugins: [
new ProgressPlugin(true),
new webpack.DefinePlugin({
'process.env': {
PACKAGE_VERSION: `"${version}"`
}
})
]
};
/**
* Adjust rendererConfig for production settings
*/
if (isDevMode) {
// any dev only config
config.plugins.push(new webpack.HotModuleReplacementPlugin());
}
else {
config.plugins.push(
new webpack.LoaderOptionsPlugin({
minimize: true
})
);
}
module.exports = config;