feature connection #45

Merged
hjlee merged 1 commits from feature/connection into dev 2025-09-22 17:34:47 +09:00
16 changed files with 1332 additions and 100 deletions

2
.gitignore vendored
View File

@ -272,3 +272,5 @@ out/
.classpath
.settings/
bin/
/src/generated/prisma

View File

@ -47,7 +47,7 @@
"@typescript-eslint/parser": "^6.14.0",
"eslint": "^8.55.0",
"jest": "^29.7.0",
"nodemon": "^3.0.2",
"nodemon": "^3.1.10",
"prettier": "^3.1.0",
"supertest": "^6.3.3",
"ts-jest": "^29.1.1",

View File

@ -65,7 +65,7 @@
"@typescript-eslint/parser": "^6.14.0",
"eslint": "^8.55.0",
"jest": "^29.7.0",
"nodemon": "^3.0.2",
"nodemon": "^3.1.10",
"prettier": "^3.1.0",
"supertest": "^6.3.3",
"ts-jest": "^29.1.1",

View File

@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "postgresql"

View File

@ -16,6 +16,38 @@ const router = Router();
* GET /api/external-db-connections
* DB
*/
/**
* GET /api/external-db-connections/types/supported
* DB
*/
router.get(
"/types/supported",
authenticateToken,
async (req: AuthenticatedRequest, res: Response) => {
try {
const { DB_TYPE_OPTIONS, DB_TYPE_DEFAULTS } = await import(
"../types/externalDbTypes"
);
return res.status(200).json({
success: true,
data: {
types: DB_TYPE_OPTIONS,
defaults: DB_TYPE_DEFAULTS,
},
message: "지원하는 DB 타입 목록을 조회했습니다.",
});
} catch (error) {
console.error("DB 타입 목록 조회 오류:", error);
return res.status(500).json({
success: false,
message: "서버 내부 오류가 발생했습니다.",
error: error instanceof Error ? error.message : "알 수 없는 오류",
});
}
}
);
router.get(
"/",
authenticateToken,
@ -53,6 +85,7 @@ router.get(
}
);
/**
* GET /api/external-db-connections/:id
* DB
@ -208,42 +241,28 @@ router.delete(
);
/**
* POST /api/external-db-connections/test
*
* POST /api/external-db-connections/:id/test
* (ID )
*/
router.post(
"/test",
"/:id/test",
authenticateToken,
async (req: AuthenticatedRequest, res: Response) => {
try {
const testData =
req.body as import("../types/externalDbTypes").ConnectionTestRequest;
// 필수 필드 검증
const requiredFields = [
"db_type",
"host",
"port",
"database_name",
"username",
"password",
];
const missingFields = requiredFields.filter(
(field) => !testData[field as keyof typeof testData]
);
if (missingFields.length > 0) {
const id = parseInt(req.params.id);
if (isNaN(id)) {
return res.status(400).json({
success: false,
message: "필수 필드가 누락되었습니다.",
message: "유효하지 않은 연결 ID입니다.",
error: {
code: "MISSING_FIELDS",
details: `다음 필드가 필요합니다: ${missingFields.join(", ")}`,
code: "INVALID_ID",
details: "연결 ID는 숫자여야 합니다.",
},
});
}
const result = await ExternalDbConnectionService.testConnection(testData);
const result = await ExternalDbConnectionService.testConnectionById(id);
return res.status(200).json({
success: result.success,
@ -265,35 +284,59 @@ router.post(
);
/**
* GET /api/external-db-connections/types/supported
* DB
* POST /api/external-db-connections/:id/execute
* SQL
*/
router.get(
"/types/supported",
router.post(
"/:id/execute",
authenticateToken,
async (req: AuthenticatedRequest, res: Response) => {
try {
const { DB_TYPE_OPTIONS, DB_TYPE_DEFAULTS } = await import(
"../types/externalDbTypes"
);
const id = parseInt(req.params.id);
const { query } = req.body;
return res.status(200).json({
success: true,
data: {
types: DB_TYPE_OPTIONS,
defaults: DB_TYPE_DEFAULTS,
},
message: "지원하는 DB 타입 목록을 조회했습니다.",
});
if (!query?.trim()) {
return res.status(400).json({
success: false,
message: "쿼리가 입력되지 않았습니다."
});
}
const result = await ExternalDbConnectionService.executeQuery(id, query);
return res.json(result);
} catch (error) {
console.error("DB 타입 목록 조회 오류:", error);
console.error("쿼리 실행 오류:", error);
return res.status(500).json({
success: false,
message: "서버 내부 오류가 발생했습니다.",
error: error instanceof Error ? error.message : "알 수 없는 오류",
message: "쿼리 실행 중 오류가 발생했습니다.",
error: error instanceof Error ? error.message : "알 수 없는 오류"
});
}
}
);
/**
* GET /api/external-db-connections/:id/tables
*
*/
router.get(
"/:id/tables",
authenticateToken,
async (req: AuthenticatedRequest, res: Response) => {
try {
const id = parseInt(req.params.id);
const result = await ExternalDbConnectionService.getTables(id);
return res.json(result);
} catch (error) {
console.error("테이블 목록 조회 오류:", error);
return res.status(500).json({
success: false,
message: "테이블 목록 조회 중 오류가 발생했습니다.",
error: error instanceof Error ? error.message : "알 수 없는 오류"
});
}
}
);
export default router;

View File

@ -6,6 +6,7 @@ import {
ExternalDbConnection,
ExternalDbConnectionFilter,
ApiResponse,
TableInfo,
} from "../types/externalDbTypes";
import { PasswordEncryption } from "../utils/passwordEncryption";
@ -315,15 +316,57 @@ export class ExternalDbConnectionService {
}
/**
*
* (ID )
*/
static async testConnection(
testData: import("../types/externalDbTypes").ConnectionTestRequest
static async testConnectionById(
id: number
): Promise<import("../types/externalDbTypes").ConnectionTestResult> {
const startTime = Date.now();
try {
switch (testData.db_type.toLowerCase()) {
// 저장된 연결 정보 조회
const connection = await prisma.external_db_connections.findUnique({
where: { id }
});
if (!connection) {
return {
success: false,
message: "연결 정보를 찾을 수 없습니다.",
error: {
code: "CONNECTION_NOT_FOUND",
details: `ID ${id}에 해당하는 연결 정보가 없습니다.`
}
};
}
// 비밀번호 복호화
const decryptedPassword = await this.getDecryptedPassword(id);
if (!decryptedPassword) {
return {
success: false,
message: "비밀번호 복호화에 실패했습니다.",
error: {
code: "DECRYPTION_FAILED",
details: "저장된 비밀번호를 복호화할 수 없습니다."
}
};
}
// 테스트용 데이터 준비
const testData = {
db_type: connection.db_type,
host: connection.host,
port: connection.port,
database_name: connection.database_name,
username: connection.username,
password: decryptedPassword,
connection_timeout: connection.connection_timeout || undefined,
ssl_enabled: connection.ssl_enabled || undefined
};
// 실제 연결 테스트 수행
switch (connection.db_type.toLowerCase()) {
case "postgresql":
return await this.testPostgreSQLConnection(testData, startTime);
case "mysql":
@ -360,7 +403,7 @@ export class ExternalDbConnectionService {
* PostgreSQL
*/
private static async testPostgreSQLConnection(
testData: import("../types/externalDbTypes").ConnectionTestRequest,
testData: any,
startTime: number
): Promise<import("../types/externalDbTypes").ConnectionTestResult> {
const { Client } = await import("pg");
@ -416,7 +459,7 @@ export class ExternalDbConnectionService {
* MySQL ( )
*/
private static async testMySQLConnection(
testData: import("../types/externalDbTypes").ConnectionTestRequest,
testData: any,
startTime: number
): Promise<import("../types/externalDbTypes").ConnectionTestResult> {
// MySQL 라이브러리가 없으므로 모의 구현
@ -434,7 +477,7 @@ export class ExternalDbConnectionService {
* Oracle ( )
*/
private static async testOracleConnection(
testData: import("../types/externalDbTypes").ConnectionTestRequest,
testData: any,
startTime: number
): Promise<import("../types/externalDbTypes").ConnectionTestResult> {
return {
@ -451,7 +494,7 @@ export class ExternalDbConnectionService {
* SQL Server ( )
*/
private static async testMSSQLConnection(
testData: import("../types/externalDbTypes").ConnectionTestRequest,
testData: any,
startTime: number
): Promise<import("../types/externalDbTypes").ConnectionTestResult> {
return {
@ -468,7 +511,7 @@ export class ExternalDbConnectionService {
* SQLite ( )
*/
private static async testSQLiteConnection(
testData: import("../types/externalDbTypes").ConnectionTestRequest,
testData: any,
startTime: number
): Promise<import("../types/externalDbTypes").ConnectionTestResult> {
return {
@ -546,4 +589,237 @@ export class ExternalDbConnectionService {
return null;
}
}
/**
* SQL
*/
static async executeQuery(
id: number,
query: string
): Promise<ApiResponse<any[]>> {
try {
// 연결 정보 조회
console.log("연결 정보 조회 시작:", { id });
const connection = await prisma.external_db_connections.findUnique({
where: { id }
});
console.log("조회된 연결 정보:", connection);
if (!connection) {
console.log("연결 정보를 찾을 수 없음:", { id });
return {
success: false,
message: "연결 정보를 찾을 수 없습니다."
};
}
// 비밀번호 복호화
const decryptedPassword = await this.getDecryptedPassword(id);
if (!decryptedPassword) {
return {
success: false,
message: "비밀번호 복호화에 실패했습니다."
};
}
// DB 타입에 따른 쿼리 실행
switch (connection.db_type.toLowerCase()) {
case "postgresql":
return await this.executePostgreSQLQuery(connection, decryptedPassword, query);
case "mysql":
return {
success: false,
message: "MySQL 쿼리 실행은 현재 지원하지 않습니다."
};
case "oracle":
return {
success: false,
message: "Oracle 쿼리 실행은 현재 지원하지 않습니다."
};
case "mssql":
return {
success: false,
message: "SQL Server 쿼리 실행은 현재 지원하지 않습니다."
};
case "sqlite":
return {
success: false,
message: "SQLite 쿼리 실행은 현재 지원하지 않습니다."
};
default:
return {
success: false,
message: `지원하지 않는 데이터베이스 타입입니다: ${connection.db_type}`
};
}
} catch (error) {
console.error("쿼리 실행 오류:", error);
return {
success: false,
message: "쿼리 실행 중 오류가 발생했습니다.",
error: error instanceof Error ? error.message : "알 수 없는 오류"
};
}
}
/**
* PostgreSQL
*/
private static async executePostgreSQLQuery(
connection: any,
password: string,
query: string
): Promise<ApiResponse<any[]>> {
const { Client } = await import("pg");
const client = new Client({
host: connection.host,
port: connection.port,
database: connection.database_name,
user: connection.username,
password: password,
connectionTimeoutMillis: (connection.connection_timeout || 30) * 1000,
ssl: connection.ssl_enabled === "Y" ? { rejectUnauthorized: false } : false,
});
try {
await client.connect();
console.log("DB 연결 정보:", {
host: connection.host,
port: connection.port,
database: connection.database_name,
user: connection.username
});
console.log("쿼리 실행:", query);
const result = await client.query(query);
console.log("쿼리 결과:", result.rows);
await client.end();
return {
success: true,
message: "쿼리가 성공적으로 실행되었습니다.",
data: result.rows
};
} catch (error) {
try {
await client.end();
} catch (endError) {
// 연결 종료 오류는 무시
}
return {
success: false,
message: "쿼리 실행 중 오류가 발생했습니다.",
error: error instanceof Error ? error.message : "알 수 없는 오류"
};
}
}
/**
*
*/
static async getTables(id: number): Promise<ApiResponse<TableInfo[]>> {
try {
// 연결 정보 조회
const connection = await prisma.external_db_connections.findUnique({
where: { id }
});
if (!connection) {
return {
success: false,
message: "연결 정보를 찾을 수 없습니다."
};
}
// 비밀번호 복호화
const decryptedPassword = await this.getDecryptedPassword(id);
if (!decryptedPassword) {
return {
success: false,
message: "비밀번호 복호화에 실패했습니다."
};
}
switch (connection.db_type.toLowerCase()) {
case "postgresql":
return await this.getPostgreSQLTables(connection, decryptedPassword);
default:
return {
success: false,
message: `지원하지 않는 데이터베이스 타입입니다: ${connection.db_type}`
};
}
} catch (error) {
console.error("테이블 목록 조회 오류:", error);
return {
success: false,
message: "테이블 목록 조회 중 오류가 발생했습니다.",
error: error instanceof Error ? error.message : "알 수 없는 오류"
};
}
}
/**
* PostgreSQL
*/
private static async getPostgreSQLTables(
connection: any,
password: string
): Promise<ApiResponse<TableInfo[]>> {
const { Client } = await import("pg");
const client = new Client({
host: connection.host,
port: connection.port,
database: connection.database_name,
user: connection.username,
password: password,
connectionTimeoutMillis: (connection.connection_timeout || 30) * 1000,
ssl: connection.ssl_enabled === "Y" ? { rejectUnauthorized: false } : false
});
try {
await client.connect();
// 테이블 목록과 각 테이블의 컬럼 정보 조회
const result = await client.query(`
SELECT
t.table_name,
array_agg(
json_build_object(
'column_name', c.column_name,
'data_type', c.data_type,
'is_nullable', c.is_nullable,
'column_default', c.column_default
)
) as columns,
obj_description(quote_ident(t.table_name)::regclass::oid, 'pg_class') as table_description
FROM information_schema.tables t
LEFT JOIN information_schema.columns c
ON c.table_name = t.table_name
AND c.table_schema = t.table_schema
WHERE t.table_schema = 'public'
AND t.table_type = 'BASE TABLE'
GROUP BY t.table_name
ORDER BY t.table_name
`);
await client.end();
return {
success: true,
data: result.rows.map(row => ({
table_name: row.table_name,
columns: row.columns || [],
description: row.table_description
})) as TableInfo[],
message: "테이블 목록을 조회했습니다."
};
} catch (error) {
await client.end();
return {
success: false,
message: "테이블 목록 조회 중 오류가 발생했습니다.",
error: error instanceof Error ? error.message : "알 수 없는 오류"
};
}
}
}

View File

@ -4,17 +4,17 @@
export interface ExternalDbConnection {
id?: number;
connection_name: string;
description?: string;
description?: string | null;
db_type: "mysql" | "postgresql" | "oracle" | "mssql" | "sqlite";
host: string;
port: number;
database_name: string;
username: string;
password: string;
connection_timeout?: number;
query_timeout?: number;
max_connections?: number;
ssl_enabled?: string;
connection_timeout?: number | null;
query_timeout?: number | null;
max_connections?: number | null;
ssl_enabled?: string | null;
ssl_cert_path?: string;
connection_options?: Record<string, unknown>;
company_code: string;
@ -32,6 +32,19 @@ export interface ExternalDbConnectionFilter {
search?: string;
}
export interface TableColumn {
column_name: string;
data_type: string;
is_nullable: string;
column_default: string | null;
}
export interface TableInfo {
table_name: string;
columns: TableColumn[];
description: string | null;
}
export interface ApiResponse<T> {
success: boolean;
data?: T;

View File

@ -12,7 +12,7 @@ services:
environment:
- NODE_ENV=development
- PORT=8080
- DATABASE_URL=postgresql://postgres:ph0909!!@39.117.244.52:11132/plm
- DATABASE_URL=postgresql://postgres:postgres@postgres-erp:5432/ilshin
- JWT_SECRET=ilshin-plm-super-secret-jwt-key-2024
- JWT_EXPIRES_IN=24h
- CORS_ORIGIN=http://localhost:9771

View File

@ -1,7 +1,7 @@
"use client";
import React, { useState, useEffect } from "react";
import { Plus, Search, Pencil, Trash2, Database } from "lucide-react";
import { Plus, Search, Pencil, Trash2, Database, Terminal } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
@ -26,6 +26,7 @@ import {
ConnectionTestRequest,
} from "@/lib/api/externalDbConnection";
import { ExternalDbConnectionModal } from "@/components/admin/ExternalDbConnectionModal";
import { SqlQueryModal } from "@/components/admin/SqlQueryModal";
// DB 타입 매핑
const DB_TYPE_LABELS: Record<string, string> = {
@ -59,6 +60,8 @@ export default function ExternalConnectionsPage() {
const [connectionToDelete, setConnectionToDelete] = useState<ExternalDbConnection | null>(null);
const [testingConnections, setTestingConnections] = useState<Set<number>>(new Set());
const [testResults, setTestResults] = useState<Map<number, boolean>>(new Map());
const [sqlModalOpen, setSqlModalOpen] = useState(false);
const [selectedConnection, setSelectedConnection] = useState<ExternalDbConnection | null>(null);
// 데이터 로딩
const loadConnections = async () => {
@ -170,18 +173,7 @@ export default function ExternalConnectionsPage() {
setTestingConnections((prev) => new Set(prev).add(connection.id!));
try {
const testData: ConnectionTestRequest = {
db_type: connection.db_type,
host: connection.host,
port: connection.port,
database_name: connection.database_name,
username: connection.username,
password: connection.password,
connection_timeout: connection.connection_timeout,
ssl_enabled: connection.ssl_enabled,
};
const result = await ExternalDbConnectionAPI.testConnection(testData);
const result = await ExternalDbConnectionAPI.testConnection(connection.id);
setTestResults((prev) => new Map(prev).set(connection.id!, result.success));
@ -193,7 +185,7 @@ export default function ExternalConnectionsPage() {
} else {
toast({
title: "연결 실패",
description: `${connection.connection_name} 연결에 실패했습니다.`,
description: result.message || `${connection.connection_name} 연결에 실패했습니다.`,
variant: "destructive",
});
}
@ -369,6 +361,19 @@ export default function ExternalConnectionsPage() {
</TableCell>
<TableCell className="text-right">
<div className="flex justify-end gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => {
console.log("SQL 쿼리 실행 버튼 클릭 - connection:", connection);
setSelectedConnection(connection);
setSqlModalOpen(true);
}}
className="h-8 w-8 p-0"
title="SQL 쿼리 실행"
>
<Terminal className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
@ -428,6 +433,19 @@ export default function ExternalConnectionsPage() {
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* SQL 쿼리 모달 */}
{selectedConnection && (
<SqlQueryModal
isOpen={sqlModalOpen}
onClose={() => {
setSqlModalOpen(false);
setSelectedConnection(null);
}}
connectionId={selectedConnection.id!}
connectionName={selectedConnection.connection_name}
/>
)}
</div>
);
}

View File

@ -0,0 +1,275 @@
"use client";
import { useState, useEffect, ChangeEvent } from "react";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";
import { ExternalDbConnectionAPI } from "@/lib/api/externalDbConnection";
interface TableColumn {
column_name: string;
data_type: string;
is_nullable: string;
column_default: string | null;
}
interface TableInfo {
table_name: string;
columns: TableColumn[];
description: string | null;
}
interface QueryResult {
[key: string]: string | number | boolean | null | undefined;
}
interface TableColumn {
column_name: string;
data_type: string;
is_nullable: string;
column_default: string | null;
}
interface TableInfo {
table_name: string;
columns: TableColumn[];
description: string | null;
}
interface SqlQueryModalProps {
isOpen: boolean;
onClose: () => void;
connectionId: number;
connectionName: string;
}
export const SqlQueryModal: React.FC<SqlQueryModalProps> = ({ isOpen, onClose, connectionId, connectionName }) => {
const { toast } = useToast();
const [query, setQuery] = useState("SELECT * FROM ");
const [results, setResults] = useState<QueryResult[]>([]);
const [loading, setLoading] = useState(false);
const [tables, setTables] = useState<TableInfo[]>([]);
const [selectedTable, setSelectedTable] = useState("");
const [loadingTables, setLoadingTables] = useState(false);
// 테이블 목록 로딩
useEffect(() => {
console.log("SqlQueryModal - connectionId:", connectionId);
const loadTables = async () => {
setLoadingTables(true);
try {
const result = await ExternalDbConnectionAPI.getTables(connectionId);
if (result.success && result.data) {
setTables(result.data as unknown as TableInfo[]);
}
} catch (error) {
console.error("테이블 목록 로딩 오류:", error);
toast({
title: "오류",
description: "테이블 목록을 불러오는데 실패했습니다.",
variant: "destructive",
});
} finally {
setLoadingTables(false);
}
};
loadTables();
}, []);
const handleExecute = async () => {
console.log("실행 버튼 클릭");
if (!query.trim()) {
toast({
title: "오류",
description: "실행할 쿼리를 입력해주세요.",
variant: "destructive",
});
return;
}
console.log("쿼리 실행 시작:", { connectionId, query });
setLoading(true);
try {
const result = await ExternalDbConnectionAPI.executeQuery(connectionId, query);
console.log("쿼리 실행 결과:", result);
if (result.success && result.data) {
setResults(result.data);
toast({
title: "성공",
description: "쿼리가 성공적으로 실행되었습니다.",
});
} else {
toast({
title: "오류",
description: result.message || "쿼리 실행 중 오류가 발생했습니다.",
variant: "destructive",
});
}
} catch (error) {
console.error("쿼리 실행 오류:", error);
toast({
title: "오류",
description: error instanceof Error ? error.message : "쿼리 실행 중 오류가 발생했습니다.",
variant: "destructive",
});
} finally {
setLoading(false);
}
};
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="max-h-[90vh] max-w-5xl" aria-describedby="modal-description">
<DialogHeader>
<DialogTitle>{connectionName} - SQL </DialogTitle>
<DialogDescription>
SQL SELECT .
</DialogDescription>
</DialogHeader>
{/* 쿼리 입력 영역 */}
<div className="mb-4 space-y-4">
<div className="space-y-2">
{/* 테이블 선택 */}
<div className="flex flex-col gap-4">
<div className="flex items-center gap-2">
<Select
value={selectedTable}
onValueChange={(value) => {
setSelectedTable(value);
// 현재 커서 위치에 테이블 이름 삽입
setQuery((prev) => {
const fromIndex = prev.toUpperCase().lastIndexOf("FROM");
if (fromIndex === -1) {
return `SELECT * FROM ${value}`;
}
const beforeFrom = prev.substring(0, fromIndex + 4);
return `${beforeFrom} ${value}`;
});
}}
disabled={loadingTables}
>
<SelectTrigger className="w-[200px]">
<SelectValue placeholder={loadingTables ? "테이블 로딩 중..." : "테이블 선택"} />
</SelectTrigger>
<SelectContent>
{tables.map((table) => (
<SelectItem key={table.table_name} value={table.table_name}>
{table.table_name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* 테이블 정보 */}
<div className="bg-muted/50 rounded-md border p-4">
<h3 className="mb-2 font-medium"> </h3>
<div className="space-y-4">
{tables.map((table) => (
<div key={table.table_name} className="border-b pb-2 last:border-b-0 last:pb-0">
<div className="flex items-center justify-between">
<h4 className="font-mono font-bold">{table.table_name}</h4>
<Button variant="ghost" size="sm" onClick={() => setQuery(`SELECT * FROM ${table.table_name}`)}>
</Button>
</div>
{table.description && (
<p className="text-muted-foreground mt-1 text-sm">{table.description}</p>
)}
<div className="mt-2 grid grid-cols-3 gap-2">
{table.columns.map((column: TableColumn) => (
<div key={column.column_name} className="text-sm">
<span className="font-mono">{column.column_name}</span>
<span className="text-muted-foreground ml-1">({column.data_type})</span>
</div>
))}
</div>
</div>
))}
</div>
</div>
</div>
{/* 쿼리 입력 */}
<div className="relative">
<Textarea
value={query}
onChange={(e: ChangeEvent<HTMLTextAreaElement>) => setQuery(e.target.value)}
placeholder="SELECT * FROM table_name"
className="min-h-[120px] pr-24 font-mono"
/>
<Button
onClick={() => {
console.log("버튼 클릭됨");
handleExecute();
}}
disabled={loading}
className="absolute top-2 right-2 w-20"
size="sm"
>
{loading ? "실행 중..." : "실행"}
</Button>
</div>
</div>
</div>
{/* 결과 섹션 */}
<div className="mt-4 space-y-4">
<div className="flex items-center justify-between">
<div className="text-muted-foreground text-sm">
{loading ? "쿼리 실행 중..." : results.length > 0 ? `${results.length}개의 결과가 있습니다.` : "실행된 쿼리가 없습니다."}
</div>
</div>
{/* 결과 그리드 */}
<div className="rounded-md border">
<div className="max-h-[400px] overflow-auto">
<Table>
{results.length > 0 ? (
<>
<TableHeader className="sticky top-0 bg-white">
<TableRow>
{Object.keys(results[0]).map((key) => (
<TableHead key={key} className="font-mono font-bold">
{key}
</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{results.map((row: QueryResult, i: number) => (
<TableRow key={i} className="hover:bg-muted/50">
{Object.values(row).map((value, j) => (
<TableCell key={j} className="font-mono">
{value === null ? (
<span className="text-muted-foreground italic">NULL</span>
) : (
String(value)
)}
</TableCell>
))}
</TableRow>
))}
</TableBody>
</>
) : (
<TableBody>
<TableRow>
<TableCell className="text-muted-foreground h-32 text-center">
{loading ? "쿼리 실행 중..." : "쿼리를 실행하면 결과가 여기에 표시됩니다."}
</TableCell>
</TableRow>
</TableBody>
)}
</Table>
</div>
</div>
</div>
</DialogContent>
</Dialog>
);
};

View File

@ -203,33 +203,29 @@ export class ExternalDbConnectionAPI {
}
/**
*
* (ID )
*/
static async testConnection(testData: ConnectionTestRequest): Promise<ConnectionTestResult> {
static async testConnection(connectionId: number): Promise<ConnectionTestResult> {
try {
const response = await apiClient.post<ApiResponse<ConnectionTestResult>>(`${this.BASE_PATH}/test`, testData);
const response = await apiClient.post<ApiResponse<ConnectionTestResult>>(
`${this.BASE_PATH}/${connectionId}/test`
);
if (!response.data.success) {
// 백엔드에서 테스트 실패 시에도 200으로 응답하지만 data.success가 false
return (
response.data.data || {
success: false,
message: response.data.message || "연결 테스트에 실패했습니다.",
error: response.data.error,
}
);
return {
success: false,
message: response.data.message || "연결 테스트에 실패했습니다.",
error: response.data.error,
};
}
return (
response.data.data || {
success: true,
message: response.data.message || "연결 테스트가 완료되었습니다.",
}
);
return response.data.data || {
success: true,
message: response.data.message || "연결 테스트가 완료되었습니다.",
};
} catch (error) {
console.error("연결 테스트 오류:", error);
// 네트워크 오류 등의 경우
return {
success: false,
message: "연결 테스트 중 오류가 발생했습니다.",
@ -240,4 +236,37 @@ export class ExternalDbConnectionAPI {
};
}
}
/**
* SQL
*/
/**
*
*/
static async getTables(connectionId: number): Promise<ApiResponse<string[]>> {
try {
const response = await apiClient.get<ApiResponse<string[]>>(
`${this.BASE_PATH}/${connectionId}/tables`
);
return response.data;
} catch (error) {
console.error("테이블 목록 조회 오류:", error);
throw error;
}
}
static async executeQuery(connectionId: number, query: string): Promise<ApiResponse<any[]>> {
try {
console.log("API 요청:", `${this.BASE_PATH}/${connectionId}/execute`, { query });
const response = await apiClient.post<ApiResponse<any[]>>(
`${this.BASE_PATH}/${connectionId}/execute`,
{ query }
);
console.log("API 응답:", response.data);
return response.data;
} catch (error) {
console.error("SQL 쿼리 실행 오류:", error);
throw error;
}
}
}

View File

@ -56,8 +56,8 @@
"@tailwindcss/postcss": "^4",
"@tanstack/react-query-devtools": "^5.86.0",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"@types/react": "^19.1.13",
"@types/react-dom": "^19.1.9",
"eslint": "^9",
"eslint-config-next": "15.4.4",
"eslint-config-prettier": "^10.1.8",
@ -2757,9 +2757,9 @@
}
},
"node_modules/@types/react": {
"version": "19.1.12",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.1.12.tgz",
"integrity": "sha512-cMoR+FoAf/Jyq6+Df2/Z41jISvGZZ2eTlnsaJRptmZ76Caldwy1odD4xTr/gNV9VLj0AWgg/nmkevIyUfIIq5w==",
"version": "19.1.13",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.1.13.tgz",
"integrity": "sha512-hHkbU/eoO3EG5/MZkuFSKmYqPbSVk5byPFa3e7y/8TybHiLMACgI8seVYlicwk7H5K/rI2px9xrQp/C+AUDTiQ==",
"license": "MIT",
"dependencies": {
"csstype": "^3.0.2"

View File

@ -64,8 +64,8 @@
"@tailwindcss/postcss": "^4",
"@tanstack/react-query-devtools": "^5.86.0",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"@types/react": "^19.1.13",
"@types/react-dom": "^19.1.9",
"eslint": "^9",
"eslint-config-next": "15.4.4",
"eslint-config-prettier": "^10.1.8",

386
package-lock.json generated
View File

@ -5,9 +5,96 @@
"packages": {
"": {
"dependencies": {
"axios": "^1.12.2"
"@prisma/client": "^6.16.2",
"axios": "^1.12.2",
"prisma": "^6.16.2"
}
},
"node_modules/@prisma/client": {
"version": "6.16.2",
"resolved": "https://registry.npmjs.org/@prisma/client/-/client-6.16.2.tgz",
"integrity": "sha512-E00PxBcalMfYO/TWnXobBVUai6eW/g5OsifWQsQDzJYm7yaY+IRLo7ZLsaefi0QkTpxfuhFcQ/w180i6kX3iJw==",
"hasInstallScript": true,
"license": "Apache-2.0",
"engines": {
"node": ">=18.18"
},
"peerDependencies": {
"prisma": "*",
"typescript": ">=5.1.0"
},
"peerDependenciesMeta": {
"prisma": {
"optional": true
},
"typescript": {
"optional": true
}
}
},
"node_modules/@prisma/config": {
"version": "6.16.2",
"resolved": "https://registry.npmjs.org/@prisma/config/-/config-6.16.2.tgz",
"integrity": "sha512-mKXSUrcqXj0LXWPmJsK2s3p9PN+aoAbyMx7m5E1v1FufofR1ZpPoIArjjzOIm+bJRLLvYftoNYLx1tbHgF9/yg==",
"license": "Apache-2.0",
"dependencies": {
"c12": "3.1.0",
"deepmerge-ts": "7.1.5",
"effect": "3.16.12",
"empathic": "2.0.0"
}
},
"node_modules/@prisma/debug": {
"version": "6.16.2",
"resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-6.16.2.tgz",
"integrity": "sha512-bo4/gA/HVV6u8YK2uY6glhNsJ7r+k/i5iQ9ny/3q5bt9ijCj7WMPUwfTKPvtEgLP+/r26Z686ly11hhcLiQ8zA==",
"license": "Apache-2.0"
},
"node_modules/@prisma/engines": {
"version": "6.16.2",
"resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-6.16.2.tgz",
"integrity": "sha512-7yf3AjfPUgsg/l7JSu1iEhsmZZ/YE00yURPjTikqm2z4btM0bCl2coFtTGfeSOWbQMmq45Jab+53yGUIAT1sjA==",
"hasInstallScript": true,
"license": "Apache-2.0",
"dependencies": {
"@prisma/debug": "6.16.2",
"@prisma/engines-version": "6.16.0-7.1c57fdcd7e44b29b9313256c76699e91c3ac3c43",
"@prisma/fetch-engine": "6.16.2",
"@prisma/get-platform": "6.16.2"
}
},
"node_modules/@prisma/engines-version": {
"version": "6.16.0-7.1c57fdcd7e44b29b9313256c76699e91c3ac3c43",
"resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-6.16.0-7.1c57fdcd7e44b29b9313256c76699e91c3ac3c43.tgz",
"integrity": "sha512-ThvlDaKIVrnrv97ujNFDYiQbeMQpLa0O86HFA2mNoip4mtFqM7U5GSz2ie1i2xByZtvPztJlNRgPsXGeM/kqAA==",
"license": "Apache-2.0"
},
"node_modules/@prisma/fetch-engine": {
"version": "6.16.2",
"resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-6.16.2.tgz",
"integrity": "sha512-wPnZ8DMRqpgzye758ZvfAMiNJRuYpz+rhgEBZi60ZqDIgOU2694oJxiuu3GKFeYeR/hXxso4/2oBC243t/whxQ==",
"license": "Apache-2.0",
"dependencies": {
"@prisma/debug": "6.16.2",
"@prisma/engines-version": "6.16.0-7.1c57fdcd7e44b29b9313256c76699e91c3ac3c43",
"@prisma/get-platform": "6.16.2"
}
},
"node_modules/@prisma/get-platform": {
"version": "6.16.2",
"resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-6.16.2.tgz",
"integrity": "sha512-U/P36Uke5wS7r1+omtAgJpEB94tlT4SdlgaeTc6HVTTT93pXj7zZ+B/cZnmnvjcNPfWddgoDx8RLjmQwqGDYyA==",
"license": "Apache-2.0",
"dependencies": {
"@prisma/debug": "6.16.2"
}
},
"node_modules/@standard-schema/spec": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.0.0.tgz",
"integrity": "sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA==",
"license": "MIT"
},
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
@ -25,6 +112,34 @@
"proxy-from-env": "^1.1.0"
}
},
"node_modules/c12": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/c12/-/c12-3.1.0.tgz",
"integrity": "sha512-uWoS8OU1MEIsOv8p/5a82c3H31LsWVR5qiyXVfBNOzfffjUWtPnhAb4BYI2uG2HfGmZmFjCtui5XNWaps+iFuw==",
"license": "MIT",
"dependencies": {
"chokidar": "^4.0.3",
"confbox": "^0.2.2",
"defu": "^6.1.4",
"dotenv": "^16.6.1",
"exsolve": "^1.0.7",
"giget": "^2.0.0",
"jiti": "^2.4.2",
"ohash": "^2.0.11",
"pathe": "^2.0.3",
"perfect-debounce": "^1.0.0",
"pkg-types": "^2.2.0",
"rc9": "^2.1.2"
},
"peerDependencies": {
"magicast": "^0.3.5"
},
"peerDependenciesMeta": {
"magicast": {
"optional": true
}
}
},
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
@ -38,6 +153,30 @@
"node": ">= 0.4"
}
},
"node_modules/chokidar": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz",
"integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==",
"license": "MIT",
"dependencies": {
"readdirp": "^4.0.1"
},
"engines": {
"node": ">= 14.16.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/citty": {
"version": "0.1.6",
"resolved": "https://registry.npmjs.org/citty/-/citty-0.1.6.tgz",
"integrity": "sha512-tskPPKEs8D2KPafUypv2gxwJP8h/OaJmC82QQGGDQcHvXX43xF2VDACcJVmZ0EuSxkpO9Kc4MlrA3q0+FG58AQ==",
"license": "MIT",
"dependencies": {
"consola": "^3.2.3"
}
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
@ -50,6 +189,36 @@
"node": ">= 0.8"
}
},
"node_modules/confbox": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/confbox/-/confbox-0.2.2.tgz",
"integrity": "sha512-1NB+BKqhtNipMsov4xI/NnhCKp9XG9NamYp5PVm9klAT0fsrNPjaFICsCFhNhwZJKNh7zB/3q8qXz0E9oaMNtQ==",
"license": "MIT"
},
"node_modules/consola": {
"version": "3.4.2",
"resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz",
"integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==",
"license": "MIT",
"engines": {
"node": "^14.18.0 || >=16.10.0"
}
},
"node_modules/deepmerge-ts": {
"version": "7.1.5",
"resolved": "https://registry.npmjs.org/deepmerge-ts/-/deepmerge-ts-7.1.5.tgz",
"integrity": "sha512-HOJkrhaYsweh+W+e74Yn7YStZOilkoPb6fycpwNLKzSPtruFs48nYis0zy5yJz1+ktUhHxoRDJ27RQAWLIJVJw==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=16.0.0"
}
},
"node_modules/defu": {
"version": "6.1.4",
"resolved": "https://registry.npmjs.org/defu/-/defu-6.1.4.tgz",
"integrity": "sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg==",
"license": "MIT"
},
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
@ -59,6 +228,24 @@
"node": ">=0.4.0"
}
},
"node_modules/destr": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/destr/-/destr-2.0.5.tgz",
"integrity": "sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA==",
"license": "MIT"
},
"node_modules/dotenv": {
"version": "16.6.1",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",
"integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://dotenvx.com"
}
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
@ -73,6 +260,25 @@
"node": ">= 0.4"
}
},
"node_modules/effect": {
"version": "3.16.12",
"resolved": "https://registry.npmjs.org/effect/-/effect-3.16.12.tgz",
"integrity": "sha512-N39iBk0K71F9nb442TLbTkjl24FLUzuvx2i1I2RsEAQsdAdUTuUoW0vlfUXgkMTUOnYqKnWcFfqw4hK4Pw27hg==",
"license": "MIT",
"dependencies": {
"@standard-schema/spec": "^1.0.0",
"fast-check": "^3.23.1"
}
},
"node_modules/empathic": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/empathic/-/empathic-2.0.0.tgz",
"integrity": "sha512-i6UzDscO/XfAcNYD75CfICkmfLedpyPDdozrLMmQc5ORaQcdMoc21OnlEylMIqI7U8eniKrPMxxtj8k0vhmJhA==",
"license": "MIT",
"engines": {
"node": ">=14"
}
},
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
@ -118,6 +324,34 @@
"node": ">= 0.4"
}
},
"node_modules/exsolve": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.0.7.tgz",
"integrity": "sha512-VO5fQUzZtI6C+vx4w/4BWJpg3s/5l+6pRQEHzFRM8WFi4XffSP1Z+4qi7GbjWbvRQEbdIco5mIMq+zX4rPuLrw==",
"license": "MIT"
},
"node_modules/fast-check": {
"version": "3.23.2",
"resolved": "https://registry.npmjs.org/fast-check/-/fast-check-3.23.2.tgz",
"integrity": "sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A==",
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/dubzzz"
},
{
"type": "opencollective",
"url": "https://opencollective.com/fast-check"
}
],
"license": "MIT",
"dependencies": {
"pure-rand": "^6.1.0"
},
"engines": {
"node": ">=8.0.0"
}
},
"node_modules/follow-redirects": {
"version": "1.15.11",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz",
@ -200,6 +434,23 @@
"node": ">= 0.4"
}
},
"node_modules/giget": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/giget/-/giget-2.0.0.tgz",
"integrity": "sha512-L5bGsVkxJbJgdnwyuheIunkGatUF/zssUoxxjACCseZYAVbaqdh9Tsmmlkl8vYan09H7sbvKt4pS8GqKLBrEzA==",
"license": "MIT",
"dependencies": {
"citty": "^0.1.6",
"consola": "^3.4.0",
"defu": "^6.1.4",
"node-fetch-native": "^1.6.6",
"nypm": "^0.6.0",
"pathe": "^2.0.3"
},
"bin": {
"giget": "dist/cli.mjs"
}
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
@ -251,6 +502,15 @@
"node": ">= 0.4"
}
},
"node_modules/jiti": {
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/jiti/-/jiti-2.5.1.tgz",
"integrity": "sha512-twQoecYPiVA5K/h6SxtORw/Bs3ar+mLUtoPSc7iMXzQzK8d7eJ/R09wmTwAjiamETn1cXYPGfNnu7DMoHgu12w==",
"license": "MIT",
"bin": {
"jiti": "lib/jiti-cli.mjs"
}
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
@ -281,11 +541,135 @@
"node": ">= 0.6"
}
},
"node_modules/node-fetch-native": {
"version": "1.6.7",
"resolved": "https://registry.npmjs.org/node-fetch-native/-/node-fetch-native-1.6.7.tgz",
"integrity": "sha512-g9yhqoedzIUm0nTnTqAQvueMPVOuIY16bqgAJJC8XOOubYFNwz6IER9qs0Gq2Xd0+CecCKFjtdDTMA4u4xG06Q==",
"license": "MIT"
},
"node_modules/nypm": {
"version": "0.6.2",
"resolved": "https://registry.npmjs.org/nypm/-/nypm-0.6.2.tgz",
"integrity": "sha512-7eM+hpOtrKrBDCh7Ypu2lJ9Z7PNZBdi/8AT3AX8xoCj43BBVHD0hPSTEvMtkMpfs8FCqBGhxB+uToIQimA111g==",
"license": "MIT",
"dependencies": {
"citty": "^0.1.6",
"consola": "^3.4.2",
"pathe": "^2.0.3",
"pkg-types": "^2.3.0",
"tinyexec": "^1.0.1"
},
"bin": {
"nypm": "dist/cli.mjs"
},
"engines": {
"node": "^14.16.0 || >=16.10.0"
}
},
"node_modules/ohash": {
"version": "2.0.11",
"resolved": "https://registry.npmjs.org/ohash/-/ohash-2.0.11.tgz",
"integrity": "sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ==",
"license": "MIT"
},
"node_modules/pathe": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
"integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
"license": "MIT"
},
"node_modules/perfect-debounce": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-1.0.0.tgz",
"integrity": "sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==",
"license": "MIT"
},
"node_modules/pkg-types": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.3.0.tgz",
"integrity": "sha512-SIqCzDRg0s9npO5XQ3tNZioRY1uK06lA41ynBC1YmFTmnY6FjUjVt6s4LoADmwoig1qqD0oK8h1p/8mlMx8Oig==",
"license": "MIT",
"dependencies": {
"confbox": "^0.2.2",
"exsolve": "^1.0.7",
"pathe": "^2.0.3"
}
},
"node_modules/prisma": {
"version": "6.16.2",
"resolved": "https://registry.npmjs.org/prisma/-/prisma-6.16.2.tgz",
"integrity": "sha512-aRvldGE5UUJTtVmFiH3WfNFNiqFlAtePUxcI0UEGlnXCX7DqhiMT5TRYwncHFeA/Reca5W6ToXXyCMTeFPdSXA==",
"hasInstallScript": true,
"license": "Apache-2.0",
"dependencies": {
"@prisma/config": "6.16.2",
"@prisma/engines": "6.16.2"
},
"bin": {
"prisma": "build/index.js"
},
"engines": {
"node": ">=18.18"
},
"peerDependencies": {
"typescript": ">=5.1.0"
},
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
}
},
"node_modules/proxy-from-env": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
"license": "MIT"
},
"node_modules/pure-rand": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.1.0.tgz",
"integrity": "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==",
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/dubzzz"
},
{
"type": "opencollective",
"url": "https://opencollective.com/fast-check"
}
],
"license": "MIT"
},
"node_modules/rc9": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/rc9/-/rc9-2.1.2.tgz",
"integrity": "sha512-btXCnMmRIBINM2LDZoEmOogIZU7Qe7zn4BpomSKZ/ykbLObuBdvG+mFq11DL6fjH1DRwHhrlgtYWG96bJiC7Cg==",
"license": "MIT",
"dependencies": {
"defu": "^6.1.4",
"destr": "^2.0.3"
}
},
"node_modules/readdirp": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz",
"integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==",
"license": "MIT",
"engines": {
"node": ">= 14.18.0"
},
"funding": {
"type": "individual",
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/tinyexec": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.1.tgz",
"integrity": "sha512-5uC6DDlmeqiOwCPmK9jMSdOuZTh8bU39Ys6yidB+UTt5hfZUPGAypSgFRiEp+jbi9qH40BLDvy85jIU88wKSqw==",
"license": "MIT"
}
}
}

View File

@ -1,5 +1,7 @@
{
"dependencies": {
"axios": "^1.12.2"
"@prisma/client": "^6.16.2",
"axios": "^1.12.2",
"prisma": "^6.16.2"
}
}

View File

@ -0,0 +1,187 @@
# 외부 데이터베이스 제어관리 시스템 계획서
## 1. 개요
### 1.1 목적
- 외부 데이터베이스 연동 및 중앙 제어 시스템 구축
- 다중 데이터베이스 통합 관리 환경 제공
- 실시간 데이터 동기화 및 제어 기능 구현
- 데이터 수집 및 변환 자동화
### 1.2 기대효과
- 외부 데이터베이스 통합 관리 효율성 향상
- 데이터 수집 및 동기화 시간 단축
- 중앙화된 데이터 제어로 일관성 확보
- 데이터 변환 및 매핑 자동화
## 2. 핵심 기능 설계
### 2.1 데이터베이스 연결 관리
1. **외부 DB 연결 설정**
- 다양한 DBMS 지원 (PostgreSQL, MySQL, Oracle 등)
- 연결 정보 암호화 저장
- 연결 상태 모니터링
- 자동 재연결 메커니즘
2. **연결 풀 관리**
- 커넥션 풀 최적화
- 부하 분산 처리
- 타임아웃 설정
- 연결 상태 로깅
### 2.2 데이터 수집 및 동기화
1. **실시간 데이터 수집**
- 증분 데이터 수집
- 스케줄 기반 수집
- 이벤트 기반 수집
- 에러 복구 메커니즘
2. **데이터 변환 및 매핑**
- 스키마 자동 매핑
- 데이터 타입 변환
- 사용자 정의 변환 규칙
- 매핑 템플릿 관리
3. **동기화 관리**
- 양방향 동기화 지원
- 충돌 감지 및 해결
- 트랜잭션 관리
- 동기화 이력 관리
### 2.3 제어 시스템
1. **중앙 제어 인터페이스**
- 통합 대시보드
- 실시간 모니터링
- 원격 제어 기능
- 알림 시스템
2. **작업 관리**
- 작업 스케줄링
- 우선순위 설정
- 작업 이력 관리
- 에러 처리 및 복구
## 3. 기술 구현 계획
### 3.1 데이터베이스 어댑터 개발 (1개월)
- 다중 DBMS 지원 어댑터
- 연결 풀 관리자
- 쿼리 변환기
- 에러 핸들러
### 3.2 데이터 수집 시스템 개발 (2개월)
- 실시간 수집 엔진
- 데이터 변환 프로세서
- 동기화 매니저
- 로깅 시스템
### 3.3 제어 시스템 개발 (2개월)
- 웹 기반 관리 콘솔
- 모니터링 대시보드
- 알림 시스템
- 리포팅 도구
## 4. 시스템 아키텍처
### 4.1 핵심 컴포넌트
- Database Connection Manager
- Data Collection Engine
- Transformation Processor
- Synchronization Manager
- Control Interface
- Monitoring System
### 4.2 기술 스택
- **Backend**: Node.js, TypeScript
- **Database**: PostgreSQL (메인 DB)
- **캐싱**: Redis
- **모니터링**: Prometheus + Grafana
- **메시지 큐**: RabbitMQ
## 5. 구현 세부사항
### 5.1 데이터베이스 연결 관리
```typescript
interface DBConnection {
id: string;
type: 'postgres' | 'mysql' | 'oracle';
host: string;
port: number;
database: string;
credentials: EncryptedCredentials;
status: ConnectionStatus;
}
class ConnectionManager {
async connect(config: DBConnection): Promise<void>;
async disconnect(connectionId: string): Promise<void>;
async checkStatus(connectionId: string): Promise<ConnectionStatus>;
async executeQuery(connectionId: string, query: string): Promise<QueryResult>;
}
```
### 5.2 데이터 수집 엔진
```typescript
interface CollectionJob {
id: string;
sourceDb: DBConnection;
targetDb: DBConnection;
collectionType: 'full' | 'incremental';
schedule?: CronExpression;
transformationRules: TransformationRule[];
}
class DataCollector {
async startCollection(job: CollectionJob): Promise<void>;
async stopCollection(jobId: string): Promise<void>;
async getStatus(jobId: string): Promise<CollectionStatus>;
}
```
## 6. 고려사항 및 리스크
### 6.1 성능 고려사항
- 대용량 데이터 처리 전략
- 네트워크 대역폭 관리
- 리소스 사용량 모니터링
- 캐싱 전략
### 6.2 보안 고려사항
- 데이터 암호화
- 접근 권한 관리
- 감사 로깅
- 보안 프로토콜 준수
### 6.3 안정성 고려사항
- 장애 복구 전략
- 데이터 정합성 보장
- 백업 및 복구 계획
- 모니터링 및 알림
## 7. 성공 기준
### 7.1 성능 지표
- 데이터 수집 지연시간 < 5초
- 동기화 성공률 99.9%
- 시스템 가용성 99.9%
- 동시 처리 연결 수 > 100
### 7.2 품질 지표
- 데이터 정확도 100%
- 에러 복구율 99%
- 사용자 만족도 90%
- 시스템 응답시간 < 1초
## 8. 향후 계획
### 8.1 확장 계획
- 추가 데이터베이스 유형 지원
- 고급 데이터 변환 기능
- 머신러닝 기반 최적화
- API 게이트웨이 통합
### 8.2 유지보수 계획
- 24/7 모니터링
- 정기 성능 검토
- 보안 패치 관리
- 사용자 피드백 반영