# All files / src/hooks useDatabaseOperations.ts

100% Statements 133/133
95.83% Branches 23/24
100% Functions 1/1
100% Lines 133/133

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    1341x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    5x
    5x
    5x
    4x
    5x
    1x
    1x
    5x
    5x
    5x
    25x
    25x
    25x
    4x
    4x
    4x
    4x
    4x
    1x
    1x
    4x
    4x
    4x
    25x
    25x
    25x
    2x
    2x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    25x
    25x
    25x
    3x
    3x
    3x
    3x
    3x
    1x
    1x
    1x
    3x
    2x
    2x
    2x
    3x
    3x
    25x
    25x
    25x
    3x
    1x
    1x
    2x
    2x
    2x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    25x
    25x
    25x
    2x
    2x
    1x
    1x
    1x
    1x
    1x
    1x
    25x
    25x
    25x
    5x
    4x
    4x
    4x
    4x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
     import { useState, useCallback } from 'react'
    import { toast } from 'sonner'
    import {
      getDatabaseStats,
      exportDatabase,
      importDatabase,
      clearDatabase,
      seedDatabase,
      validateDatabaseSchema
    } from '@/lib/db'

    export function useDatabaseOperations() {
      const [stats, setStats] = useState<{
        snippetCount: number
        templateCount: number
        storageType: 'indexeddb' | 'localstorage' | 'none'
        databaseSize: number
      } | null>(null)
      const [loading, setLoading] = useState(true)
      const [schemaHealth, setSchemaHealth] = useState<'unknown' | 'healthy' | 'corrupted'>('unknown')
      const [checkingSchema, setCheckingSchema] = useState(false)

      const loadStats = useCallback(async () => {
        setLoading(true)
        try {
          const data = await getDatabaseStats()
          setStats(data)
        } catch (error) {
          console.error('Failed to load stats:', error)
          toast.error('Failed to load database statistics')
        } finally {
          setLoading(false)
        }
      }, [])

      const checkSchemaHealth = useCallback(async () => {
        setCheckingSchema(true)
        try {
          const result = await validateDatabaseSchema()
          setSchemaHealth(result ? 'healthy' : 'corrupted')
        } catch (error) {
          console.error('Schema check failed:', error)
          setSchemaHealth('corrupted')
        } finally {
          setCheckingSchema(false)
        }
      }, [])

      const handleExport = useCallback(async () => {
        try {
          const jsonData = await exportDatabase()
          const blob = new Blob([jsonData], { type: 'application/json' })
          const url = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.href = url
          a.download = `codesnippet-backup-${Date.now()}.json`
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
          URL.revokeObjectURL(url)
          toast.success('Database exported successfully')
        } catch (error) {
          console.error('Failed to export:', error)
          toast.error('Failed to export database')
        }
      }, [])

      const handleImport = useCallback(async (event: React.ChangeEvent<HTMLInputElement>) => {
        const file = event.target.files?.[0]
        if (!file) return

        try {
          const text = await file.text()
          await importDatabase(text)
          toast.success('Database imported successfully')
          await loadStats()
        } catch (error) {
          console.error('Failed to import:', error)
          toast.error('Failed to import database')
        }

        event.target.value = ''
      }, [loadStats])

      const handleClear = useCallback(async () => {
        if (!confirm('Are you sure you want to clear all data? This cannot be undone.')) {
          return
        }

        try {
          await clearDatabase()
          toast.success('Database cleared and schema recreated successfully')
          await loadStats()
          await checkSchemaHealth()
        } catch (error) {
          console.error('Failed to clear:', error)
          toast.error('Failed to clear database')
        }
      }, [loadStats, checkSchemaHealth])

      const handleSeed = useCallback(async () => {
        try {
          await seedDatabase()
          toast.success('Sample data added successfully')
          await loadStats()
        } catch (error) {
          console.error('Failed to seed:', error)
          toast.error('Failed to add sample data')
        }
      }, [loadStats])

      const formatBytes = useCallback((bytes: number) => {
        if (bytes === 0) return '0 Bytes'
        const k = 1024
        const sizes = ['Bytes', 'KB', 'MB', 'GB']
        const i = Math.floor(Math.log(bytes) / Math.log(k))
        return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
      }, [])

      return {
        stats,
        loading,
        schemaHealth,
        checkingSchema,
        loadStats,
        checkSchemaHealth,
        handleExport,
        handleImport,
        handleClear,
        handleSeed,
        formatBytes,
      }
    }