Skip to content

Commit

Permalink
Merge pull request #8732 from ever-co/fix/mysql-and-postgres-providers
Browse files Browse the repository at this point in the history
[Chore(deps)]: Upgrades MySQL client to `mysql2`
  • Loading branch information
rahul-rocket authored Jan 23, 2025
2 parents 36024f7 + 998ee01 commit dd208de
Show file tree
Hide file tree
Showing 12 changed files with 100 additions and 68 deletions.
2 changes: 1 addition & 1 deletion apps/desktop-timer/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@
"moment-duration-format": "^2.3.2",
"moment-range": "^4.0.2",
"moment-timezone": "^0.5.45",
"mysql": "^2.18.1",
"mysql2": "^3.12.0",
"node-fetch": "^2.6.7",
"node-notifier": "^8.0.0",
"pg": "^8.13.1",
Expand Down
1 change: 1 addition & 0 deletions apps/desktop-timer/src/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@
"moment": "^2.30.1",
"node-fetch": "^2.6.7",
"node-notifier": "^8.0.0",
"mysql2": "^3.12.0",
"pg": "^8.13.1",
"pg-query-stream": "^4.7.1",
"screenshot-desktop": "^1.15.0",
Expand Down
3 changes: 2 additions & 1 deletion packages/desktop-lib/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@
"moment-duration-format": "^2.3.2",
"moment-range": "^4.0.2",
"moment-timezone": "^0.5.45",
"mysql": "^2.18.1",
"mysql2": "^3.12.0",
"pg": "^8.13.1",
"node-notifier": "^8.0.0",
"screenshot-desktop": "^1.15.0",
"sound-play": "1.1.0",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { TABLE_NAME_INTERVALS, TABLE_NAME_TIMERS } from '../../../offline';
import { Knex } from 'knex';
import { ProviderFactory, TABLE_NAME_INTERVALS, TABLE_NAME_TIMERS } from '../../../offline';

export async function up(knex: Knex): Promise<void> {
if (ProviderFactory.instance.dialect === 'postgres') return;
await knex.schema.alterTable(TABLE_NAME_INTERVALS, (table: Knex.TableBuilder) => {
table.integer('timerId').unsigned().references('id').inTable(TABLE_NAME_TIMERS).onDelete('SET NULL').alter();
});
Expand Down
31 changes: 18 additions & 13 deletions packages/desktop-lib/src/lib/offline/databases/mysql-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export class MysqlProvider implements IClientServerProvider {
private static _instance: IClientServerProvider;
private _connection: Knex;
private _database: string;
private readonly CLIENT = 'mysql2';

private constructor() {
this._initialization();
Expand All @@ -17,13 +18,13 @@ export class MysqlProvider implements IClientServerProvider {

public get config(): Knex.Config {
return {
client: 'mysql',
client: this.CLIENT,
connection: {
...this._connectionConfig,
database: this._database,
database: this._database
},
migrations: {
directory: __dirname + '/migrations',
directory: __dirname + '/migrations'
},
pool: {
min: 2,
Expand All @@ -32,10 +33,10 @@ export class MysqlProvider implements IClientServerProvider {
acquireTimeoutMillis: 60 * 1000 * 2,
idleTimeoutMillis: 30000,
reapIntervalMillis: 1000,
createRetryIntervalMillis: 100,
createRetryIntervalMillis: 100
},
useNullAsDefault: true,
asyncStackTraces: true,
asyncStackTraces: true
};
}

Expand All @@ -49,26 +50,30 @@ export class MysqlProvider implements IClientServerProvider {
private _initialization() {
this._database = 'gauzy_timer_db';
const cfg = LocalStore.getApplicationConfig().config['mysql'];
if (!cfg) {
throw new AppError('MYSQL', 'MysqlSQL configuration is missing');
}
if (!cfg.dbHost || !cfg.dbPort || !cfg.dbUsername || !cfg.dbPassword) {
throw new AppError('MYSQL', 'Required MySQL configuration fields are missing');
}
this._connectionConfig = {
host: cfg.dbHost,
port: cfg.dbPort,
user: cfg.dbUsername,
password: cfg.dbPassword,
timezone: 'utc'
timezone: '+00:00'
};
}

public async createDatabase() {
try {
const connection: Knex = require('knex')({
client: 'mysql',
connection: this._connectionConfig,
client: this.CLIENT,
connection: this._connectionConfig
});
await connection.raw('CREATE DATABASE IF NOT EXISTS ??', this._database).finally(async () => {
await connection.destroy();
});
await connection
.raw('CREATE DATABASE IF NOT EXISTS ??', this._database)
.finally(async () => {
await connection.destroy();
});
} catch (error) {
throw new AppError('MYSQL', error);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ export class PostgresProvider implements IClientServerProvider {
private _initialization() {
this._database = 'gauzy_timer_db';
const cfg = LocalStore.getApplicationConfig().config['postgres'];
if (!cfg) {
throw new AppError('POSTGRES', 'PostgreSQL configuration is missing');
}
if (!cfg.dbHost || !cfg.dbPort || !cfg.dbUsername || !cfg.dbPassword) {
throw new AppError('POSTGRES', 'Required PostgreSQL configuration fields are missing');
}
this._connectionConfig = {
host: cfg.dbHost,
port: cfg.dbPort,
Expand Down
39 changes: 21 additions & 18 deletions packages/desktop-lib/src/lib/offline/databases/provider-factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { MysqlProvider } from './mysql-provider';
import { LocalStore } from '../../desktop-store';
import { AppError } from '../../error-handler';
import { BetterSqliteProvider } from './better-sqlite-provider';
import { logger } from '@gauzy/desktop-core';

export class ProviderFactory implements IDatabaseProvider {
private _dbContext: DatabaseProviderContext;
Expand Down Expand Up @@ -56,20 +57,22 @@ export class ProviderFactory implements IDatabaseProvider {

public async migrate(): Promise<void> {
const connection = require('knex')(this.config);
await connection.migrate
.latest()
.then(([, log]) => {
if (!log.length) {
console.info('Database is already up to date...✅');
} else {
console.info('⚓️ Ran migrations: ' + log.join(', '));
console.log('Migration completed... 💯');
}
})
.catch((error) => { throw new AppError('PRMIG', error) })
.finally(async () => {
await connection.destroy();
});

try {
const [, log] = await connection.migrate.latest();

if (log.length === 0) {
logger.info('✅ Database is already up to date.');
} else {
logger.info(`⚓️ Ran migrations: ${log.join(', ')}`);
logger.info('💯 Migration completed successfully.');
}
} catch (error) {
logger.error('❌ Migration failed:', error.message);
throw new AppError('PRMIG', `Migration error: ${error.message}`);
} finally {
await connection.destroy();
}
}

public static get instance(): ProviderFactory {
Expand Down Expand Up @@ -101,7 +104,7 @@ export class ProviderFactory implements IDatabaseProvider {
user: arg[dialect]?.dbUsername,
password: arg[dialect]?.dbPassword,
database: arg[dialect]?.dbName,
port: arg[dialect]?.dbPort,
port: arg[dialect]?.dbPort
};
let databaseOptions: Knex.Config = {};
let driver = '';
Expand All @@ -110,14 +113,14 @@ export class ProviderFactory implements IDatabaseProvider {
driver = 'PostgresSQL';
databaseOptions = {
client: 'pg',
connection,
connection
};
break;
case 'mysql':
driver = 'MySQL';
databaseOptions = {
client: 'mysql',
connection,
client: 'mysql2',
connection
};
break;
case 'sqlite':
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { AppError } from '../../error-handler';
import { IUserService } from '../../interfaces';
import { isJSON } from '../../utilities/util';
import { UserDAO } from '../dao';
import { UserTO } from '../dto';
import { User } from '../models';
Expand Down Expand Up @@ -37,7 +38,9 @@ export class UserService implements IUserService<UserTO> {
try {
const userDao = await this._userDAO.current();
const user = new User(userDao);
user.employee = JSON.parse(user.employee as string);
if (isJSON(user.employee)) {
user.employee = JSON.parse(user.employee as string);
}
return user;
} catch (error) {
console.error(error);
Expand Down
8 changes: 8 additions & 0 deletions packages/desktop-lib/src/lib/utilities/util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export function isJSON<T>(input: T): boolean {
try {
JSON.parse(input as string);
return true;
} catch (e) {
return false;
}
}
1 change: 1 addition & 0 deletions packages/utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export * from './lib/is-date';
export * from './lib/is-defined';
export * from './lib/is-empty';
export * from './lib/is-function';
export * from './lib/is-json';
export * from './lib/is-js-object';
export * from './lib/is-not-empty';
export * from './lib/is-not-null-or-undefined';
Expand Down
21 changes: 21 additions & 0 deletions packages/utils/src/lib/is-json.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* Checks if a given input is a valid JSON string.
*
* @param {unknown} input - The input value to check.
* @returns {boolean} - Returns `true` if the input is a valid JSON string, otherwise `false`.
*
* @example
* console.log(isJSON('{"name": "John", "age": 30}')); // true
* console.log(isJSON('{name: John, age: 30}')); // false
* console.log(isJSON(123)); // false
* console.log(isJSON(null)); // false
*/
export function isJSON(input: unknown): boolean {
if (typeof input !== 'string') return false;
try {
JSON.parse(input);
return true;
} catch {
return false;
}
}
48 changes: 15 additions & 33 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -14823,11 +14823,6 @@ big.js@^5.2.2:
resolved "https://registry.yarnpkg.com/big.js/-/big.js-5.2.2.tgz#65f0af382f578bcdc742bd9c281e9cb2d7768328"
integrity sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ==

[email protected]:
version "9.0.0"
resolved "https://registry.yarnpkg.com/bignumber.js/-/bignumber.js-9.0.0.tgz#805880f84a329b5eac6e7cb6f8274b6d82bdf075"
integrity sha512-t/OYhhJ2SD+YGBQcjY8GzzDHEk9f3nerxjtfa6tlMXfe7frs/WozhvCNoGvpM0P3bNf3Gq5ZRMlGr5f3r4/N8A==

bignumber.js@^9.0.0:
version "9.1.2"
resolved "https://registry.yarnpkg.com/bignumber.js/-/bignumber.js-9.1.2.tgz#b7c4242259c008903b13707983b5f4bbd31eda0c"
Expand Down Expand Up @@ -28142,6 +28137,21 @@ [email protected]:
seq-queue "^0.0.5"
sqlstring "^2.3.2"

mysql2@^3.12.0:
version "3.12.0"
resolved "https://registry.yarnpkg.com/mysql2/-/mysql2-3.12.0.tgz#db8fc770f8b76ebaba49dc4bbfe2a1754057d882"
integrity sha512-C8fWhVysZoH63tJbX8d10IAoYCyXy4fdRFz2Ihrt9jtPILYynFEKUUzpp1U7qxzDc3tMbotvaBH+sl6bFnGZiw==
dependencies:
aws-ssl-profiles "^1.1.1"
denque "^2.1.0"
generate-function "^2.3.1"
iconv-lite "^0.6.3"
long "^5.2.1"
lru.min "^1.0.0"
named-placeholders "^1.1.3"
seq-queue "^0.0.5"
sqlstring "^2.3.2"

mysql2@^3.9.7:
version "3.11.3"
resolved "https://registry.yarnpkg.com/mysql2/-/mysql2-3.11.3.tgz#8291e6069a0784310846f6437b8527050dfc10c4"
Expand All @@ -28157,16 +28167,6 @@ mysql2@^3.9.7:
seq-queue "^0.0.5"
sqlstring "^2.3.2"

mysql@^2.18.1:
version "2.18.1"
resolved "https://registry.yarnpkg.com/mysql/-/mysql-2.18.1.tgz#2254143855c5a8c73825e4522baf2ea021766717"
integrity sha512-Bca+gk2YWmqp2Uf6k5NFEurwY/0td0cpebAucFpY/3jhrwrVGuxU2uQFCHjU19SJfje0yQvi+rVWdq78hR5lig==
dependencies:
bignumber.js "9.0.0"
readable-stream "2.3.7"
safe-buffer "5.1.2"
sqlstring "2.3.1"

mz@^2.4.0:
version "2.7.0"
resolved "https://registry.yarnpkg.com/mz/-/mz-2.7.0.tgz#95008057a56cafadc2bc63dde7f9ff6955948e32"
Expand Down Expand Up @@ -32562,19 +32562,6 @@ read@^4.0.0:
string_decoder "^1.1.1"
util-deprecate "^1.0.1"

[email protected]:
version "2.3.7"
resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.7.tgz#1eca1cf711aef814c04f62252a36a62f6cb23b57"
integrity sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==
dependencies:
core-util-is "~1.0.0"
inherits "~2.0.3"
isarray "~1.0.0"
process-nextick-args "~2.0.0"
safe-buffer "~5.1.1"
string_decoder "~1.1.1"
util-deprecate "~1.0.1"

readable-stream@^2.0.0, readable-stream@^2.0.1, readable-stream@^2.0.2, readable-stream@^2.0.5, readable-stream@^2.1.4, readable-stream@^2.2.2, readable-stream@^2.3.5, readable-stream@^2.3.8, readable-stream@~2.3.6:
version "2.3.8"
resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.8.tgz#91125e8042bba1b9887f49345f6277027ce8be9b"
Expand Down Expand Up @@ -34498,11 +34485,6 @@ [email protected]:
resolved "https://registry.yarnpkg.com/sqlstring-sqlite/-/sqlstring-sqlite-0.1.1.tgz#c8c61810663f2e59a6b0d737b70a8752bda3a078"
integrity sha512-9CAYUJ0lEUPYJrswqiqdINNSfq3jqWo/bFJ7tufdoNeSK0Fy+d1kFTxjqO9PIqza0Kri+ZtYMfPVf1aZaFOvrQ==

[email protected]:
version "2.3.1"
resolved "https://registry.yarnpkg.com/sqlstring/-/sqlstring-2.3.1.tgz#475393ff9e91479aea62dcaf0ca3d14983a7fb40"
integrity sha512-ooAzh/7dxIG5+uDik1z/Rd1vli0+38izZhGzSa34FwR7IbelPWCCKSNIl8jlL/F7ERvy8CB2jNeM1E9i9mXMAQ==

[email protected], sqlstring@^2.3.2:
version "2.3.3"
resolved "https://registry.yarnpkg.com/sqlstring/-/sqlstring-2.3.3.tgz#2ddc21f03bce2c387ed60680e739922c65751d0c"
Expand Down

0 comments on commit dd208de

Please sign in to comment.