init-database.php 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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. // Also try to load from .env.with-services for docker-compose-with-services
  33. loadEnv('.env.with-services');
  34. // Get database configuration
  35. $dbHost = getenv('DB_HOST') ?: 'localhost';
  36. $dbPort = getenv('DB_PORT') ?: '3306';
  37. $dbName = getenv('DB_NAME') ?: 'inventory_db';
  38. $dbUser = getenv('DB_USER') ?: 'root';
  39. $dbPass = getenv('DB_PASS') ?: '';
  40. echo "Database Initialization Script\n";
  41. echo "==============================\n";
  42. echo "Host: $dbHost:$dbPort\n";
  43. echo "Database: $dbName\n";
  44. echo "User: $dbUser\n\n";
  45. try {
  46. // First connect without database to create it if needed
  47. $dsn = "mysql:host=$dbHost;port=$dbPort;charset=utf8mb4";
  48. $options = [
  49. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  50. PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  51. PDO::ATTR_EMULATE_PREPARES => false,
  52. ];
  53. $pdo = new PDO($dsn, $dbUser, $dbPass, $options);
  54. echo "Connected to MySQL server successfully.\n";
  55. // Create database if it doesn't exist
  56. $pdo->exec("CREATE DATABASE IF NOT EXISTS `$dbName` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
  57. echo "Database '$dbName' created or already exists.\n";
  58. // Connect to the specific database
  59. $pdo->exec("USE `$dbName`");
  60. // Check if tables exist by checking if users table exists
  61. $stmt = $pdo->query("SHOW TABLES LIKE 'users'");
  62. $tablesExist = $stmt->rowCount() > 0;
  63. if (!$tablesExist) {
  64. echo "Tables do not exist. Creating database schema...\n";
  65. // Read and execute the complete setup script
  66. $setupFile = __DIR__ . '/setup_database.sql';
  67. if (file_exists($setupFile)) {
  68. $sql = file_get_contents($setupFile);
  69. $statements = array_filter(array_map('trim', explode(';', $sql)));
  70. foreach ($statements as $statement) {
  71. if (!empty($statement)) {
  72. try {
  73. $pdo->exec($statement);
  74. } catch (PDOException $e) {
  75. echo "Error executing statement: " . $statement . "\n";
  76. echo "Error: " . $e->getMessage() . "\n";
  77. }
  78. }
  79. }
  80. echo "Database schema created successfully.\n";
  81. } else {
  82. echo "Setup script not found: $setupFile\n";
  83. exit(1);
  84. }
  85. // Create default user if the script exists
  86. $defaultUserFile = __DIR__ . '/create_default_user.sql';
  87. if (file_exists($defaultUserFile)) {
  88. $sql = file_get_contents($defaultUserFile);
  89. $statements = array_filter(array_map('trim', explode(';', $sql)));
  90. foreach ($statements as $statement) {
  91. if (!empty($statement)) {
  92. try {
  93. $pdo->exec($statement);
  94. } catch (PDOException $e) {
  95. echo "Error creating default user: " . $e->getMessage() . "\n";
  96. }
  97. }
  98. }
  99. echo "Default user created.\n";
  100. }
  101. } else {
  102. echo "Database tables already exist. Skipping initialization.\n";
  103. }
  104. // Verify database setup by checking key tables
  105. $requiredTables = ['users', 'items', 'clients', 'projects', 'accounting_entries'];
  106. $missingTables = [];
  107. foreach ($requiredTables as $table) {
  108. $stmt = $pdo->query("SHOW TABLES LIKE '$table'");
  109. if ($stmt->rowCount() == 0) {
  110. $missingTables[] = $table;
  111. }
  112. }
  113. if (!empty($missingTables)) {
  114. echo "Warning: Missing tables: " . implode(', ', $missingTables) . "\n";
  115. exit(1);
  116. }
  117. echo "Database initialization completed successfully!\n";
  118. echo "Required tables are present and ready for use.\n";
  119. } catch (PDOException $e) {
  120. echo "Database connection failed: " . $e->getMessage() . "\n";
  121. echo "Please check your database configuration.\n";
  122. exit(1);
  123. }