Skip to content

Commit

Permalink
Merge pull request #5 from oslabs-beta/derek/depends
Browse files Browse the repository at this point in the history
Derek/depends
  • Loading branch information
derekoko authored Aug 2, 2023
2 parents 47a00ee + ad5a327 commit 769bd34
Show file tree
Hide file tree
Showing 84 changed files with 1,559 additions and 1,138 deletions.
45 changes: 33 additions & 12 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,52 +7,73 @@
},
"globals": { "JSX": "readonly", "Chart": "readonly", "NodeJS": "readonly" },
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"plugin:react-hooks/recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/recommended-requiring-type-checking",

"airbnb",
"plugin:import/errors",
"plugin:import/warnings",
"plugin:import/typescript",
// "plugin:@typescript-eslint/recommended",
"prettier"

"plugin:import/recommended",
"plugin:import/typescript"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": 12,
"sourceType": "module"
"sourceType": "module",
"project": "./tsconfig.json"
},
"plugins": ["react", "@typescript-eslint"],
"plugins": ["react", "react-hooks", "@typescript-eslint"],
"rules": {
"react/jsx-filename-extension": [2, { "extensions": [".jsx", ".tsx"] }],
"indent": ["error", 2, { "offsetTernaryExpressions": true }],
"react/jsx-filename-extension": [1, { "extensions": [".jsx", ".tsx"] }],

"no-use-before-define": "off",
"@typescript-eslint/no-use-before-define": ["error"],

"import/extensions": [
"error",
"ignorePackages",
{ "js": "never", "jsx": "never", "ts": "never", "tsx": "never" }
],
// "import/no-extraneous-dependencies": ["error", { "devDependencies": true }], **trying to resolve the electron issue

"jsx-a11y/label-has-associated-control": "off",

// prevent wrong warning with typescript overloads
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": ["error"],
"no-dupe-class-members": "off",

"no-dupe-class-members": "off",
"@typescript-eslint/no-dupe-class-members": ["error"],

"lines-between-class-members": "off",
"@typescript-eslint/lines-between-class-members": [
"error",
"always",
{ "exceptAfterSingleLine": true }
],
"react/jsx-curly-newline": "off",

// "react/jsx-curly-newline": "off",

// turned off because typescript, functional components and default props
// don't seem to be good friends. Decided to manually handle defaults for
// optional props instead
"react/require-default-props": "off",
"react/jsx-props-no-spreading": "off",

"camelcase": "off"

// "import/no-extraneous-dependencies": ["error", { "devDependencies": true }], **trying to resolve the electron issue
},
// "settings": "import/core-modules: [ electron ]", **trying to resolve the electron issue
"settings": {
"react": {
"version": "detect"
}
},
// "settings": "import/core-modules: [ electron ]", **trying to resolve the electron issue
"root": true
}
3 changes: 2 additions & 1 deletion .prettierrc.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"singleQuote": true,
"tabWidth": 2,
"useTabs": false
"useTabs": false,
"trailingComma": "all"
}
4 changes: 2 additions & 2 deletions backend/BE_types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export enum DBType {
MySQL = 'mysql',
RDSPostgres = 'rds-pg',
RDSMySQL = 'rds-mysql',
CloudDB = 'cloud-database', //added for cloud dbs
CloudDB = 'cloud-database', // added for cloud dbs
SQLite = 'sqlite',
directPGURI = 'directPGURI',
}
Expand Down Expand Up @@ -126,4 +126,4 @@ export interface QueryPayload {
sqlString: string;
selectedDb: string;
runQueryNumber: number;
}
}
46 changes: 21 additions & 25 deletions backend/DummyD/dummyDataMain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,22 @@ const db = require('../models');
/* subsequently concatenated into the INSERT query generated */
/* in channels.ts to generate the dummy records for the table */


// *************************************************** Helper Functions *************************************************** //

// helper function to generate random numbers that will ultimately represent a random date
const getRandomInt = (min: number, max: number) => {
const minInt = Math.ceil(min);
const maxInt = Math.floor(max);
// The maximum is exclusive and the minimum is inclusive
return Math.floor(Math.random() * (maxInt - minInt) + minInt);
return Math.floor(Math.random() * (maxInt - minInt) + minInt);
};


// helper function to generate random data based on a given column's data type
const generateDataByType = (columnObj: ColumnObj): string | number => {
let length;
// faker.js method to generate data by type
// console.log('columnObj_datatype: ', columnObj.data_type)

switch (columnObj.data_type) {
case 'smallint':
return faker.random.number({ min: -32768, max: 32767 });
Expand All @@ -50,11 +48,11 @@ const generateDataByType = (columnObj: ColumnObj): string | number => {
return '\''.concat(faker.random.alphaNumeric(length)).concat('\'');
case 'varchar':
// defaulting length to 3 because faker.lorem defaults to a length of 3 if no length is specified

length = columnObj.character_maximum_length && columnObj.character_maximum_length > 3
? Math.floor(Math.random() * columnObj.character_maximum_length)
: 3;
return '\''.concat(faker.random.alphaNumeric(length)).concat('\'');
return '\''.concat(faker.random.alphaNumeric(length)).concat('\'');
case 'int':
return faker.random.number({ min: -2147483648, max: 2147483647 });
case 'date': {
Expand Down Expand Up @@ -82,7 +80,7 @@ type GenerateDummyData = (tableInfo: ColumnObj[], numRows: number) => Promise<Du
const generateDummyData: GenerateDummyData = async (tableInfo: ColumnObj[], numRows: number) => {
// assuming primary key is serial, get all the column names except for the column with the primary key
const columnNames: Array<string> = [];
for(let i = 0; i < tableInfo.length; i++) {
for (let i = 0; i < tableInfo.length; i++) {
columnNames.push(tableInfo[i].column_name);
}

Expand All @@ -94,31 +92,29 @@ const generateDummyData: GenerateDummyData = async (tableInfo: ColumnObj[], numR
// at each row, check the columns of the table and generate dummy data accordingly
for (let j = 0; j < tableInfo.length; j += 1) {
// if column has no foreign key constraint, then generate dummy data based on data type
if (tableInfo[j].constraint_type !== 'FOREIGN KEY'){
if (tableInfo[j].constraint_type !== 'FOREIGN KEY') {
// && tableInfo[j].constraint_type !== 'PRIMARY KEY'
row.push(generateDataByType(tableInfo[j]))
row.push(generateDataByType(tableInfo[j]));
}

// if there is a foreign key constraint, grab random key from foreign table
else if (tableInfo[j].constraint_type === 'FOREIGN KEY') {

const foreignColumn = tableInfo[j].foreign_column;
const foreignTable = tableInfo[j].foreign_table;
const getForeignKeyQuery = `
// if there is a foreign key constraint, grab random key from foreign table
else if (tableInfo[j].constraint_type === 'FOREIGN KEY') {
const foreignColumn = tableInfo[j].foreign_column;
const foreignTable = tableInfo[j].foreign_table;
const getForeignKeyQuery = `
SELECT ${foreignColumn}
FROM ${foreignTable} TABLESAMPLE BERNOULLI(100)
LIMIT 1
`;
const foreignKey = await db.query(getForeignKeyQuery);
const chosenPrimaryValue = foreignKey.rows[0][Object.keys(foreignKey.rows[0])[0]]
if (foreignKey.rows.length) {
if (typeof chosenPrimaryValue === 'string') row.push(`'${chosenPrimaryValue}'`);
else row.push(chosenPrimaryValue);
}
else{
logger('There was an error while retrieving a valid foreign key while generating dummy data.', LogType.ERROR);
throw new Error('There was an error while retrieving a valid foreign key.');
}
const foreignKey = await db.query(getForeignKeyQuery);
const chosenPrimaryValue = foreignKey.rows[0][Object.keys(foreignKey.rows[0])[0]];
if (foreignKey.rows.length) {
if (typeof chosenPrimaryValue === 'string') row.push(`'${chosenPrimaryValue}'`);
else row.push(chosenPrimaryValue);
} else {
logger('There was an error while retrieving a valid foreign key while generating dummy data.', LogType.ERROR);
throw new Error('There was an error while retrieving a valid foreign key.');
}
}
}
dummyRecords.push(row);
Expand Down
6 changes: 3 additions & 3 deletions backend/Logging/masterlog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const logger = function (
message: string,
logType: LogType = LogType.NORMAL,
opt1?,
opt2?
opt2?,
) {
// Code for the log color
let colorCode = 0;
Expand Down Expand Up @@ -61,8 +61,8 @@ const logger = function (
if (opt2) moreText += JSON.stringify(opt2);

console.log(
`\u001b[1;${colorCode}m ${`[${logType}] ${message + moreText}`}` +
`\u001b[1;0m`
`\u001b[1;${colorCode}m ${`[${logType}] ${message + moreText}`}`
+ '\u001b[1;0m',
);
saveLogMessage(`[${logType}] ${message}`);
};
Expand Down
34 changes: 19 additions & 15 deletions backend/_documentsConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,19 @@ import { DBType, DocConfigFile, LogType } from './BE_types';
import logger from './Logging/masterlog';

const home = `${os.homedir()}/Documents/SeeQR`;
const configFile = `config.json`;
const configFile = 'config.json';
const configPath = `${home}/${configFile}`;
const defaultFile: DocConfigFile = {
mysql: { user: '', password: '', port: 3306 },
pg: { user: '', password: '', port: 5432 },
rds_mysql: { user: '', password: '', port: 3306, host: '' },
rds_pg: { user: '', password: '', port: 5432, host: '' },
rds_mysql: {
user: '', password: '', port: 3306, host: '',
},
rds_pg: {
user: '', password: '', port: 5432, host: '',
},
sqlite: { path: '' },
directPGURI: { uri: '' }
directPGURI: { uri: '' },
};

/**
Expand All @@ -27,7 +31,7 @@ function writeConfigDefault(): DocConfigFile {
logger('Could not find config file. Creating default', LogType.WARNING);
fs.writeFileSync(configPath, JSON.stringify(defaultFile));
return defaultFile;
};
}

/**
* Check if config.json object has the correct database properties (mysql, pg, etc.), tries to replace only the properties that are missing and return either the original or new object. Doesn't care about additional properties in the object besides those in const defaultFile.
Expand All @@ -51,8 +55,8 @@ const checkConfigFile = function (currConfig: DocConfigFile): DocConfigFile {
} catch (err) {
console.log(err);
logger(
`Error caught checking config file. Resetting config to default.`,
LogType.WARNING
'Error caught checking config file. Resetting config to default.',
LogType.WARNING,
);
return writeConfigDefault();
}
Expand All @@ -69,24 +73,24 @@ const checkConfigFile = function (currConfig: DocConfigFile): DocConfigFile {

/**
* Reads config file data and sends it into checkConfigFile, then returns the result
* If an error occurs during read, the config file will be set back to default
* If an error occurs during read, the config file will be set back to default
* @returns config file contents (login info for each database type)
*/
function readConfigFile(): DocConfigFile {
try {
const config = JSON.parse(
fs.readFileSync(configPath, 'utf-8')
fs.readFileSync(configPath, 'utf-8'),
) as DocConfigFile;
return checkConfigFile(config);
} catch (err: any) {
console.log(err);
logger(
`Error caught checking config file. Resetting config to default.`,
LogType.WARNING
'Error caught checking config file. Resetting config to default.',
LogType.WARNING,
);
return writeConfigDefault();
}
};
}

interface DocConfig {
getConfigFolder: () => string;
Expand All @@ -113,7 +117,7 @@ const docConfig: DocConfig = {
} else {
logger(
`Could not find documents directory. Creating at: ${home}`,
LogType.WARNING
LogType.WARNING,
);
fs.mkdirSync(home);
}
Expand All @@ -126,7 +130,7 @@ const docConfig: DocConfig = {
* @returns login info for the desired database type
*/
getCredentials: function getCredentials(dbType: DBType) {
this.getConfigFolder(); // ensure directory exists
this.getConfigFolder(); // ensure directory exists
let configFile: DocConfigFile;
try {
configFile = readConfigFile(); // all login info now in configFile
Expand Down Expand Up @@ -177,7 +181,7 @@ const docConfig: DocConfig = {

/**
* Takes config data object sent from frontend, stringifies it and saves in config file
* @param config
* @param config
*/
saveConfig: function saveConfig(config: Object) {
try {
Expand Down
Loading

0 comments on commit 769bd34

Please sign in to comment.