init-database.php 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. #!/usr/bin/env php
  2. <?php
  3. /**
  4. * Database Initialization Script
  5. *
  6. * This script automatically creates the database and tables if they don't exist.
  7. * It runs when the container starts and checks if the database is properly set up.
  8. */
  9. // Load environment variables
  10. function loadEnv($file) {
  11. if (!file_exists($file)) {
  12. echo "Environment file not found: $file\n";
  13. return false;
  14. }
  15. $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  16. foreach ($lines as $line) {
  17. if (strpos($line, '#') === 0) continue;
  18. if (strpos($line, '=') === false) continue;
  19. list($key, $value) = explode('=', $line, 2);
  20. $key = trim($key);
  21. $value = trim($value);
  22. if (!array_key_exists($key, $_SERVER) && !array_key_exists($key, $_ENV)) {
  23. putenv(sprintf('%s=%s', $key, $value));
  24. $_ENV[$key] = $value;
  25. $_SERVER[$key] = $value;
  26. }
  27. }
  28. return true;
  29. }
  30. // Load environment from .env file
  31. loadEnv('.env');
  32. // Get database configuration
  33. $dbHost = getenv('DB_HOST') ?: 'localhost';
  34. $dbPort = getenv('DB_PORT') ?: '3306';
  35. $dbName = getenv('DB_NAME') ?: 'inventory_db';
  36. $dbUser = getenv('DB_USER') ?: 'root';
  37. $dbPass = getenv('DB_PASS') ?: '';
  38. echo "Database Initialization Script\n";
  39. echo "==============================\n";
  40. echo "Host: $dbHost:$dbPort\n";
  41. echo "Database: $dbName\n";
  42. echo "User: $dbUser\n\n";
  43. try {
  44. // First connect without database to create it if needed
  45. $dsn = "mysql:host=$dbHost;port=$dbPort;charset=utf8mb4";
  46. $options = [
  47. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  48. PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  49. PDO::ATTR_EMULATE_PREPARES => false,
  50. ];
  51. $pdo = new PDO($dsn, $dbUser, $dbPass, $options);
  52. echo "Connected to MySQL server successfully.\n";
  53. // Create database if it doesn't exist
  54. $pdo->exec("CREATE DATABASE IF NOT EXISTS `$dbName` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
  55. echo "Database '$dbName' created or already exists.\n";
  56. // Connect to the specific database
  57. $pdo->exec("USE `$dbName`");
  58. // Check if tables exist by checking if users table exists
  59. $stmt = $pdo->query("SHOW TABLES LIKE 'users'");
  60. $tablesExist = $stmt->rowCount() > 0;
  61. if (!$tablesExist) {
  62. echo "Tables do not exist. Creating database schema...\n";
  63. // Read and execute the complete setup script
  64. $setupFile = __DIR__ . '/setup_database.sql';
  65. if (file_exists($setupFile)) {
  66. $sql = file_get_contents($setupFile);
  67. $statements = array_filter(array_map('trim', explode(';', $sql)));
  68. foreach ($statements as $statement) {
  69. if (!empty($statement)) {
  70. try {
  71. $pdo->exec($statement);
  72. } catch (PDOException $e) {
  73. echo "Error executing statement: " . $statement . "\n";
  74. echo "Error: " . $e->getMessage() . "\n";
  75. }
  76. }
  77. }
  78. echo "Database schema created successfully.\n";
  79. } else {
  80. echo "Setup script not found: $setupFile\n";
  81. exit(1);
  82. }
  83. // Create default user if the script exists
  84. $defaultUserFile = __DIR__ . '/create_default_user.sql';
  85. if (file_exists($defaultUserFile)) {
  86. $sql = file_get_contents($defaultUserFile);
  87. $statements = array_filter(array_map('trim', explode(';', $sql)));
  88. foreach ($statements as $statement) {
  89. if (!empty($statement)) {
  90. try {
  91. $pdo->exec($statement);
  92. } catch (PDOException $e) {
  93. echo "Error creating default user: " . $e->getMessage() . "\n";
  94. }
  95. }
  96. }
  97. echo "Default user created.\n";
  98. }
  99. } else {
  100. echo "Database tables already exist. Skipping initialization.\n";
  101. }
  102. // Verify database setup by checking key tables
  103. $requiredTables = ['users', 'items', 'clients', 'projects', 'accounting_entries'];
  104. $missingTables = [];
  105. foreach ($requiredTables as $table) {
  106. $stmt = $pdo->query("SHOW TABLES LIKE '$table'");
  107. if ($stmt->rowCount() == 0) {
  108. $missingTables[] = $table;
  109. }
  110. }
  111. if (!empty($missingTables)) {
  112. echo "Warning: Missing tables: " . implode(', ', $missingTables) . "\n";
  113. exit(1);
  114. }
  115. echo "Database initialization completed successfully!\n";
  116. echo "Required tables are present and ready for use.\n";
  117. } catch (PDOException $e) {
  118. echo "Database connection failed: " . $e->getMessage() . "\n";
  119. echo "Please check your database configuration.\n";
  120. exit(1);
  121. }