Skip to content

Commit

Permalink
Merge pull request #37 from oslabs-beta/annabelle/import
Browse files Browse the repository at this point in the history
Annabelle/import
  • Loading branch information
tgao17 authored Aug 14, 2023
2 parents 01c98c8 + caa62cc commit d6ea6f5
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 287 deletions.
55 changes: 21 additions & 34 deletions backend/src/ipcHandlers/handlers/dbOpsHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ interface ImportPayload {
filePath: string;
}

interface ExportPayload extends ImportPayload {
db: string;
}

interface ExportPayload {
sourceDb: string;
}
Expand Down Expand Up @@ -308,35 +312,30 @@ export async function importDb(
event.sender.send('async-started');

try {
// create new empty db
await queryModel.query(createDBFunc(newDbName, dbType), [], dbType);

const ext = path.extname(filePath).toLowerCase();
if (ext !== '.sql' && ext !== '.tar') {
throw new Error('Invalid file extension');
// create new empty database
try {
await queryModel.query(createDBFunc(newDbName, dbType), [], dbType);
} catch (e) {
throw new Error('Failed to create Database');
}

const restoreCmd =
ext === '.sql'
? runSQLFunc(newDbName, filePath, dbType)
: runTARFunc(newDbName, filePath, dbType);

// run temp sql file on new database
try {
// populate new db with data from file
await promExecute(restoreCmd);
await promExecute(runSQLFunc(newDbName, filePath, dbType));
} catch (e: any) {
console.log('this is error in run temp', e);
// cleanup: drop created db
logger(`Dropping imported db because: ${e.message}`, LogType.WARNING);
logger(`Dropping duplicate db because: ${e.message}`, LogType.WARNING);
const dropDBScript = dropDBFunc(newDbName, dbType);
await queryModel.query(dropDBScript, [], dbType);

throw new Error('Failed to populate database');
throw new Error('Failed to populate newly created database');
}

// update frontend with new db list
const dbsAndTableInfo: DBList = await databaseModel.getLists('', dbType);
event.sender.send('db-lists', dbsAndTableInfo);
logger("Sent 'db-lists' from 'import-db'", LogType.SEND);
logger("Sent 'db-lists' from 'duplicate-db'", LogType.SEND);
} finally {
event.sender.send('async-complete');
}
Expand All @@ -354,36 +353,24 @@ export async function importDb(
* 4. send back a feedback to frontend based on pormExecute.
*/

export async function exportDb(
event,
{ sourceDb }: ExportPayload,
dbType: DBType,
) {
export async function exportDb(event, payload: ExportPayload, dbType: DBType) {
logger("Received 'export-db'", LogType.RECEIVE);
event.sender.send('async-started');

// store temporary file in user desktop
const FilePath = path.resolve(os.homedir(), 'desktop', `${sourceDb}.sql`);
const { db, filePath } = payload;

let feedback: Feedback = {
const feedback: Feedback = {
type: '',
message: '',
};

try {
// dump database to new file
const dumpCmd = runFullCopyFunc(sourceDb, FilePath, dbType);

// dump database to file
const dumpCmd = runFullCopyFunc(db, filePath, dbType);
try {
await promExecute(dumpCmd);
feedback = {
type: 'success',
message: `${sourceDb} Schema successfully exported to ${FilePath}`,
};
event.sender.send('feedback', feedback);
logger("Sent 'feedback' from 'export-db'", LogType.SEND);
} catch (e) {
throw new Error(`Failed to dump ${sourceDb} to a file at ${FilePath}`);
throw new Error(`Failed to dump ${db} to temp file at ${filePath}`);
}
} finally {
event.sender.send('async-complete');
Expand Down
1 change: 1 addition & 0 deletions backend/src/utils/helperFunctions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ const helperFunctions: HelperFunctions = {
},
(error, stdout, stderr) => {
if (error) {
console.log('ERROR in helperfunctions - promExecute', error);
return reject(error);
}
if (stderr) return reject(new Error(stderr));
Expand Down
30 changes: 30 additions & 0 deletions frontend/components/sidebar/DbEntry.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@ import {
} from '@mui/material';
import DeleteIcon from '@mui/icons-material/Delete';
import FileCopyIcon from '@mui/icons-material/FileCopy';
import FileDownloadIcon from '@mui/icons-material/FileDownload';

import { SidebarListItem, StyledListItemText } from '../../style-variables';
import { sendFeedback } from '../../lib/utils';
import { DBType } from '../../../backend/BE_types';
import { getAppDataPath } from '../../lib/queries';

const { ipcRenderer } = window.require('electron');

Expand All @@ -42,13 +44,41 @@ function DbEntry({ db, isSelected, select, duplicate, dbType }: DbEntryProps) {
);
};

const handleExportDB = async () => {
const options = {
title: 'Choose File Path',
defaultPath: `${getAppDataPath('sql')}`,
buttonLabel: 'Save',
filters: [{ name: 'SQL', extensions: ['sql'] }],
};

try {
const filePath = await ipcRenderer.invoke('showSaveDialog', options);

const payload = {
db,
filePath,
};

await ipcRenderer.invoke('export-db', payload, dbType);
} catch (error) {
console.log(error);
}
};

return (
<SidebarListItem
$customSelected={isSelected}
onClick={() => select(db, dbType)}
>
<StyledListItemText primary={`${db} [${dbType}]`} />
<ListItemSecondaryAction>
<Tooltip title="Export Database">
<IconButton edge="end" onClick={handleExportDB} size="large">
<FileDownloadIcon />
</IconButton>
</Tooltip>

<Tooltip title="Copy Database">
<IconButton edge="end" onClick={duplicate} size="large">
<FileCopyIcon />
Expand Down
10 changes: 5 additions & 5 deletions frontend/lib/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,22 +48,22 @@ export const deleteQuery = (
};

// Finds proper data path for saving based on operating system
type GetAppDataPath = () => string;
// type GetAppDataPath = (file: string) => string;

// used to determine default filepath for saving query information locally
export const getAppDataPath: GetAppDataPath = () => {
export const getAppDataPath = (file: 'sql' | 'json' = 'json') => {
switch (process.platform) {
case 'darwin':
return path.join(process.env.HOME ?? '', 'Library', 'SeeQR Data.json');
return path.join(process.env.HOME ?? '', 'Library', `SeeQR Data.${file}`);

case 'win32':
return path.join(
process.env.APPDATA ?? '',
'../../Documents/SeeQR Data.json',
`../../Documents/SeeQR Data.${file}`,
);

case 'linux':
return path.join(process.env.HOME ?? '', '.SeeQR Data.json');
return path.join(process.env.HOME ?? '', `.SeeQR Data.${file}`);

default:
// console.log("Unsupported platform!");
Expand Down
Loading

0 comments on commit d6ea6f5

Please sign in to comment.