Merge branch 'master' into dependabot/npm_and_yarn/sql-formatter-12.2.0

This commit is contained in:
Fabio Di Stasio 2023-06-12 15:01:48 +02:00
commit 0a6907b549
44 changed files with 1513 additions and 23820 deletions

View File

@ -202,6 +202,24 @@
"contributions": [
"translation"
]
},
{
"login": "555cider",
"name": "555cider",
"avatar_url": "https://avatars.githubusercontent.com/u/73565447?v=4",
"profile": "https://github.com/555cider",
"contributions": [
"translation"
]
},
{
"login": "m1khal3v",
"name": "Anton Mikhalev",
"avatar_url": "https://avatars.githubusercontent.com/u/41085561?v=4",
"profile": "https://github.com/m1khal3v",
"contributions": [
"translation"
]
}
],
"contributorsPerLine": 7,

View File

@ -0,0 +1,32 @@
name: Create artifact [LINUX ARM64]
on:
workflow_dispatch: {}
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Check out Git repository
uses: actions/checkout@v3
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: 16
- name: Install dependencies
run: npm i
- name: "Build"
run: npm run build -- --arm64 --linux deb AppImage
- name: Upload Artifact
uses: actions/upload-artifact@v3
with:
name: linux-build
retention-days: 3
path: |
build
!build/*-unpacked
!build/.icon-ico

View File

@ -2,6 +2,72 @@
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.7.11](https://github.com/antares-sql/antares/compare/v0.7.10...v0.7.11) (2023-06-04)
### Features
* context menu to close tabs, closes [#392](https://github.com/antares-sql/antares/issues/392) ([787014c](https://github.com/antares-sql/antares/commit/787014c38df743315c04962871a3801805a93c55))
### Bug Fixes
* disable filter during table content loading, fixes [#588](https://github.com/antares-sql/antares/issues/588) ([e60726c](https://github.com/antares-sql/antares/commit/e60726c741276b7da0d54c0986d2a45ed9979bc9))
* **MySQL:** unable to get users list with some db settings ([9046707](https://github.com/antares-sql/antares/commit/904670781d47b1ac0dcfd982215ba1786f8c8145))
* unique keys not recognized in table settings on some MariaDB versions ([4461998](https://github.com/antares-sql/antares/commit/446199827be4b07382453739f42d46fa0201d04c))
* weird behavior in some text editors ([22bdaac](https://github.com/antares-sql/antares/commit/22bdaac18b1c46a57802cbbd3ad339ee075ec70b))
### [0.7.10](https://github.com/antares-sql/antares/compare/v0.7.9...v0.7.10) (2023-05-28)
### Features
* copy rows as PHP array ([03638c0](https://github.com/antares-sql/antares/commit/03638c05534e9ce2e594ce5945485587ed99e609))
* DDL query in table settings for MySQL and PostgreSQL, closes [#581](https://github.com/antares-sql/antares/issues/581) ([f454b4b](https://github.com/antares-sql/antares/commit/f454b4bb1ca79eec285b3b4039a2ef66802ff82a))
* export table content or query results as PHP array, closes [#575](https://github.com/antares-sql/antares/issues/575) ([8968179](https://github.com/antares-sql/antares/commit/8968179c11f4fe3e624873aac4685a5a33521024))
* keepalive on mysql/postgre connections, should fix [#577](https://github.com/antares-sql/antares/issues/577) ([17eeb6d](https://github.com/antares-sql/antares/commit/17eeb6d38e45b553e35e004b748569971743ca18))
### Bug Fixes
* disable shorctut to show Ace editor settings, fixes [#585](https://github.com/antares-sql/antares/issues/585) ([2c0b4ff](https://github.com/antares-sql/antares/commit/2c0b4ffe1f2e418f5e9120a40787788d8e7fd27e))
### [0.7.9](https://github.com/antares-sql/antares/compare/v0.7.8...v0.7.9) (2023-05-01)
### Features
* no table results message ([19859f4](https://github.com/antares-sql/antares/commit/19859f45f4457292b6ecfe79bdcfbdcc7722be06))
* option to choose the target table of an SQL INSERT exportation, closes [#556](https://github.com/antares-sql/antares/issues/556) ([c48266c](https://github.com/antares-sql/antares/commit/c48266c336d7c61abe2b56b5702e5bca83bb57b3))
* **translation:** ko-KR translation, closes [#561](https://github.com/antares-sql/antares/issues/561) ([baef4ea](https://github.com/antares-sql/antares/commit/baef4ea4d1747233a86b90fe5b60a0d6cfba1f1c))
### Bug Fixes
* sidebar height out of visible area ([af91d96](https://github.com/antares-sql/antares/commit/af91d96db6e79222e5dbc9b880a904a40332c09b))
* unable to delete rows with null values and no primary key ([74c136f](https://github.com/antares-sql/antares/commit/74c136f8334b6972ae55dd8ee0ade09ef8ae3282))
* vertical scrollbar does not reset after performing a search, fixes [#567](https://github.com/antares-sql/antares/issues/567) ([0cd55fb](https://github.com/antares-sql/antares/commit/0cd55fbfe9ff09589ae5993f16b0dd56a2ea1a5a))
### Improvements
* **translation:** update italian translation ([96e1ceb](https://github.com/antares-sql/antares/commit/96e1ceb1d2488390216553cd3fce2eec261f04eb))
### [0.7.8](https://github.com/antares-sql/antares/compare/v0.7.7...v0.7.8) (2023-04-12)
### Features
* filter schemas in sidebar, closes [#555](https://github.com/antares-sql/antares/issues/555) ([8be9f93](https://github.com/antares-sql/antares/commit/8be9f932e7a44b2067d8b57950d8faafc577123f))
* **MySQL:** option to export from results SQL INSERTS in chunks, closes [#501](https://github.com/antares-sql/antares/issues/501) ([0f24c80](https://github.com/antares-sql/antares/commit/0f24c80e5a2dc45875df6b67d3c097cf1cca458e))
### Bug Fixes
* **MySQL:** missing scale for FLOAT type ([52108d7](https://github.com/antares-sql/antares/commit/52108d76133d5fdffb56faa995d7ab7ee3e7c4bc))
* triggers not exported if related table not included ([d802b32](https://github.com/antares-sql/antares/commit/d802b32597e42ee90a2d691fe74245b3bc2517ee))
* unable to export BLOB values from table content o query result ([afa61a9](https://github.com/antares-sql/antares/commit/afa61a9bc2d698894096a6b5413c49f05b2fd5aa))
### [0.7.7](https://github.com/antares-sql/antares/compare/v0.7.6...v0.7.7) (2023-03-10)

View File

@ -144,6 +144,10 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
<td align="center" valign="top" width="14.28%"><a href="http://yaskur.net"><img src="https://avatars.githubusercontent.com/u/9539970?v=4?s=100" width="100px;" alt="Muhammad Dyas Yaskur"/><br /><sub><b>Muhammad Dyas Yaskur</b></sub></a><br /><a href="#translation-dyaskur" title="Translation">🌍</a> <a href="https://github.com/antares-sql/antares/commits?author=dyaskur" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/jimcat8"><img src="https://avatars.githubusercontent.com/u/86754294?v=4?s=100" width="100px;" alt="tianci li"/><br /><sub><b>tianci li</b></sub></a><br /><a href="#translation-jimcat8" title="Translation">🌍</a></td>
</tr>
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/555cider"><img src="https://avatars.githubusercontent.com/u/73565447?v=4?s=100" width="100px;" alt="555cider"/><br /><sub><b>555cider</b></sub></a><br /><a href="#translation-555cider" title="Translation">🌍</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/m1khal3v"><img src="https://avatars.githubusercontent.com/u/41085561?v=4?s=100" width="100px;" alt="Anton Mikhalev"/><br /><sub><b>Anton Mikhalev</b></sub></a><br /><a href="#translation-m1khal3v" title="Translation">🌍</a></td>
</tr>
</tbody>
</table>

23645
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
{
"name": "antares",
"productName": "Antares",
"version": "0.7.7",
"version": "0.7.11",
"description": "A modern, fast and productivity driven SQL client with a focus in UX.",
"license": "MIT",
"repository": "https://github.com/antares-sql/antares.git",
@ -66,16 +66,14 @@
"target": "deb",
"arch": [
"x64",
"armv7l",
"arm64"
"armv7l"
]
},
{
"target": "AppImage",
"arch": [
"x64",
"armv7l",
"arm64"
"armv7l"
]
}
],
@ -132,6 +130,7 @@
"electron-window-state": "~5.0.3",
"encoding": "~0.1.13",
"floating-vue": "~2.0.0-beta.20",
"json2php": "~0.0.7",
"leaflet": "~1.7.1",
"marked": "~4.0.19",
"moment": "~2.29.4",

View File

@ -31,11 +31,12 @@ export const defaults: Customizations = {
routines: false,
functions: false,
schedulers: false,
// Settings
// Misc
elementsWrapper: '',
stringsWrapper: '"',
tableAdd: false,
tableTruncateDisableFKCheck: false,
tableDdl: false,
viewAdd: false,
triggerAdd: false,
triggerFunctionAdd: false,

View File

@ -44,6 +44,7 @@ export const customizations: Customizations = {
tableAdd: true,
tableTruncateDisableFKCheck: true,
tableDuplicate: true,
tableDdl: true,
viewAdd: true,
triggerAdd: true,
routineAdd: true,

View File

@ -35,11 +35,12 @@ export const customizations: Customizations = {
triggerFunctions: true,
routines: true,
functions: true,
// Settings
// Misc
elementsWrapper: '"',
stringsWrapper: '\'',
tableAdd: true,
tableDuplicate: true,
tableDdl: true,
viewAdd: true,
triggerAdd: true,
triggerFunctionAdd: true,

View File

@ -30,7 +30,7 @@ export interface Customizations {
routines?: boolean;
functions?: boolean;
schedulers?: boolean;
// Settings
// Misc
elementsWrapper: string;
stringsWrapper: string;
tableAdd?: boolean;
@ -39,6 +39,7 @@ export interface Customizations {
tableArray?: boolean;
tableRealCount?: boolean;
tableTruncateDisableFKCheck?: boolean;
tableDdl?: boolean;
viewAdd?: boolean;
viewSettings?: boolean;
triggerAdd?: boolean;

View File

@ -72,7 +72,7 @@ export const escapeAndQuote = (val: string, client: ClientCode) => {
export const valueToSqlString = (args: {
val: any;
client: ClientCode;
field: {type: string; datePrecision: number};
field: {type: string; datePrecision: number; isArray?: boolean};
}): string => {
let parsedValue;
const { val, client, field } = args;
@ -94,7 +94,7 @@ export const valueToSqlString = (args: {
? escapeAndQuote(moment(val).format(`YYYY-MM-DD HH:mm:ss${datePrecision}`), client)
: escapeAndQuote(val, client);
}
else if ('isArray' in field) {
else if ('isArray' in field && field.isArray) {
let localVal;
if (Array.isArray(val))
localVal = JSON.stringify(val).replaceAll('[', '{').replaceAll(']', '}');
@ -107,10 +107,16 @@ export const valueToSqlString = (args: {
else if (BIT.includes(field.type))
parsedValue = `b'${hexToBinary(Buffer.from(val).toString('hex') as undefined as HexChar[])}'`;
else if (BLOB.includes(field.type)) {
let buffer: Buffer;
if (val instanceof Uint8Array)
buffer = Buffer.from(val);
else
buffer = val;
if (['mysql', 'maria'].includes(client))
parsedValue = `X'${val.toString('hex').toUpperCase()}'`;
parsedValue = `X'${buffer.toString('hex').toUpperCase()}'`;
else if (client === 'pg')
parsedValue = `decode('${val.toString('hex').toUpperCase()}', 'hex')`;
parsedValue = `decode('${buffer.toString('hex').toUpperCase()}', 'hex')`;
}
else if (NUMBER.includes(field.type))
parsedValue = val;
@ -146,17 +152,47 @@ export const valueToSqlString = (args: {
};
export const jsonToSqlInsert = (args: {
json: { [key: string]: any};
json: { [key: string]: any}[];
client: ClientCode;
fields: { [key: string]: {type: string; datePrecision: number}};
table: string;
options?: {sqlInsertAfter: number; sqlInsertDivider: 'bytes' | 'rows'};
}) => {
const { client, json, fields, table } = args;
const { client, json, fields, table, options } = args;
const sqlInsertAfter = options && options.sqlInsertAfter ? options.sqlInsertAfter : 1;
const sqlInsertDivider = options && options.sqlInsertDivider ? options.sqlInsertDivider : 'rows';
const { elementsWrapper: ew } = customizations[client];
const fieldNames = Object.keys(json).map(key => `${ew}${key}${ew}`);
const values = Object.keys(json).map(key => (
valueToSqlString({ val: json[key], client, field: fields[key] })
));
const fieldNames = Object.keys(json[0]).map(key => `${ew}${key}${ew}`);
let insertStmt = `INSERT INTO ${ew}${table}${ew} (${fieldNames.join(', ')}) VALUES `;
let insertsString = '';
let queryLength = 0;
let rowsWritten = 0;
return `INSERT INTO ${ew}${table}${ew} (${fieldNames.join(', ')}) VALUES (${values.join(', ')});`;
for (const row of json) {
const values = [];
values.push(Object.keys(row).map(key => (
valueToSqlString({ val: row[key], client, field: fields[key] })
)));
if (
(sqlInsertDivider === 'bytes' && queryLength >= sqlInsertAfter * 1024) ||
(sqlInsertDivider === 'rows' && rowsWritten === sqlInsertAfter)
) {
insertsString += insertStmt+';';
insertStmt = `\nINSERT INTO ${ew}${table}${ew} (${fieldNames.join(', ')}) VALUES `;
rowsWritten = 0;
}
rowsWritten++;
if (rowsWritten > 1) insertStmt += ',\n';
insertStmt += `(${values.join(',')})`;
queryLength = insertStmt.length;
}
if (rowsWritten > 0)
insertsString += insertStmt+';';
return insertsString;
};

View File

@ -75,6 +75,17 @@ export default (connections: {[key: string]: antares.Client}) => {
}
});
ipcMain.handle('get-table-ddl', async (event, params) => {
try {
const result = await connections[params.uid].getTableDll(params);
return { status: 'success', response: result };
}
catch (err) {
return { status: 'error', response: err.toString() };
}
});
ipcMain.handle('get-key-usage', async (event, params) => {
try {
const result = await connections[params.uid].getKeyUsage(params);
@ -247,7 +258,10 @@ export default (connections: {[key: string]: antares.Client}) => {
if (typeof row[key] === 'string')
row[key] = `'${row[key]}'`;
row[key] = `= ${row[key]}`;
if (row[key] === null)
row[key] = 'IS NULL';
else
row[key] = `= ${row[key]}`;
}
await connections[params.uid]

View File

@ -174,6 +174,10 @@ export abstract class AntaresCore {
throw new Error('Method "dropSchema" not implemented');
}
getTableDll (...args: any) {
throw new Error('Method "getTableDll" not implemented');
}
getDatabaseCollation (...args: any) {
throw new Error('Method "getDatabaseCollation" not implemented');
}

View File

@ -9,6 +9,8 @@ export class MySQLClient extends AntaresCore {
private _schema?: string;
private _runningConnections: Map<string, number>;
private _connectionsToCommit: Map<string, mysql.Connection | mysql.PoolConnection>;
private _keepaliveTimer: NodeJS.Timer;
private _keepaliveMs: number;
_connection?: mysql.Connection | mysql.Pool;
_params: mysql.ConnectionOptions & {schema: string; ssl?: mysql.SslOptions; ssh?: SSHConfig; readonly: boolean};
@ -52,6 +54,7 @@ export class MySQLClient extends AntaresCore {
this._schema = null;
this._runningConnections = new Map();
this._connectionsToCommit = new Map();
this._keepaliveMs = 10*60*1000;
}
private _getType (field: mysql.FieldPacket & { columnType?: number; columnLength?: number }) {
@ -182,6 +185,8 @@ export class MySQLClient extends AntaresCore {
destroy () {
this._connection.end();
clearInterval(this._keepaliveTimer);
this._keepaliveTimer = undefined;
if (this._ssh) this._ssh.close();
}
@ -243,9 +248,19 @@ export class MySQLClient extends AntaresCore {
conn.query(`SET SESSION sql_mode = '${sqlMode.filter((m: string) => !['ANSI', 'ANSI_QUOTES'].includes(m)).join(',')}'`);
});
this._keepaliveTimer = setInterval(async () => {
await this.keepAlive();
}, this._keepaliveMs);
return connection;
}
private async keepAlive () {
const connection = await (this._connection as mysql.Pool).getConnection();
await connection.ping();
connection.release();
}
use (schema: string) {
this._schema = schema;
return this.raw(`USE \`${schema}\``);
@ -674,11 +689,11 @@ export class MySQLClient extends AntaresCore {
return rows.map(row => {
return {
unique: !row.Non_unique,
unique: !Number(row.Non_unique),
name: row.Key_name,
column: row.Column_name,
indexType: row.Index_type,
type: row.Key_name === 'PRIMARY' ? 'PRIMARY' : !row.Non_unique ? 'UNIQUE' : row.Index_type === 'FULLTEXT' ? 'FULLTEXT' : 'INDEX',
type: row.Key_name === 'PRIMARY' ? 'PRIMARY' : !Number(row.Non_unique) ? 'UNIQUE' : row.Index_type === 'FULLTEXT' ? 'FULLTEXT' : 'INDEX',
cardinality: row.Cardinality,
comment: row.Comment,
indexComment: row.Index_comment
@ -686,6 +701,17 @@ export class MySQLClient extends AntaresCore {
});
}
async getTableDll ({ schema, table }: { schema: string; table: string }) {
const { rows } = await this.raw<antares.QueryResult<{
'Create Table'?: string;
Table: string;
}>>(`SHOW CREATE TABLE \`${schema}\`.\`${table}\``);
if (rows.length)
return rows[0]['Create Table'];
else return '';
}
async getKeyUsage ({ schema, table }: { schema: string; table: string }) {
interface KeyResult {
TABLE_SCHEMA: string;
@ -738,7 +764,7 @@ export class MySQLClient extends AntaresCore {
}
async getUsers () {
const { rows } = await this.raw('SELECT `user`, `host`, authentication_string AS `password` FROM `mysql`.`user`');
const { rows } = await this.raw('SELECT `user` as \'user\', `host` as \'host\', authentication_string AS `password` FROM `mysql`.`user`');
return rows.map(row => {
return {

View File

@ -84,6 +84,8 @@ export class PostgreSQLClient extends AntaresCore {
private _schema?: string;
private _runningConnections: Map<string, number>;
private _connectionsToCommit: Map<string, pg.Client | pg.PoolClient>;
private _keepaliveTimer: NodeJS.Timer;
private _keepaliveMs: number;
protected _connection?: pg.Client | pg.Pool;
private types: {[key: string]: string} = {};
private _arrayTypes: {[key: string]: string} = {
@ -104,6 +106,7 @@ export class PostgreSQLClient extends AntaresCore {
this._schema = null;
this._runningConnections = new Map();
this._connectionsToCommit = new Map();
this._keepaliveMs = 10*60*1000;
for (const key in pg.types.builtins) {
const builtinKey = key as builtinsTypes;
@ -222,14 +225,26 @@ export class PostgreSQLClient extends AntaresCore {
});
}
this._keepaliveTimer = setInterval(async () => {
await this.keepAlive();
}, this._keepaliveMs);
return connection;
}
destroy () {
this._connection.end();
clearInterval(this._keepaliveTimer);
this._keepaliveTimer = undefined;
if (this._ssh) this._ssh.close();
}
private async keepAlive () {
const connection = await this._connection.connect() as pg.PoolClient;
await connection.query('SELECT 1+1');
connection.release();
}
use (schema: string, connection?: pg.Client | pg.PoolClient) {
this._schema = schema;
@ -567,6 +582,142 @@ export class PostgreSQLClient extends AntaresCore {
}, {} as {table: string; schema: string}[]);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async getTableDll ({ schema, table }: { schema: string; table: string }) {
// const { rows } = await this.raw<antares.QueryResult<{'ddl'?: string}>>(`
// SELECT
// 'CREATE TABLE ' || relname || E'\n(\n' ||
// array_to_string(
// array_agg(' ' || column_name || ' ' || type || ' '|| not_null)
// , E',\n'
// ) || E'\n);\n' AS ddl
// FROM (
// SELECT
// a.attname AS column_name
// , pg_catalog.format_type(a.atttypid, a.atttypmod) AS type
// , CASE WHEN a.attnotnull THEN 'NOT NULL' ELSE 'NULL' END AS not_null
// , c.relname
// FROM pg_attribute a, pg_class c, pg_type t
// WHERE a.attnum > 0
// AND a.attrelid = c.oid
// AND a.atttypid = t.oid
// AND c.relname = '${table}'
// ORDER BY a.attnum
// ) AS tabledefinition
// GROUP BY relname
// `);
// if (rows.length)
// return rows[0].ddl;
// else return '';
/* eslint-disable camelcase */
interface SequenceRecord {
sequence_catalog: string;
sequence_schema: string;
sequence_name: string;
data_type: string;
numeric_precision: number;
numeric_precision_radix: number;
numeric_scale: number;
start_value: string;
minimum_value: string;
maximum_value: string;
increment: string;
cycle_option: string;
}
/* eslint-enable camelcase */
let createSql = '';
const sequences = [];
const columnsSql = [];
const arrayTypes: {[key: string]: string} = {
_int2: 'smallint',
_int4: 'integer',
_int8: 'bigint',
_float4: 'real',
_float8: 'double precision',
_char: '"char"',
_varchar: 'character varying'
};
// Table columns
const { rows } = await this.raw(`
SELECT *
FROM "information_schema"."columns"
WHERE "table_schema" = '${schema}'
AND "table_name" = '${table}'
ORDER BY "ordinal_position" ASC
`, { schema: 'information_schema' });
if (!rows.length) return '';
for (const column of rows) {
let fieldType = column.data_type;
if (fieldType === 'USER-DEFINED') fieldType = `"${schema}".${column.udt_name}`;
else if (fieldType === 'ARRAY') {
if (Object.keys(arrayTypes).includes(fieldType))
fieldType = arrayTypes[column.udt_name] + '[]';
else
fieldType = column.udt_name.replaceAll('_', '') + '[]';
}
const columnArr = [
`"${column.column_name}"`,
`${fieldType}${column.character_maximum_length ? `(${column.character_maximum_length})` : ''}`
];
if (column.column_default) {
columnArr.push(`DEFAULT ${column.column_default}`);
if (column.column_default.includes('nextval')) {
const sequenceName = column.column_default.split('\'')[1];
sequences.push(sequenceName);
}
}
if (column.is_nullable === 'NO') columnArr.push('NOT NULL');
columnsSql.push(columnArr.join(' '));
}
// Table sequences
for (let sequence of sequences) {
if (sequence.includes('.')) sequence = sequence.split('.')[1];
const { rows } = await this.select('*')
.schema('information_schema')
.from('sequences')
.where({ sequence_schema: `= '${schema}'`, sequence_name: `= '${sequence}'` })
.run<SequenceRecord>();
if (rows.length) {
createSql += `CREATE SEQUENCE "${schema}"."${sequence}"
START WITH ${rows[0].start_value}
INCREMENT BY ${rows[0].increment}
MINVALUE ${rows[0].minimum_value}
MAXVALUE ${rows[0].maximum_value}
CACHE 1;\n`;
}
}
// Table create
createSql += `\nCREATE TABLE "${schema}"."${table}"(
${columnsSql.join(',\n ')}
);\n`;
// Table indexes
createSql += '\n';
const { rows: indexes } = await this.select('*')
.schema('pg_catalog')
.from('pg_indexes')
.where({ schemaname: `= '${schema}'`, tablename: `= '${table}'` })
.run<{indexdef: string}>();
for (const index of indexes)
createSql += `${index.indexdef};\n`;
return createSql;
}
async getKeyUsage ({ schema, table }: { schema: string; table: string }) {
/* eslint-disable camelcase */
interface KeyResult {

View File

@ -184,9 +184,9 @@ CREATE TABLE \`${view.Name}\`(
const { rows: triggers } = await this._client.raw(
`SHOW TRIGGERS FROM \`${this.schemaName}\``
);
const generatedTables = this._tables
.filter(t => t.includeStructure)
.map(t => t.table);
// const generatedTables = this._tables
// .filter(t => t.includeStructure)
// .map(t => t.table);
let sqlString = '';
@ -200,7 +200,7 @@ CREATE TABLE \`${view.Name}\`(
sql_mode: sqlMode
} = trigger;
if (!generatedTables.includes(table)) continue;
// if (!generatedTables.includes(table)) continue;// Commented to avoid issues if export contains triggers without tables
const definer = this.getEscapedDefiner(trigger.Definer);
sqlString += '/*!50003 SET @OLD_SQL_MODE=@@SQL_MODE*/;;\n';

View File

@ -124,8 +124,8 @@ else {
if (isWindows)
mainWindow.show();
// if (isDevelopment)
// mainWindow.webContents.openDevTools();
if (isDevelopment)
mainWindow.webContents.openDevTools();
process.on('uncaughtException', error => {
mainWindow.webContents.send('unhandled-exception', error);

View File

@ -7,7 +7,7 @@ import MysqlExporter from '../libs/exporters/sql/MysqlExporter';
import PostgreSQLExporter from '../libs/exporters/sql/PostgreSQLExporter';
let exporter: antares.Exporter;
process.on('message', async ({ type, client, tables, options }) => {
process.on('message', async ({ type, client, tables, options }: any) => {
if (type === 'init') {
const connection = await ClientsFactory.getClient({
client: client.name,

View File

@ -44,6 +44,11 @@ watch(() => props.mode, () => {
editor.session.setMode(`ace/mode/${props.mode}`);
});
watch(() => props.modelValue, () => {
if (editor && props.readOnly)
editor.session.setValue(props.modelValue);
});
watch(editorTheme, () => {
if (editor)
editor.setTheme(`ace/theme/${editorTheme.value}`);
@ -113,6 +118,8 @@ onMounted(() => {
}, 20);
}
editor.commands.removeCommand('showSettingsMenu');
setTimeout(() => {
editor.resize();
}, 20);

View File

@ -6,7 +6,7 @@
<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" />
<i class="mdi mdi-24px mdi-database-export mr-1" />
<span class="cut-text">{{ t('message.exportSchema') }}</span>
</div>
</div>
@ -78,7 +78,7 @@
<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" :style="'width: 50%;'" />
<div class="th no-border">
<label
class="form-checkbox m-0 px-2 form-inline"
@ -120,7 +120,7 @@
</div>
</div>
<div class="tr">
<div class="th" style="width: 50%;">
<div class="th" :style="'width: 50%;'">
<div class="table-column-title">
<span>{{ t('word.table') }}</span>
</div>

View File

@ -6,7 +6,7 @@
<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" />
<i class="mdi mdi-24px mdi-database-import mr-1" />
<span class="cut-text">{{ t('message.importSchema') }}</span>
</div>
</div>

View File

@ -373,6 +373,8 @@ onMounted(() => {
e.stop();
});
editor.value.commands.removeCommand('showSettingsMenu');
if (props.autoFocus) {
setTimeout(() => {
editor.value.focus();

View File

@ -1,5 +1,15 @@
<template>
<div v-show="isSelected" class="workspace column columns col-gapless">
<WorkspaceTabsContext
v-if="isTabContext"
:context-event="contextEvent"
:selected-tab="selectedContextTab"
@close-all-tabs="closeAllTabs"
@close-other-tabs="closeOtherTabs"
@close-to-left="closeTabsToLeft"
@close-to-right="closeTabsToRight"
@close-context="closeContext"
/>
<WorkspaceExploreBar
v-if="workspace?.connectionStatus === 'connected'"
:connection="connection"
@ -23,6 +33,7 @@
:class="{'active': selectedTab === element.uid}"
@mousedown.left="selectTab({uid: workspace.uid, tab: element.uid})"
@mouseup.middle="closeTab(element)"
@contextmenu.prevent="contextMenu($event, element)"
>
<a
v-if="element.type === 'query'"
@ -501,6 +512,7 @@ import WorkspaceTabNewRoutine from '@/components/WorkspaceTabNewRoutine.vue';
import WorkspaceTabNewFunction from '@/components/WorkspaceTabNewFunction.vue';
import WorkspaceTabNewScheduler from '@/components/WorkspaceTabNewScheduler.vue';
import WorkspaceTabNewTriggerFunction from '@/components/WorkspaceTabNewTriggerFunction.vue';
import WorkspaceTabsContext from '@/components/WorkspaceTabsContext.vue';
import WorkspaceTabPropsTable from '@/components/WorkspaceTabPropsTable.vue';
import WorkspaceTabPropsView from '@/components/WorkspaceTabPropsView.vue';
@ -545,6 +557,9 @@ const hasWheelEvent = ref(false);
const isProcessesModal = ref(false);
const unsavedTab = ref(null);
const tabWrap = ref(null);
const contextEvent = ref(null);
const isTabContext = ref(false);
const selectedContextTab = ref(null);
const workspace = computed(() => getWorkspace(props.connection.uid));
@ -627,6 +642,34 @@ const closeTab = (tab: WorkspaceTab, force = false) => {
removeTab({ uid: props.connection.uid, tab: tab.uid });
};
const closeAllTabs = () => {
for (const tab of draggableTabs.value)
removeTab({ uid: props.connection.uid, tab: tab.uid });
};
const closeOtherTabs = () => {
const otherTabs = draggableTabs.value.filter(t => t.uid !== selectedContextTab.value.uid);
for (const tab of otherTabs)
removeTab({ uid: props.connection.uid, tab: tab.uid });
};
const closeTabsToLeft = () => {
const tabIndex = draggableTabs.value.findIndex(t => t.uid === selectedContextTab.value.uid);
const leftTabs = draggableTabs.value.filter((t, i) => i < tabIndex);
for (const tab of leftTabs)
removeTab({ uid: props.connection.uid, tab: tab.uid });
};
const closeTabsToRight = () => {
const tabIndex = draggableTabs.value.findIndex(t => t.uid === selectedContextTab.value.uid);
const leftTabs = draggableTabs.value.filter((t, i) => i > tabIndex);
for (const tab of leftTabs)
removeTab({ uid: props.connection.uid, tab: tab.uid });
};
const showProcessesModal = () => {
isProcessesModal.value = true;
};
@ -647,6 +690,16 @@ const addWheelEvent = () => {
}
};
const contextMenu = (event: MouseEvent, tab: WorkspaceTab) => {
selectedContextTab.value = tab;
contextEvent.value = event;
isTabContext.value = true;
};
const closeContext = () => {
isTabContext.value = false;
};
(async () => {
await addWorkspace(props.connection.uid);
const isInitiated = await Connection.checkConnection(props.connection.uid);

View File

@ -416,7 +416,7 @@ const clients = [
{ name: 'MariaDB', slug: 'maria' },
{ name: 'PostgreSQL', slug: 'pg' },
{ name: 'SQLite', slug: 'sqlite' },
{ name: 'Firebird SQL (experimental)', slug: 'firebird' }
{ name: 'Firebird SQL', slug: 'firebird' }
];
const connection = ref({

View File

@ -429,7 +429,7 @@ const clients = [
{ name: 'MariaDB', slug: 'maria' },
{ name: 'PostgreSQL', slug: 'pg' },
{ name: 'SQLite', slug: 'sqlite' },
{ name: 'Firebird SQL (experimental)', slug: 'firebird' }
{ name: 'Firebird SQL', slug: 'firebird' }
];
const firstInput: Ref<HTMLInputElement> = ref(null);

View File

@ -32,13 +32,20 @@
</span>
</div>
<div class="workspace-explorebar-search">
<div v-if="workspace.connectionStatus === 'connected'" class="has-icon-right">
<div v-if="workspace.connectionStatus === 'connected'" class="input-group has-icon-right">
<div
class="input-group-addon px-1 py-0 p-vcentered c-hand"
:title="t('message.switchSearchMethod')"
@click="toggleSearchMethod"
>
<i class="mdi mdi-18px" :class="[searchMethod === 'elements' ? 'mdi-shape' : 'mdi-database']" />
</div>
<input
ref="searchInput"
v-model="searchTerm"
class="form-input input-sm"
type="text"
:placeholder="t('message.searchForElements')"
:placeholder="searchMethod === 'elements' ? t('message.searchForElements') : t('message.searchForSchemas')"
>
<i v-if="!searchTerm" class="form-icon mdi mdi-magnify mdi-18px" />
<i
@ -50,11 +57,12 @@
</div>
<div class="workspace-explorebar-body" @click="explorebar.focus()">
<WorkspaceExploreBarSchema
v-for="db of workspace.structure"
v-for="db of filteredSchemas"
:key="db.name"
ref="schema"
:database="db"
:connection="connection"
:search-method="searchMethod"
@show-schema-context="openSchemaContext"
@show-table-context="openTableContext"
@show-misc-context="openMiscContext"
@ -181,6 +189,7 @@ const selectedSchema = ref('');
const selectedTable = ref(null);
const selectedMisc = ref(null);
const searchTerm = ref('');
const searchMethod: Ref<'elements' | 'schemas'> = ref('elements');
const workspace = computed(() => {
return getWorkspace(props.connection.uid);
@ -194,6 +203,13 @@ const customizations = computed(() => {
return workspace.value.customizations;
});
const filteredSchemas = computed(() => {
if (searchMethod.value === 'schemas')
return workspace.value.structure.filter(schema => schema.name.search(searchTerm.value) >= 0);
else
return workspace.value.structure;
});
watch(localWidth, (val: number) => {
clearTimeout(explorebarWidthInterval.value);
@ -403,6 +419,15 @@ const duplicateTable = async (payload: { schema: string; table: { name: string }
});
};
const toggleSearchMethod = () => {
searchTerm.value = '';
setSearchTerm(searchTerm.value);
if (searchMethod.value === 'elements')
searchMethod.value = 'schemas';
else
searchMethod.value = 'elements';
};
</script>
<style lang="scss">
@ -478,6 +503,8 @@ const duplicateTable = async (payload: { schema: string; table: { name: string }
justify-content: space-between;
font-size: 0.6rem;
height: 28px;
margin: 5px 0;
z-index: 10;
.has-icon-right {
width: 100%;
@ -491,6 +518,7 @@ const duplicateTable = async (payload: { schema: string; table: { name: string }
.form-input {
height: 1.2rem;
padding-left: 0.2rem;
border-radius:0 $border-radius $border-radius 0;
&:focus + .form-icon {
opacity: 0.9;
@ -505,7 +533,7 @@ const duplicateTable = async (payload: { schema: string; table: { name: string }
.workspace-explorebar-body {
width: 100%;
height: calc((100vh - 58px) - #{$excluding-size});
height: calc((100vh - 68px) - #{$excluding-size});
overflow: overlay;
padding: 0 0.1rem;
}

View File

@ -10,7 +10,7 @@
<i v-else class="icon mdi mdi-18px mdi-chevron-right" />
<i class="database-icon mdi mdi-18px mdi-database mr-1" />
<div class="">
<span>{{ database.name }}</span>
<span v-html="highlightWord(database.name, 'schemas')" />
<div
v-if="database.size"
class="schema-size tooltip tooltip-left mr-1"
@ -249,7 +249,8 @@ const { t } = useI18n();
const props = defineProps({
database: Object as Prop<WorkspaceStructure>,
connection: Object
connection: Object,
searchMethod: String as Prop<'elements' | 'schemas'>
});
const emit = defineEmits([
@ -282,29 +283,51 @@ const searchTerm = computed(() => {
});
const filteredTables = computed(() => {
return props.database.tables.filter(table => table.name.search(searchTerm.value) >= 0);
if (props.searchMethod === 'elements')
return props.database.tables.filter(table => table.name.search(searchTerm.value) >= 0);
else
return props.database.tables;
});
const filteredTriggers = computed(() => {
return props.database.triggers.filter(trigger => trigger.name.search(searchTerm.value) >= 0);
if (props.searchMethod === 'elements')
return props.database.triggers.filter(trigger => trigger.name.search(searchTerm.value) >= 0);
else
return props.database.triggers;
});
const filteredProcedures = computed(() => {
return props.database.procedures.filter(procedure => procedure.name.search(searchTerm.value) >= 0);
if (props.searchMethod === 'elements')
return props.database.procedures.filter(procedure => procedure.name.search(searchTerm.value) >= 0);
else
return props.database.procedures;
});
const filteredFunctions = computed(() => {
return props.database.functions.filter(func => func.name.search(searchTerm.value) >= 0);
if (props.searchMethod === 'elements')
return props.database.functions.filter(func => func.name.search(searchTerm.value) >= 0);
else
return props.database.functions;
});
const filteredTriggerFunctions = computed(() => {
return props.database.triggerFunctions
? props.database.triggerFunctions.filter(func => func.name.search(searchTerm.value) >= 0)
: [];
if (props.searchMethod === 'elements') {
return props.database.triggerFunctions
? props.database.triggerFunctions.filter(func => func.name.search(searchTerm.value) >= 0)
: [];
}
else {
return props.database.triggerFunctions
? props.database.triggerFunctions
: [];
}
});
const filteredSchedulers = computed(() => {
return props.database.schedulers.filter(scheduler => scheduler.name.search(searchTerm.value) >= 0);
if (props.searchMethod === 'elements')
return props.database.schedulers.filter(scheduler => scheduler.name.search(searchTerm.value) >= 0);
else
return props.database.schedulers;
});
const workspace = computed(() => {
@ -446,10 +469,10 @@ const setBreadcrumbs = (payload: Breadcrumb) => {
changeBreadcrumbs(payload);
};
const highlightWord = (string: string) => {
const highlightWord = (string: string, type = 'elements') => {
string = string.replaceAll('<', '&lt;').replaceAll('>', '&gt;');
if (searchTerm.value) {
if (searchTerm.value && props.searchMethod === type) {
const regexp = new RegExp(`(${searchTerm.value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
return string.replace(regexp, '<span class="text-primary">$1</span>');
}

View File

@ -63,14 +63,14 @@
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>
<span class="d-flex"><i class="mdi mdi-18px mdi-database-export 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>
<span class="d-flex"><i class="mdi mdi-18px mdi-database-import text-light pr-1" /> {{ t('word.import') }}</span>
</div>
<div
v-if="workspace.customizations.schemaEdit"

View File

@ -43,13 +43,25 @@
<span>{{ t('word.indexes') }}</span>
</button>
<button
class="btn btn-dark btn-sm"
class="btn btn-dark btn-sm mr-0"
:disabled="isSaving"
@click="showForeignModal"
>
<i class="mdi mdi-24px mdi-key-link mr-1" />
<span>{{ t('word.foreignKeys') }}</span>
</button>
<div class="divider-vert py-3" />
<button
v-if="workspace.customizations.tableDdl"
class="btn btn-dark btn-sm"
:disabled="isSaving"
@click="showDdlModal"
>
<i class="mdi mdi-24px mdi-code-tags mr-1" />
<span>{{ t('word.ddl') }}</span>
</button>
</div>
<div class="workspace-query-info">
<div class="d-flex" :title="t('word.schema')">
@ -169,6 +181,13 @@
@hide="hideForeignModal"
@foreigns-update="foreignsUpdate"
/>
<WorkspaceTabPropsTableDdlModal
v-if="isDdlModal"
:table="table"
:schema="schema"
:workspace="workspace"
@hide="hideDdlModal"
/>
</div>
</template>
@ -186,6 +205,7 @@ import BaseSelect from '@/components/BaseSelect.vue';
import WorkspaceTabPropsTableFields from '@/components/WorkspaceTabPropsTableFields.vue';
import WorkspaceTabPropsTableIndexesModal from '@/components/WorkspaceTabPropsTableIndexesModal.vue';
import WorkspaceTabPropsTableForeignModal from '@/components/WorkspaceTabPropsTableForeignModal.vue';
import WorkspaceTabPropsTableDdlModal from '@/components/WorkspaceTabPropsTableDdlModal.vue';
import { ipcRenderer } from 'electron';
import { useSettingsStore } from '@/stores/settings';
@ -221,6 +241,7 @@ const isLoading = ref(false);
const isSaving = ref(false);
const isIndexesModal = ref(false);
const isForeignModal = ref(false);
const isDdlModal = ref(false);
const originalFields: Ref<TableField[]> = ref([]);
const localFields: Ref<TableField[]> = ref([]);
const originalKeyUsage: Ref<TableForeign[]> = ref([]);
@ -649,6 +670,14 @@ const hideForeignModal = () => {
isForeignModal.value = false;
};
const showDdlModal = () => {
isDdlModal.value = true;
};
const hideDdlModal = () => {
isDdlModal.value = false;
};
const foreignsUpdate = (foreigns: TableForeign[]) => {
localKeyUsage.value = foreigns;
};

View File

@ -0,0 +1,70 @@
<template>
<ConfirmModal
:confirm-text="t('word.confirm')"
size="large"
class="options-modal"
:cancel-text="t('word.close')"
:hide-footer="true"
@hide="$emit('hide')"
>
<template #header>
<div class="d-flex">
<i class="mdi mdi-24px mdi-code-tags mr-1" />
<span class="cut-text">{{ t('word.ddl') }} "{{ table }}"</span>
</div>
</template>
<template #body>
<div class="pb-4">
<BaseTextEditor
ref="queryEditor"
v-model="createDdl"
editor-class="textarea-editor"
:read-only="true"
mode="sql"
/>
</div>
</template>
</ConfirmModal>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useNotificationsStore } from '@/stores/notifications';
import { useI18n } from 'vue-i18n';
import Tables from '@/ipc-api/Tables';
import ConfirmModal from '@/components/BaseConfirmModal.vue';
import BaseTextEditor from '@/components/BaseTextEditor.vue';
const { t } = useI18n();
const props = defineProps({
table: String,
schema: String,
workspace: Object
});
const createDdl = ref('');
defineEmits(['hide']);
const { addNotification } = useNotificationsStore();
onMounted(async () => {
try {
const { status, response } = await Tables.getTableDll({
uid: props.workspace.uid,
table: props.table,
schema: props.schema
});
if (status === 'success')
createDdl.value = response;
else
addNotification({ status: 'error', message: response });
}
catch (err) {
addNotification({ status: 'error', message: err.stack });
}
});
</script>

View File

@ -103,6 +103,9 @@
<li class="menu-item">
<a class="c-hand" @click="downloadTable('csv')">CSV</a>
</li>
<li class="menu-item">
<a class="c-hand" @click="downloadTable('php')">{{ t('message.phpArray') }}</a>
</li>
<li class="menu-item">
<a class="c-hand" @click="downloadTable('sql')">SQL INSERT</a>
</li>
@ -446,7 +449,7 @@ const clear = () => {
clearTabData();
};
const downloadTable = (format: 'csv' | 'json' | 'sql') => {
const downloadTable = (format: 'csv' | 'json' | 'sql' | 'php') => {
queryTable.value.downloadTable(format, `${props.tab.type}-${props.tab.index}`);
};

View File

@ -31,7 +31,7 @@
:class="{'active': resultsetIndex === index}"
@click="selectResultset(index)"
>
<a>{{ result.fields ? result.fields[0].table : '' }} ({{ result.rows.length }})</a>
<a>{{ result.fields ? result.fields[0]?.table : '' }} ({{ result.rows.length }})</a>
</li>
</ul>
<div ref="table" class="table table-hover">
@ -111,6 +111,47 @@
</div>
</template>
</ConfirmModal>
<ConfirmModal
v-if="chunkModalRequest"
@confirm="downloadTable('sql', chunkModalRequest as string, true)"
@hide="chunkModalRequest = false"
>
<template #header>
<div class="d-flex">
<i class="mdi mdi-24px mdi-file-export mr-1" />
<span class="cut-text">{{ t('message.sqlExportOptions') }}</span>
</div>
</template>
<template #body>
<div class="columns">
<label class="column col-12 h6 mb-2 cut-text">{{ t('message.targetTable') }}</label>
<div class="column col-12">
<input
v-model.number="sqlExportOptions.targetTable"
type="text"
class="form-input"
:placeholder="chunkModalRequest"
>
</div>
<label class="column col-12 h6 mb-2 mt-4 cut-text">{{ t('message.newInserStmtEvery') }}:</label>
<div class="column col-6">
<input
v-model.number="sqlExportOptions.sqlInsertAfter"
type="number"
class="form-input"
>
</div>
<div class="column col-6">
<BaseSelect
v-model="sqlExportOptions.sqlInsertDivider"
class="form-select"
:options="[{value: 'bytes', label: 'KiB'}, {value: 'rows', label: t('word.row', 2)}]"
/>
</div>
</div>
</template>
</ConfirmModal>
</div>
</template>
@ -128,6 +169,7 @@ import BaseVirtualScroll from '@/components/BaseVirtualScroll.vue';
import WorkspaceTabQueryTableRow from '@/components/WorkspaceTabQueryTableRow.vue';
import TableContext from '@/components/WorkspaceTabQueryTableContext.vue';
import ConfirmModal from '@/components/BaseConfirmModal.vue';
import BaseSelect from '@/components/BaseSelect.vue';
import * as moment from 'moment';
import { useI18n } from 'vue-i18n';
import { TableField, QueryResult } from 'common/interfaces/antares';
@ -135,6 +177,7 @@ import { TableUpdateParams } from 'common/interfaces/tableApis';
import { jsonToSqlInsert } from 'common/libs/sqlUtils';
import { unproxify } from '@/libs/unproxify';
import faker from '@faker-js/faker';
import * as json2php from 'json2php';
const { t } = useI18n();
@ -179,9 +222,16 @@ const scrollElement = ref(null);
const rowHeight = ref(23);
const selectedField = ref(null);
const isEditingRow = ref(false);
const chunkModalRequest: Ref<false | string> = ref(false);
const sqlExportOptions = ref({
sqlInsertAfter: 250,
sqlInsertDivider: 'bytes' as 'bytes' | 'rows',
targetTable: ''
});
const workspaceSchema = computed(() => getWorkspace(props.connUid).breadcrumbs.schema);
const workspaceClient = computed(() => getWorkspace(props.connUid).client);
const customizations = computed(() => getWorkspace(props.connUid).customizations);
const primaryField = computed(() => {
const primaryFields = fields.value.filter(field => field.key === 'pri');
@ -219,7 +269,7 @@ const sortedResults = computed(() => {
return localResults.value;
});
const resultsWithRows = computed(() => props.results.filter(result => result.rows));
const resultsWithRows = computed(() => props.results.filter(result => result.rows.length));
const fields = computed(() => resultsWithRows.value.length ? resultsWithRows.value[resultsetIndex.value].fields : []);
const keyUsage = computed(() => resultsWithRows.value.length ? resultsWithRows.value[resultsetIndex.value].keys : []);
@ -438,20 +488,17 @@ const copyRow = (format: string) => {
if (format === 'json')
navigator.clipboard.writeText(JSON.stringify(contentToCopy));
else if (format === 'sql') {
const sqlInserts = [];
if (!Array.isArray(contentToCopy)) contentToCopy = [contentToCopy];
for (const row of contentToCopy) {
sqlInserts.push(jsonToSqlInsert({
json: row,
client: workspaceClient.value,
fields: fieldsObj.value as {
[key: string]: {type: string; datePrecision: number};
},
table: getTable(resultsetIndex.value)
}));
}
navigator.clipboard.writeText(sqlInserts.join('\n'));
const sqlInserts = jsonToSqlInsert({
json: contentToCopy,
client: workspaceClient.value,
fields: fieldsObj.value as {
[key: string]: {type: string; datePrecision: number};
},
table: getTable(resultsetIndex.value)
});
navigator.clipboard.writeText(sqlInserts);
}
else if (format === 'csv') {
const csv = [];
@ -482,6 +529,12 @@ const copyRow = (format: string) => {
navigator.clipboard.write(data);
}
else if (format === 'php') {
if (!Array.isArray(contentToCopy)) contentToCopy = [contentToCopy];
const printer = json2php.make({ linebreak: '\n', indent: '\t', shortArraySyntax: true });
const phpString = printer(contentToCopy);
navigator.clipboard.writeText(phpString);
}
};
const createHtmlTable = (tableData: Array<string[]>) => {
@ -665,22 +718,36 @@ const selectResultset = (index: number) => {
resultsetIndex.value = index;
};
const downloadTable = (format: 'csv' | 'json' | 'sql', table: string) => {
const downloadTable = (format: 'csv' | 'json' | 'sql' | 'php', table: string, chunks = false) => {
if (!sortedResults.value) return;
const rows = JSON.parse(JSON.stringify(sortedResults.value)).map((row: any) => {
delete row._antares_id;
return row;
if (format === 'sql' && !chunks && customizations.value.exportByChunks) {
sqlExportOptions.value = {
sqlInsertAfter: 250,
sqlInsertDivider: 'bytes' as 'bytes' | 'rows',
targetTable: ''
};
chunkModalRequest.value = table;
return;
}
else
chunkModalRequest.value = false;
const rows = sortedResults.value.map((row: any) => {
const clonedRow = { ...row };
delete clonedRow._antares_id;
return clonedRow;
});
exportRows({
type: format,
content: rows,
fields: fieldsObj.value as {
fields: JSON.parse(JSON.stringify(fieldsObj.value)) as {
[key: string]: {type: string; datePrecision: number};
},
client: workspaceClient.value,
table
table,
sqlOptions: chunks ? { ...sqlExportOptions.value }: null
});
};

View File

@ -31,6 +31,11 @@
<i class="mdi mdi-18px mdi-table-row text-light pr-1" /> {{ t('word.row', selectedRows.length) }} (CSV)
</span>
</div>
<div class="context-element" @click="copyRow('php')">
<span class="d-flex">
<i class="mdi mdi-18px mdi-table-row text-light pr-1" /> {{ t('word.row', selectedRows.length) }} (PHP)
</span>
</div>
<div class="context-element" @click="copyRow('sql')">
<span class="d-flex">
<i class="mdi mdi-18px mdi-table-row text-light pr-1" /> {{ t('word.row', selectedRows.length) }} (SQL INSERT)

View File

@ -73,6 +73,7 @@
<button
class="btn btn-sm"
:title="t('word.filter')"
:disabled="isQuering"
:class="{'btn-primary': isSearch, 'btn-dark': !isSearch}"
@click="isSearch = !isSearch"
>
@ -105,6 +106,9 @@
<li class="menu-item">
<a class="c-hand" @click="downloadTable('csv')">CSV</a>
</li>
<li class="menu-item">
<a class="c-hand" @click="downloadTable('php')">{{ t('message.phpArray') }}</a>
</li>
<li class="menu-item">
<a class="c-hand" @click="downloadTable('sql')">SQL INSERT</a>
</li>
@ -145,6 +149,14 @@
/>
<div class="workspace-query-results p-relative column col-12">
<BaseLoader v-if="isQuering" />
<div v-if="!isQuering && !results[0]?.rows.length" class="empty">
<div class="empty-icon">
<i class="mdi mdi-48px mdi-island" />
</div>
<p class="h4 empty-subtitle">
{{ t('message.noResultsPresent') }}
</p>
</div>
<WorkspaceTabQueryTable
v-if="results"
ref="queryTable"
@ -258,7 +270,7 @@ const keyUsage = computed(() => {
});
const getTableData = async () => {
if (!props.table || !props.isSelected) return;
if (!props.table || !props.isSelected || isQuering.value) return;
isQuering.value = true;
// if table changes clear cached values
@ -365,7 +377,7 @@ const setRefreshInterval = () => {
}
};
const downloadTable = (format: 'csv' | 'json' | 'sql') => {
const downloadTable = (format: 'csv' | 'json' | 'sql' | 'php') => {
queryTable.value.downloadTable(format, props.table);
};
@ -381,6 +393,7 @@ const resizeScroller = () => {
const updateFilters = (clausoles: TableFilterClausole[]) => {
filters.value = clausoles;
results.value = [];
getTableData();
};

View File

@ -0,0 +1,66 @@
<template>
<BaseContextMenu
:context-event="props.contextEvent"
@close-context="closeContext"
>
<div class="context-element" @click.stop="closeAllTabs">
<span class="d-flex"><i class="mdi mdi-18px mdi-asterisk text-light pr-1" /> {{ t('message.closeAllTabs') }}</span>
</div>
<div class="context-element" @click.stop="closeOtherTabs">
<span class="d-flex"><i class="mdi mdi-18px mdi-not-equal text-light pr-1" /> {{ t('message.closeOtherTabs') }}</span>
</div>
<div class="context-element" @click.stop="closeLeftTabs">
<span class="d-flex"><i class="mdi mdi-18px mdi-less-than text-light pr-1" /> {{ t('message.closeTabsToLeft') }}</span>
</div>
<div class="context-element" @click.stop="closeRightTabs">
<span class="d-flex"><i class="mdi mdi-18px mdi-greater-than text-light pr-1" /> {{ t('message.closeTabsToRight') }}</span>
</div>
</BaseContextMenu>
</template>
<script setup lang="ts">
import BaseContextMenu from '@/components/BaseContextMenu.vue';
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
const props = defineProps({
contextEvent: MouseEvent,
selectedTab: Object
});
const emit = defineEmits([
'close-context',
'close-all-tabs',
'close-other-tabs',
'close-to-left',
'close-to-right'
]);
const closeContext = () => {
emit('close-context');
};
const closeAllTabs = () => {
emit('close-all-tabs');
closeContext();
};
const closeLeftTabs = () => {
emit('close-to-left');
closeContext();
};
const closeRightTabs = () => {
emit('close-to-right');
closeContext();
};
const closeOtherTabs = () => {
emit('close-other-tabs');
closeContext();
};
</script>

View File

@ -149,7 +149,8 @@ export const enUS = {
color: 'Color',
label: 'Label',
icon: 'Icon',
resultsTable: 'Results table'
resultsTable: 'Results table',
ddl: 'DDL'
},
message: {
appWelcome: 'Welcome to Antares SQL Client!',
@ -337,7 +338,17 @@ export const enUS = {
executeSelectedQuery: 'Execute selected query',
defaultCopyType: 'Default copy type',
showTableSize: 'Show table size in sidebar',
showTableSizeDescription: 'MySQL/MariaDB only. Enable this option may affects performance on schema with many tables.'
showTableSizeDescription: 'MySQL/MariaDB only. Enable this option may affects performance on schema with many tables.',
searchForSchemas: 'Search for schemas',
switchSearchMethod: 'Switch search method',
noResultsPresent: 'No results present',
sqlExportOptions: 'SQL export options',
targetTable: 'Target table',
phpArray: 'PHP array',
closeAllTabs: 'Close all tabs',
closeOtherTabs: 'Close other tabs',
closeTabsToLeft: 'Close tabs to the left',
closeTabsToRight: 'Close tabs to the right'
},
faker: {
address: 'Address',

View File

@ -11,6 +11,7 @@ import { jaJP } from './ja-JP';
import { zhCN } from './zh-CN';
import { ruRU } from './ru-RU';
import { idID } from './id-ID';
import { koKR } from './ko-KR';
const messages = {
'en-US': enUS,
@ -24,7 +25,8 @@ const messages = {
'ja-JP': jaJP,
'zh-CN': zhCN,
'ru-RU': ruRU,
'id-ID': idID
'id-ID': idID,
'ko-KR': koKR
};
type NestedPartial<T> = {

View File

@ -22,7 +22,7 @@ export const itIT = {
settings: 'Impostazioni',
general: 'Generale',
themes: 'Temi',
update: 'Aggiornamento',
update: 'Aggiorna',
about: 'Informazioni',
language: 'Lingua',
version: 'Versione',
@ -143,7 +143,13 @@ export const itIT = {
pin: 'Fissa',
unpin: 'Sgancia',
console: 'Console',
shortcuts: 'Scorciatoie'
shortcuts: 'Scorciatoie',
folder: 'Cartella | Cartelle',
appearence: 'Aspetto',
color: 'Colore',
label: 'Etichetta',
icon: 'Icona',
resultsTable: 'Tabella risultati'
},
message: {
appWelcome: 'Benvenuto in Antares SQL Client!',
@ -322,7 +328,19 @@ export const itIT = {
clearQuery: 'Pulisci query',
openFilter: 'Apri il filtro',
nextResultsPage: 'Prossima pagina risultati',
previousResultsPage: 'Pagina risultati precedente'
previousResultsPage: 'Pagina risultati precedente',
fillCell: 'Riempi cella',
editFolder: 'Modifica cartella',
folderName: 'Nome cartella',
deleteFolder: 'Cancella cartella',
editConnectionAppearence: 'Modifica aspetto connessione',
executeSelectedQuery: 'Esegui la query selezionata',
defaultCopyType: 'Tipo di copia default',
showTableSize: 'Mostra dimensioni tabella nella sidebar',
showTableSizeDescription: 'Solo MySQL/MariaDB. Abilitare questa opzione può compromettere le performance in schemi con molte tabelle.',
searchForSchemas: 'Cerca schemi',
switchSearchMethod: 'Cambia metodo di ricerca',
noResultsPresent: 'Nessun risultato presente'
},
faker: {
address: 'Indirizzo',
@ -388,6 +406,7 @@ export const itIT = {
collation: 'Confronto',
engine: 'Motore',
past: 'Passato',
now: 'Adesso',
future: 'Futuro',
between: 'Tra',
recent: 'Recente',

509
src/renderer/i18n/ko-KR.ts Normal file
View File

@ -0,0 +1,509 @@
export const koKR = {
word: {
edit: '편집',
save: '저장',
close: '닫기',
delete: '삭제',
confirm: '확인',
cancel: '취소',
send: '보내기',
connectionName: '연결 이름',
client: '클라이언트',
hostName: '호스트 이름',
port: '포트',
user: '사용자',
password: '비밀번호',
credentials: '자격 증명',
connect: '연결',
connected: '연결됨',
disconnect: '연결 해제',
disconnected: '연결 해제됨',
refresh: '새로고침',
settings: '설정',
general: '일반',
themes: '테마',
update: '업데이트',
about: '정보',
language: '언어',
version: '버전',
donate: '기부',
run: '실행',
schema: '스키마',
results: '결과',
size: '크기',
seconds: '초',
type: '유형',
mimeType: 'Mime 타입',
download: '다운로드',
add: '추가',
data: '데이터',
properties: '속성',
insert: '삽입',
connecting: '연결 중',
name: '이름',
collation: 'Collation',
clear: '초기화',
options: '옵션',
autoRefresh: '자동 새로고침',
indexes: '인덱스',
foreignKeys: '외래 키',
length: '길이',
unsigned: 'Unsigned',
default: '기본값',
comment: '설명',
key: '키 | 키들',
order: '순서',
expression: '식',
autoIncrement: '자동 증가',
engine: '엔진',
field: '필드 | 필드들',
approximately: '대략',
total: '전체',
table: '테이블',
discard: '취소',
stay: '계속하기',
author: '작성자',
light: '라이트',
dark: '다크',
autoCompletion: '자동 완성',
application: '애플리케이션',
editor: '편집기',
view: '보기',
definer: '정의자',
algorithm: '알고리즘',
trigger: '트리거 | 트리거들',
storedRoutine: '프로시저 | 프로시저들',
scheduler: '스케줄러 | 스케줄러들',
event: '이벤트',
parameters: '매개변수',
function: '함수 | 함수들',
deterministic: '결정론적',
context: '컨텍스트',
export: '내보내기',
import: '가져오기',
returns: '반환',
timing: '타이밍',
state: '상태',
execution: '실행',
starts: '시작',
ends: '종료',
ssl: 'SSL',
privateKey: '개인 키',
certificate: '인증서',
caCertificate: 'CA 인증서',
ciphers: '암호화',
upload: '업로드',
browse: '찾아보기',
faker: 'Faker',
content: '컨텐츠',
cut: '잘라내기',
copy: '복사',
paste: '붙여넣기',
tools: '도구',
variables: '변수',
processes: '프로세스',
database: '데이터베이스',
scratchpad: '스크래치패드',
array: '배열',
changelog: '변경 로그',
format: '형식',
sshTunnel: 'SSH 터널',
structure: '구조',
small: '작음',
medium: '중간',
large: '큼',
row: '행 | 행들',
cell: '셀 | 셀들',
triggerFunction: '트리거 함수 | 트리거 함수들',
all: '모두',
duplicate: '복제',
routine: '루틴',
new: '새로 만들기',
history: '기록',
select: '선택',
passphrase: '암호',
filter: '필터',
change: '변경',
views: '뷰',
triggers: '트리거',
routines: '루틴',
functions: '함수',
schedulers: '스케줄러',
includes: '포함',
drop: '삭제',
completed: '완료됨',
aborted: '중단됨',
disabled: '비활성화됨',
enable: '활성화',
disable: '비활성화',
commit: '커밋',
rollback: '롤백',
connectionString: '연결 문자열',
contributors: '기여자',
pin: '고정',
unpin: '고정 해제',
console: '콘솔',
shortcuts: '바로가기',
folder: '폴더 | 폴더들',
appearence: '외형',
color: '색상',
label: '라벨',
icon: '아이콘',
resultsTable: '결과 테이블'
},
message: {
appWelcome: 'Antares SQL 클라이언트에 오신 것을 환영합니다!',
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: '0 채우기',
customValue: '사용자 지정 값',
onUpdate: '업데이트 시',
deleteField: '필드 삭제',
createNewIndex: '새 인덱스 생성',
addToIndex: '인덱스에 추가',
createNewTable: '새 테이블 생성',
emptyTable: '테이블 비우기',
deleteTable: '테이블 삭제',
emptyCorfirm: '비우시겠습니까',
unsavedChanges: '저장되지 않은 변경사항',
discardUnsavedChanges: '저장되지 않은 변경사항이 있습니다. 탭을 닫으면 이러한 변경사항이 삭제됩니다.',
thereAreNoIndexes: '인덱스가 없습니다.',
thereAreNoForeign: '외래 키가 없습니다.',
createNewForeign: '새로운 외래 키 생성',
referenceTable: '참조 테이블',
referenceField: '참조 필드',
foreignFields: '외래 필드',
invalidDefault: '잘못된 기본값',
onDelete: '삭제 시',
applicationTheme: '애플리케이션 테마',
editorTheme: '편집기 테마',
wrapLongLines: '긴 줄 바꿈',
selectStatement: 'SELECT 문',
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: '마크다운 지원',
plantATree: '나무 심기',
dataTabPageSize: '데이터 탭 페이지 크기',
enableSsh: 'SSH 활성화',
pageNumber: '페이지 번호',
duplicateTable: '테이블 복제',
noOpenTabs: '열린 탭이 없습니다.',
noSchema: '스키마 없음',
restorePreviourSession: '이전 세션 복원',
runQuery: '쿼리 실행',
thereAreNoTableFields: '테이블 필드가 없습니다',
newTable: '새 테이블',
newView: '새 뷰',
newTrigger: '새 트리거',
newRoutine: '새 루틴',
newFunction: '새 함수',
newScheduler: '새 스케줄러',
newTriggerFunction: '새 트리거 함수',
thereIsNoQueriesYet: '아직 쿼리가 없습니다',
searchForQueries: '쿼리 검색',
killProcess: '프로세스 종료',
closeTab: '탭 닫기',
exportSchema: '스키마 내보내기',
importSchema: '스키마 가져오기',
directoryPath: '디렉터리 경로',
newInserStmtEvery: '마다 새 INSERT 문',
processingTableExport: '{table} 처리 중',
fechingTableExport: '{table} 데이터 가져오는 중',
writingTableExport: '{table} 데이터 쓰는 중',
checkAllTables: '모든 테이블 선택',
uncheckAllTables: '모든 테이블 선택 취소',
goToDownloadPage: '다운로드 페이지로 이동',
readOnlyMode: '읽기 전용 모드',
killQuery: '쿼리 종료',
insertRow: '행 삽입 | 행 삽입',
commitMode: '커밋 모드',
autoCommit: '자동 커밋',
manualCommit: '수동 커밋',
actionSuccessful: '{action} 성공',
importQueryErrors: '경고: {n}개의 오류 발생 | 경고: {n}개의 오류 발생',
executedQueries: '{n}개의 쿼리 실행 | {n}개의 쿼리 실행',
ourputFormat: '출력 형식',
singleFile: '단일 {ext} 파일',
zipCompressedFile: 'ZIP 압축 {ext} 파일',
disableBlur: 'blur 비활성화',
untrustedConnection: '신뢰할 수 없는 연결',
missingOrIncompleteTranslation: '누락 혹은 불완전한 번역?',
findOutHowToContribute: '기여 방법 알아보기',
disableFKChecks: '외래 키 검사 비활성화',
allConnections: '모든 연결',
searchForConnections: '연결 검색',
disableScratchpad: '스크래치패드 비활성화',
reportABug: '버그 신고',
nextTab: '다음 탭',
previousTab: '이전 탭',
selectTabNumber: '{param}번 탭 선택',
toggleConsole: '콘솔 전환',
addShortcut: '단축키 추가',
editShortcut: '단축키 편집',
deleteShortcut: '단축키 삭제',
restoreDefaults: '기본값 복원',
restoreDefaultsQuestion: '기본값으로 복원하시겠습니까?',
registerAShortcut: '단축키 등록',
invalidShortcutMessage: '유효하지 않은 조합입니다. 계속 입력하세요.',
shortcutAlreadyExists: '이미 존재하는 단축키입니다.',
saveContent: '내용 저장',
openAllConnections: '모든 연결 열기',
openSettings: '설정 열기',
openScratchpad: '스크래치패드 열기',
runOrReload: '실행 또는 다시 로드',
formatQuery: '쿼리 형식',
queryHistory: '쿼리 기록',
clearQuery: '쿼리 지우기',
openFilter: '필터 열기',
nextResultsPage: '다음 결과 페이지',
previousResultsPage: '이전 결과 페이지',
fillCell: '셀 채우기',
editFolder: '폴더 수정',
folderName: '폴더 이름',
deleteFolder: '폴더 삭제',
editConnectionAppearence: '연결 형태 수정',
executeSelectedQuery: '선택한 쿼리 실행',
defaultCopyType: '기본 복사 유형',
showTableSize: '사이드바에 테이블 크기 표시',
showTableSizeDescription: 'MySQL/MariaDB 전용입니다. 이 옵션을 사용하면 많은 테이블이 있는 스키마의 성능에 영향을 줄 수 있습니다.',
searchForSchemas: '스키마 검색',
switchSearchMethod: '검색 방법 전환'
},
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: '기본 방위',
ordinalDirection: '서수 방위',
nearbyGPSCoordinate: '인근 GPS 좌표',
timeZone: '시간대',
color: '색상',
department: '부서',
productName: '제품 이름',
price: '가격',
productAdjective: '제품 형용사',
productMaterial: '제품 재질',
product: '제품',
productDescription: '제품 설명',
suffixes: '접미사',
companyName: '회사 이름',
companySuffix: '회사 접미사',
catchPhrase: '캐치프레이즈',
bs: 'BS',
catchPhraseAdjective: '캐치프레이즈 형용사',
catchPhraseDescriptor: '캐치프레이즈 서술어',
catchPhraseNoun: '캐치프레이즈 명사',
bsAdjective: 'BS 형용사',
bsBuzz: 'BS 버저',
bsNoun: 'BS 명사',
column: '열',
type: '타입',
collation: 'Collation',
engine: '엔진',
past: '과거',
now: '현재',
future: '미래',
between: '사이',
recent: '최근',
soon: '곧',
month: '월',
weekday: '요일',
account: '계정',
accountName: '계정 이름',
routingNumber: '라우팅 번호',
mask: '마스크',
amount: '금액',
transactionType: '거래 유형',
currencyCode: '통화 코드',
currencyName: '통화 이름',
currencySymbol: '통화 기호',
bitcoinAddress: '비트코인 주소',
litecoinAddress: '라이트코인 주소',
creditCardNumber: '신용카드',
creditCardCVV: '신용카드 CVV',
ethereumAddress: '이더리움 주소',
iban: '국제 은행 계좌 번호',
bic: '은행 식별자 코드',
transactionDescription: '거래 설명',
branch: '지점',
commitEntry: '커밋 항목',
commitMessage: '커밋 메시지',
commitSha: '커밋 SHA',
shortSha: '짧은 SHA',
abbreviation: '약어',
adjective: '형용사',
noun: '명사',
verb: '동사',
ingverb: '진행형 동사',
phrase: '구문',
avatar: '아바타',
email: '이메일',
exampleEmail: '예시 이메일',
userName: '사용자 이름',
protocol: '프로토콜',
url: 'URL',
domainName: '도메인 이름',
domainSuffix: '도메인 접미사',
domainWord: '도메인 단어',
ip: 'IP',
ipv6: 'IPv6',
userAgent: '사용자 에이전트',
mac: 'MAC',
password: '비밀번호',
word: '단어',
words: '단어들',
sentence: '문장',
slug: '슬러그',
sentences: '문장들',
paragraph: '문단',
paragraphs: '문단들',
text: '텍스트',
lines: '라인',
genre: '장르',
firstName: '이름',
lastName: '성',
middleName: '중간 이름',
findName: '전체 이름',
jobTitle: '직함',
gender: '성별',
prefix: '접두사',
suffix: '접미사',
title: '타이틀',
jobDescriptor: '직무 설명',
jobArea: '직무 영역',
jobType: '직무 유형',
phoneNumber: '전화번호',
phoneNumberFormat: '전화번호 형식',
phoneFormats: '전화번호 형식들',
number: '숫자',
float: 'float',
arrayElement: '배열 요소',
arrayElements: '배열 요소들',
objectElement: '객체 요소',
uuid: 'UUID',
boolean: '부울',
image: '이미지',
locale: '로케일',
alpha: '알파벳',
alphaNumeric: '알파벳 및 숫자',
hexaDecimal: '16진수',
fileName: '파일 이름',
commonFileName: '공통 파일 이름',
mimeType: 'MIME 타입',
commonFileType: '공통 파일 유형',
commonFileExt: '공통 파일 확장자',
fileType: '파일 유형',
fileExt: '파일 확장자',
directoryPath: '디렉토리 경로',
filePath: '파일 경로',
semver: '유의적 버전',
manufacturer: '제조사',
model: '모델',
fuel: '연료',
vin: '차량식별번호'
}
};

View File

@ -14,12 +14,12 @@ export const ruRU = {
user: 'Пользователь',
password: 'Пароль',
credentials: 'Полномочия',
connect: 'Подключить',
connect: 'Подключиться',
connected: 'Подключено',
disconnect: 'Отключить',
disconnect: 'Отключиться',
disconnected: 'Отключено',
refresh: 'Обновить',
settings: 'Настройка',
settings: 'Настройки',
general: 'Общие',
themes: 'Темы',
update: 'Обновить',
@ -27,9 +27,9 @@ export const ruRU = {
language: 'Язык',
version: 'Версия',
donate: 'Пожертвование',
run: 'Запуск',
run: 'Выполнить',
schema: 'Схема',
results: 'Результаты',
results: 'Отображено',
size: 'Размер',
seconds: 'Секунды',
type: 'Тип',
@ -42,17 +42,17 @@ export const ruRU = {
connecting: 'Соединение',
name: 'Название',
collation: 'Сопоставление',
clear: 'Очистить',
clear: 'Удалить',
options: 'Опции',
autoRefresh: 'Авто-обновление',
indexes: 'Индексы',
foreignKeys: 'Внешние ключи',
length: 'Длина',
unsigned: 'Неподписанный',
unsigned: 'Беззнаковое',
default: 'По умолчанию',
comment: 'Комментарий',
key: 'Ключ | Ключи',
order: 'Заказ',
order: 'Порядок',
expression: 'Выражение',
autoIncrement: 'Авто-увеличение',
engine: 'Движок',
@ -60,19 +60,19 @@ export const ruRU = {
approximately: 'Примерно',
total: 'Всего',
table: 'Таблица',
discard: 'Отказать',
discard: 'Отказаться',
stay: 'Оставить',
author: 'Автор',
light: 'Светлая',
dark: 'Темная',
autoCompletion: 'Авто-дополнение',
application: 'Приложение',
editor: 'Реадктор',
view: 'Просмотр',
editor: 'Редактор',
view: 'Представление',
definer: 'Определитель',
algorithm: 'Алгоритм',
trigger: 'Триггер | Триггеры',
storedRoutine: 'Сохраненная процедура | Сохраненные процедуры',
storedRoutine: 'Хранимая процедура | Хранимые процедуры',
scheduler: 'Планировщик | Планировщики',
event: 'Событие',
parameters: 'Параметры',
@ -85,8 +85,8 @@ export const ruRU = {
timing: 'Сроки',
state: 'Состояние',
execution: 'Выполнение',
starts: 'Начинает',
ends: 'Заканчивает',
starts: 'Начало',
ends: 'Конец',
ssl: 'SSL',
privateKey: 'Закрытый ключ',
certificate: 'Сертификат',
@ -94,7 +94,7 @@ export const ruRU = {
ciphers: 'Шифры',
upload: 'Загрузки',
browse: 'Обзор',
faker: 'Faker',
faker: 'Генератор данных',
content: 'Содержимое',
cut: 'Вырезать',
copy: 'Копировать',
@ -106,7 +106,7 @@ export const ruRU = {
scratchpad: 'Заметки',
array: 'Массив',
changelog: 'Журнал изменений',
format: 'Формат',
format: 'Отформатировать',
sshTunnel: 'SSH туннель',
structure: 'Структура',
small: 'Малый',
@ -117,47 +117,58 @@ export const ruRU = {
triggerFunction: 'Функция запуска | Функции запуска',
all: 'Все',
duplicate: 'Дубликат',
routine: 'Порядок',
routine: 'Хранимая процедура',
new: 'Новый',
history: 'История',
select: 'Выбрать',
passphrase: 'Кодовая фраза',
filter: 'Фильтр',
change: 'Изменить',
views: 'Просмотры',
views: 'Представления',
triggers: 'Триггеры',
routines: 'Порядок',
routines: 'Хранимые процедуры',
functions: 'Функции',
schedulers: 'Планировщики',
includes: 'Включает',
drop: 'Сбросить',
includes: 'Включая',
drop: 'Удалить',
completed: 'Завершено',
aborted: 'Aborted',
disabled: 'Прервано',
aborted: 'Прервано',
disabled: 'Отключено',
enable: 'Включить',
disable: 'Выключить',
commit: 'Подтвердить',
rollback: 'Отмена',
rollback: 'Откатить',
connectionString: 'Строка подключения',
contributors: 'Участники'
contributors: 'Участники',
pin: 'Закрепить',
unpin: 'Открепить',
console: 'Консоль',
shortcuts: 'Горячие клавиши',
folder: 'Директория | Директории',
appearence: 'Внешний вид',
color: 'Цвет',
label: 'Метка',
icon: 'Иконка',
resultsTable: 'Таблица с результатом',
ddl: 'DDL'
},
message: {
appWelcome: 'Приветсвуем в SQL клиенте Antares!',
appWelcome: 'Приветствуем в SQL клиенте Antares!',
appFirstStep: 'Ваш первый шаг: создать новое подключение с БД.',
addConnection: 'Добавить подключение',
createConnection: 'Создать подключение',
createNewConnection: 'Созадть новое подключение',
createNewConnection: 'Создать новое подключение',
askCredentials: 'Спрашивать учетные данные',
testConnection: 'Тестирование подключения',
editConnection: 'Редактирование подключения',
testConnection: 'Тест подключения',
editConnection: 'Редактировать подключение',
deleteConnection: 'Удалить подключение',
deleteCorfirm: 'Подтверждаете ли вы отмену',
deleteCorfirm: 'Подтверждаете ли вы удаление',
connectionSuccessfullyMade: 'Соединение успешно установлено!',
madeWithJS: 'Сделано с 💛 и JavaScript!',
checkForUpdates: 'Проверить обновления',
noUpdatesAvailable: 'Обновлений не найдено',
checkingForUpdate: роверить обновления',
checkFailure: 'Проверка не удалась, пожалуйста, попробуйте позже',
checkingForUpdate: оиск обновлений',
checkFailure: 'Не удалось проверить обновления, пожалуйста, попробуйте позже',
updateAvailable: 'Доступно обновление',
downloadingUpdate: 'Скачать обновление',
updateDownloaded: 'Обновление скачано',
@ -174,10 +185,10 @@ export const ruRU = {
affectedRows: 'Задействовано строк',
createNewDatabase: 'Создать новую БД',
databaseName: 'Название БД',
serverDefault: 'Сервер по умолчанию',
serverDefault: 'По-умолчанию на сервере',
deleteDatabase: 'Удалить БД',
editDatabase: 'Редактировать БД',
clearChanges: 'Очистить изменения',
clearChanges: 'Удалить изменения',
addNewField: 'Добавить новое поле',
manageIndexes: 'Управление индексами',
manageForeignKeys: 'Управление внешними ключами',
@ -189,7 +200,7 @@ export const ruRU = {
createNewIndex: 'Создать новый индекс',
addToIndex: 'Добавить индекс',
createNewTable: 'Создать новую таблицу',
emptyTable: 'Пустая таблица',
emptyTable: 'Очистить таблицу',
deleteTable: 'Удалить таблицу',
emptyCorfirm: 'Подтверждаете очистку?',
unsavedChanges: 'Несохраненные изменения',
@ -203,23 +214,23 @@ export const ruRU = {
invalidDefault: 'Недопустимое значение',
onDelete: 'При удалении',
applicationTheme: 'Тема приложения',
editorTheme: 'Редактировать Тему',
editorTheme: 'Редактировать тему',
wrapLongLines: 'Перенос длинных строк',
selectStatement: 'Оператор выбора',
triggerStatement: 'Оператор триггера',
sqlSecurity: 'SQL безопасность',
updateOption: 'Опции обновления',
deleteView: 'Удалить просмотр',
createNewView: 'Создать новый просмотр',
deleteView: 'Удалить представление',
createNewView: 'Создать новое представление',
deleteTrigger: 'Удалить триггер',
createNewTrigger: 'Создать новый триггер',
currentUser: 'Текущий пользователь',
routineBody: 'Routine body',
routineBody: 'Тело процедуры',
dataAccess: 'Доступ к данным',
thereAreNoParameters: 'Там нет никаких параметров',
thereAreNoParameters: 'Параметры отсутствуют',
createNewParameter: 'Создать новый параметр',
createNewRoutine: 'Создание новой сохраненной процедуры',
deleteRoutine: 'Удаление сохраненной процедуры',
createNewRoutine: 'Создание новой хранимой процедуры',
deleteRoutine: 'Удаление хранимой процедуры',
functionBody: 'Тело функции',
createNewFunction: 'Создать новую функцию',
deleteFunction: 'Удалить функцию',
@ -248,37 +259,37 @@ export const ruRU = {
dataTabPageSize: 'Размер страницы вкладки ДАННЫЕ',
enableSsh: 'Включить SSH',
pageNumber: 'Номер страницы',
duplicateTable: 'Дубликат таблицы',
duplicateTable: 'Клонировать таблицу',
noOpenTabs: 'Открытых вкладок нет, перейдите по левой панели или:',
noSchema: 'Нет схемы',
restorePreviourSession: 'Восстановить предыдущую сессию',
runQuery: 'Запуск очереди',
runQuery: 'Выполнить запрос',
thereAreNoTableFields: 'В таблице нет полей',
newTable: 'Новая таблица',
newView: 'Новый просмотр',
newView: 'Новое представление',
newTrigger: 'Новый триггер',
newRoutine: 'New routine',
newRoutine: 'Новая хранимая процедура',
newFunction: 'Новая функция',
newScheduler: 'Новый планировщик',
newTriggerFunction: 'Новая функция триггера',
thereIsNoQueriesYet: 'Пока нет никаких запросов',
thereIsNoQueriesYet: 'Запросы пока отсутствуют',
searchForQueries: 'Поиск по запросам',
killProcess: 'Убить процесс',
closeTab: 'Закрыть вкладку',
exportSchema: 'Экспорт схемы',
importSchema: 'Импорт схемы',
directoryPath: 'Путь к каталогу',
newInserStmtEvery: 'New INSERT statement every',
newInserStmtEvery: 'Новый INSERT оператор для каждых',
processingTableExport: 'Обработка {table}',
fechingTableExport: 'Получение данных с {table}',
fechingTableExport: 'Получение данных из {table}',
writingTableExport: 'Запись данных в {table}',
checkAllTables: 'Проверить все таблицы',
checkAllTables: 'Выбрать у всех таблицы',
uncheckAllTables: 'Убрать со всех таблиц',
goToDownloadPage: 'Перейти на страницу для загрузки',
goToDownloadPage: 'Перейти на страницу загрузки',
readOnlyMode: 'Режим только чтение',
killQuery: 'Убить запрос',
insertRow: 'Вставить строку | Вставить строки',
commitMode: 'Режим подтверждения',
commitMode: 'Режим подтверждения транзакций',
autoCommit: 'Авто-подтверждение',
manualCommit: 'Ручное подтверждение',
actionSuccessful: '{action} успешно',
@ -290,7 +301,54 @@ export const ruRU = {
disableBlur: 'Отключить размытие',
untrustedConnection: 'Ненадежное соединение',
missingOrIncompleteTranslation: 'Отсутствующий или неполный перевод?',
findOutHowToContribute: 'Узнайте, как внести свой вклад'
findOutHowToContribute: 'Узнайте, как внести свой вклад',
disableFKChecks: 'Отключить проверку внешних ключей',
allConnections: 'Все соединения',
searchForConnections: 'Поиск соединений',
disableScratchpad: 'Отключить заметки',
reportABug: 'Сообщить о баге',
nextTab: 'Следующая вкладка',
previousTab: 'Предыдущая вкладка',
selectTabNumber: 'Выбрать вкладку под номером {param}',
toggleConsole: 'Переключиться на консоль',
addShortcut: 'Добавить горячие клавиши',
editShortcut: 'Изменить горячие клавиши',
deleteShortcut: 'Удалить горячие клавиши',
restoreDefaults: 'Восстановить по-умолчанию',
restoreDefaultsQuestion: 'Вы подтверждаете восстановление значений по-умолчанию?',
registerAShortcut: 'Зарегистрировать горячие клавиши',
invalidShortcutMessage: 'Невозможно использовать эту комбинацию, попробуйте ещё',
shortcutAlreadyExists: 'Такая комбинация уже существует',
saveContent: 'Сохранить содержимое',
openAllConnections: 'Открыть все соединения',
openSettings: 'Открыть настройки',
openScratchpad: 'Открыть заметки',
runOrReload: 'Выполнить или обновить',
formatQuery: 'Отформатировать запрос',
queryHistory: 'История запросов',
clearQuery: 'Очистить запрос',
openFilter: 'Открыть фильтр',
nextResultsPage: 'Следующая страница',
previousResultsPage: 'Предыдущая страница',
fillCell: 'Заполнить ячейку',
editFolder: 'Изменить директорию',
folderName: 'Название директории',
deleteFolder: 'Удалить директорию',
editConnectionAppearence: 'Изменить внешний вид соединения',
executeSelectedQuery: 'Выполнить выделенный запрос',
defaultCopyType: 'Тип копирования по-умолчанию',
showTableSize: 'Показывать размер таблицы в сайдбаре',
showTableSizeDescription: 'Только MySQL/MariaDB. Включение этого параметра может повлиять на производительность схемы с большим количеством таблиц.',
searchForSchemas: 'Поиск схем',
switchSearchMethod: 'Переключить способ поиска',
noResultsPresent: 'Данные отсутствуют',
sqlExportOptions: 'Опции SQL экспорта',
targetTable: 'Целевая таблица',
phpArray: 'PHP массив',
closeAllTabs: 'Закрыть все вкладки',
closeOtherTabs: 'Закрыть остальные вкладки',
closeTabsToLeft: 'Закрыть вкладки слева',
closeTabsToRight: 'Закрыть вкладки справа'
},
faker: {
address: 'Адрес',
@ -309,7 +367,7 @@ export const ruRU = {
random: 'Случайный',
system: 'Система',
time: 'Время',
vehicle: 'Vehicle',
vehicle: 'Средство передвижения',
zipCode: 'Почтовый код',
zipCodeByState: 'Почтовый код города',
city: 'Город',
@ -323,8 +381,8 @@ export const ruRU = {
county: 'Округ',
country: 'Страна',
countryCode: 'Код страны',
state: 'Штат',
stateAbbr: 'Аббревиатура штата',
state: 'Область',
stateAbbr: 'Аббревиатура области',
latitude: 'Широта',
longitude: 'Долгота',
direction: 'Направление',
@ -336,8 +394,8 @@ export const ruRU = {
department: 'Отдел',
productName: 'Имя продукта',
price: 'Прайс',
productAdjective: 'Product adjective',
productMaterial: 'Product material',
productAdjective: 'Относящееся к продукту',
productMaterial: 'Материал продукта',
product: 'Продукт',
productDescription: 'Описание продукта',
suffixes: 'Суфиксы',
@ -356,15 +414,16 @@ export const ruRU = {
collation: 'Сопоставление',
engine: 'Движок',
past: 'Прошлое',
now: 'Сейчас',
future: 'Будущее',
between: 'Между',
recent: 'Недавнее',
soon: 'Вскоре',
month: 'Месяц',
weekday: 'Будний день',
weekday: 'День недели',
account: 'Аккаунт',
accountName: 'Имя аккаунта',
routingNumber: 'Routing number',
routingNumber: 'Номер маршрута',
mask: 'Маска',
amount: 'Сумма',
transactionType: 'Тип транзакции',
@ -380,9 +439,9 @@ export const ruRU = {
bic: 'Bic',
transactionDescription: 'Описание транзакции',
branch: 'Ветка',
commitEntry: 'Подтвердить запись',
commitMessage: 'Подтвердить сообщение',
commitSha: 'Подтвердить SHA',
commitEntry: 'Коммит',
commitMessage: 'Сообщение коммита',
commitSha: 'SHA коммита',
shortSha: 'Короткий SHA',
abbreviation: 'Сокращение',
adjective: 'Прилагательное',
@ -402,21 +461,21 @@ export const ruRU = {
ip: 'Ip',
ipv6: 'Ipv6',
userAgent: 'User agent',
mac: 'Мак-адрес',
mac: 'MAC-адрес',
password: 'Пароль',
word: 'Слово',
words: 'Слова',
sentence: 'Предложение',
slug: 'Slug',
sentences: 'Sentences',
sentences: 'Предложения',
paragraph: 'Параграф',
paragraphs: 'Параграфы',
text: 'Текст',
lines: 'Линии',
genre: 'Жанр',
firstName: 'Фамилия',
lastName: 'Имя',
middleName: 'Среднее имя',
firstName: 'Имя',
lastName: 'Фамилия',
middleName: 'Отчество',
findName: 'Полное имя',
jobTitle: 'Название задания',
gender: 'Пол',
@ -427,24 +486,24 @@ export const ruRU = {
jobArea: 'Область задания',
jobType: 'Тип задания',
phoneNumber: 'Номер телефона',
phoneNumberFormat: 'Формат номера',
phoneNumberFormat: 'Формат номера телефона',
phoneFormats: 'Формат номеров телефона',
number: 'Номер',
float: 'Дробное число',
arrayElement: 'Элемент массива',
arrayElements: 'Элементы массива',
objectElement: 'Объект элемента',
objectElement: 'Элемент объекта',
uuid: 'Uuid',
boolean: 'Логический',
image: 'Изображение',
locale: 'Локаль',
alpha: 'Альфа',
alphaNumeric: 'Буквенно-Цифровой',
alpha: 'Буквенный',
alphaNumeric: 'Буквенно-цифровой',
hexaDecimal: 'Шестнадцатеричный',
fileName: 'Имя файла',
commonFileName: 'Общее имя файла',
mimeType: 'Mime тип',
commonFileType: 'Общий тип файло',
mimeType: 'Mime-тип',
commonFileType: 'Общий тип файлов',
commonFileExt: 'Общее расширение файлов',
fileType: 'Тип файла',
fileExt: 'Расширение файла',

View File

@ -10,5 +10,6 @@ export const localesNames: {[key: string]: string} = {
'ja-JP': '日本語',
'zh-CN': '简体中文',
'ru-RU': 'Русский',
'id-ID': 'Bahasa Indonesia'
'id-ID': 'Bahasa Indonesia',
'ko-KR': '한국어'
};

View File

@ -35,6 +35,10 @@ export default class {
return ipcRenderer.invoke('get-table-indexes', unproxify(params));
}
static getTableDll (params: { uid: string; schema: string; table: string }): Promise<IpcResponse<string>> {
return ipcRenderer.invoke('get-table-ddl', unproxify(params));
}
static getKeyUsage (params: { uid: string; schema: string; table: string }): Promise<IpcResponse> {
return ipcRenderer.invoke('get-key-usage', unproxify(params));
}

View File

@ -1,14 +1,16 @@
import { ClientCode } from 'common/interfaces/antares';
import { jsonToSqlInsert } from 'common/libs/sqlUtils';
import * as json2php from 'json2php';
export const exportRows = (args: {
type: 'csv' | 'json'| 'sql';
type: 'csv' | 'json'| 'sql' | 'php';
content: object[];
table: string;
client?: ClientCode;
fields?: {
[key: string]: {type: string; datePrecision: number};
};
sqlOptions?: {sqlInsertAfter: number; sqlInsertDivider: 'bytes' | 'rows'; targetTable: string};
}) => {
let mime;
let content;
@ -21,27 +23,37 @@ export const exportRows = (args: {
if (args.content.length)
csv.push(Object.keys(args.content[0]).join(';'));
for (const row of args.content)
csv.push(Object.values(row).map(col => typeof col === 'string' ? `"${col}"` : col).join(';'));
for (const row of args.content) {
csv.push(Object.values(row).map(col => {
if (typeof col === 'string') return `"${col}"`;
if (col instanceof Buffer) return col.toString('base64');
if (col instanceof Uint8Array) return Buffer.from(col).toString('base64');
return col;
}).join(';'));
}
content = csv.join('\n');
break;
}
case 'sql': {
mime = 'text/sql';
const sql = [];
const sql = jsonToSqlInsert({
json: args.content,
client:
args.client,
fields: args.fields,
table: args.sqlOptions.targetTable || args.table,
options: args.sqlOptions
});
for (const row of args.content) {
sql.push(jsonToSqlInsert({
json: row,
client:
args.client,
fields: args.fields,
table: args.table
}));
}
content = sql.join('\n');
content = sql;
break;
}
case 'php': {
mime = 'application/x-httpd-php';
const printer = json2php.make({ linebreak: '\n', indent: '\t', shortArraySyntax: true });
content = printer(args.content);
content = `<?php\n$${(args.sqlOptions?.targetTable || args.table).replaceAll('-', '_')} = ${content};`;
break;
}
case 'json':
@ -54,7 +66,7 @@ export const exportRows = (args: {
const file = new Blob([content], { type: mime });
const downloadLink = document.createElement('a');
downloadLink.download = `${args.table}.${args.type}`;
downloadLink.download = `${args.sqlOptions?.targetTable || args.table}.${args.type}`;
downloadLink.href = window.URL.createObjectURL(file);
downloadLink.style.display = 'none';
document.body.appendChild(downloadLink);

View File

@ -2,6 +2,7 @@
/* eslint-disable @typescript-eslint/ban-types */
declare module '@/App.vue';
declare module 'v-mask';
declare module 'json2php';
declare module 'vuedraggable' {// <- to export as default
const draggableComponent: import('vue').DefineComponent<{
list: {