#!/bin/bash # ============================================================== # GUARDiA DB 선택 공통 함수 # ============================================================== # 사용법: source setup/lib/db_select.sh; select_database # 결과: DB_TYPE, DATABASE_URL, INSTALL_POSTGRES, INSTALL_PGVECTOR 변수 설정 # ============================================================== select_database() { # 환경변수로 이미 지정된 경우 프롬프트 생략 if [[ -n "${DB_TYPE:-}" ]]; then info "DB_TYPE=$DB_TYPE (환경변수 설정됨)" _apply_db_type "$DB_TYPE" return fi echo "" echo "============================================================" echo " 데이터베이스 선택" echo "============================================================" echo " 1) SQLite (개발·단독 실행 권장, 추가 설치 없음)" echo " 2) PostgreSQL (운영 환경 권장)" echo " 3) PostgreSQL + pgvector (AI 벡터 검색 포함, 권장)" echo "" echo " pgvector: SR 유사도 검색, KB 시맨틱 검색, 이상 탐지에 활용" echo " Qdrant: docker-compose에 선택적 포함 (고성능 벡터 검색)" echo "============================================================" local choice read -rp " 선택 [1-3, 기본값=3]: " choice choice="${choice:-3}" case "$choice" in 1) DB_TYPE="sqlite" ;; 2) DB_TYPE="postgres" ;; 3) DB_TYPE="postgres-vector";; *) warn "잘못된 선택 '$choice' — 기본값 3(postgres-vector) 사용" DB_TYPE="postgres-vector" ;; esac _apply_db_type "$DB_TYPE" } _apply_db_type() { local dtype="$1" case "$dtype" in sqlite) DATABASE_URL="sqlite+aiosqlite:///./guardia_itsm.db" INSTALL_POSTGRES=false INSTALL_PGVECTOR=false INSTALL_QDRANT=false ok "DB: SQLite (개발 모드)" ;; postgres) DATABASE_URL="postgresql+asyncpg://guardia:guardia@localhost:5432/guardia" INSTALL_POSTGRES=true INSTALL_PGVECTOR=false INSTALL_QDRANT=false ok "DB: PostgreSQL" ;; postgres-vector) DATABASE_URL="postgresql+asyncpg://guardia:guardia@localhost:5432/guardia" INSTALL_POSTGRES=true INSTALL_PGVECTOR=true INSTALL_QDRANT=false # Qdrant는 docker-compose로 별도 제공 ok "DB: PostgreSQL + pgvector (AI 벡터 검색 포함)" ;; *) warn "알 수 없는 DB_TYPE='$dtype' — SQLite로 대체" DATABASE_URL="sqlite+aiosqlite:///./guardia_itsm.db" INSTALL_POSTGRES=false INSTALL_PGVECTOR=false INSTALL_QDRANT=false ;; esac export DB_TYPE DATABASE_URL INSTALL_POSTGRES INSTALL_PGVECTOR INSTALL_QDRANT } setup_postgres() { local pgpw="${POSTGRES_PASSWORD:-guardia}" [[ "$INSTALL_POSTGRES" != "true" ]] && return echo "" info "PostgreSQL 설정..." # 배포 환경별 초기화 (호출 스크립트에서 처리됨) # 여기서는 DB/사용자 생성만 담당 # 비밀번호 안전 저장 sudo -u postgres psql \ -tc "SELECT 1 FROM pg_user WHERE usename='guardia'" 2>/dev/null \ | grep -q 1 \ || sudo -u postgres psql -c \ "CREATE USER guardia WITH PASSWORD '${pgpw}';" 2>/dev/null sudo -u postgres psql \ -tc "SELECT 1 FROM pg_database WHERE datname='guardia'" 2>/dev/null \ | grep -q 1 \ || sudo -u postgres psql -c \ "CREATE DATABASE guardia OWNER guardia;" 2>/dev/null ok "PostgreSQL DB/사용자 생성 완료" # pgvector 확장 설치 if [[ "$INSTALL_PGVECTOR" == "true" ]]; then _install_pgvector "$pgpw" fi } _install_pgvector() { local pgpw="$1" echo "" info "pgvector 확장 설치..." # OS별 패키지 설치 if command -v apt-get &>/dev/null; then apt-get install -y -qq postgresql-server-dev-all build-essential git 2>/dev/null || true # pgvector 소스 빌드 (패키지 없는 경우) if ! dpkg -l postgresql-15-pgvector &>/dev/null 2>&1; then _build_pgvector_from_source else apt-get install -y -qq "postgresql-$(pg_lsclusters | grep online | awk '{print $1}' | head -1)-pgvector" 2>/dev/null \ || _build_pgvector_from_source fi elif command -v dnf &>/dev/null; then dnf install -y pgvector_15 2>/dev/null \ || _build_pgvector_from_source else _build_pgvector_from_source fi # 확장 활성화 sudo -u postgres psql -d guardia -c "CREATE EXTENSION IF NOT EXISTS vector;" 2>/dev/null \ && ok "pgvector 확장 활성화 완료" \ || warn "pgvector 활성화 실패 — 나중에 수동: CREATE EXTENSION vector;" } _build_pgvector_from_source() { local tmpdir tmpdir=$(mktemp -d) info "pgvector 소스 빌드..." git clone --depth 1 https://github.com/pgvector/pgvector.git "$tmpdir" 2>/dev/null \ || { warn "pgvector 소스 클론 실패 — 인터넷 연결 확인"; return; } cd "$tmpdir" make 2>/dev/null make install 2>/dev/null cd - rm -rf "$tmpdir" ok "pgvector 빌드 완료" } write_db_env() { local env_file="$1" # .env 파일에 DATABASE_URL 기록 if grep -q "^DATABASE_URL=" "$env_file" 2>/dev/null; then sed -i "s|^DATABASE_URL=.*|DATABASE_URL=${DATABASE_URL}|" "$env_file" else echo "DATABASE_URL=${DATABASE_URL}" >> "$env_file" fi # pgvector 설정 추가 if [[ "$INSTALL_PGVECTOR" == "true" ]]; then grep -q "^ENABLE_VECTOR=" "$env_file" 2>/dev/null \ || echo "ENABLE_VECTOR=true" >> "$env_file" fi ok ".env DATABASE_URL 기록 완료: $DATABASE_URL" }