כלי עזר למסד נתונים
מרחב השמות Xmf\Database מספק שיעורים כדי לפשט את משימות תחזוקת מסד הנתונים הקשורות להתקנה ועדכון של מודולי XOOPS. כלי עזר אלה מטפלים בהעברת סכימה, שינויי טבלה וטעינת נתונים ראשונית.
סקירה כללית
Section titled “סקירה כללית”כלי השירות של מסד הנתונים כוללים:
- טבלאות - בנייה וביצוע של הצהרות DDL עבור שינויים בטבלה
- הגירה - סנכרון סכימת מסד נתונים בין גרסאות מודול
- TableLoad - טעינת נתונים ראשוניים לטבלאות
Xmf\Database\Tables
Section titled “Xmf\Database\Tables”המחלקה Tables מפשטת יצירה ושינוי של טבלאות מסד נתונים. הוא בונה תור עבודה של הצהרות DDL (שפת הגדרת נתונים) המבוצעות יחד.
תכונות עיקריות
Section titled “תכונות עיקריות”- טוען סכימה נוכחית מטבלאות קיימות
- שינויים בתורים ללא ביצוע מיידי
- לוקח בחשבון את המצב הנוכחי בעת קביעת העבודה
- מטפל אוטומטית בקידומת הטבלה XOOPS
תחילת העבודה
Section titled “תחילת העבודה”use Xmf\Database\Tables;
// Create a new Tables instance$tables = new Tables();
// Load an existing table or start new schema$tables->addTable('mymodule_items');
// For existing tables only (fails if table doesn't exist)$tables->useTable('mymodule_items');פעולות טבלה
Section titled “פעולות טבלה”שנה שם של טבלה
Section titled “שנה שם של טבלה”$tables = new Tables();$tables->addTable('mymodule_old_name');$tables->renameTable('mymodule_old_name', 'mymodule_new_name');$tables->executeQueue();הגדר אפשרויות טבלה
Section titled “הגדר אפשרויות טבלה”$tables->addTable('mymodule_items');$tables->setTableOptions('mymodule_items', 'ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');$tables->executeQueue();זרוק טבלה
Section titled “זרוק טבלה”$tables->addTable('mymodule_temp');$tables->dropTable('mymodule_temp');$tables->executeQueue();העתק טבלה
Section titled “העתק טבלה”// Copy structure only$tables->copyTable('mymodule_items', 'mymodule_items_backup', false);
// Copy structure and data$tables->copyTable('mymodule_items', 'mymodule_items_backup', true);$tables->executeQueue();עבודה עם עמודות
Section titled “עבודה עם עמודות”הוסף עמודה
Section titled “הוסף עמודה”$tables = new Tables();$tables->addTable('mymodule_items');
$tables->addColumn( 'mymodule_items', 'status', "TINYINT(1) NOT NULL DEFAULT '1'");
$tables->executeQueue();שנה עמודה
Section titled “שנה עמודה”$tables->useTable('mymodule_items');
// Change column attributes$tables->alterColumn( 'mymodule_items', 'title', "VARCHAR(255) NOT NULL DEFAULT ''");
// Rename and modify column$tables->alterColumn( 'mymodule_items', 'old_column_name', "VARCHAR(100) NOT NULL", 'new_column_name');
$tables->executeQueue();קבל תכונות עמודות
Section titled “קבל תכונות עמודות”$tables->useTable('mymodule_items');$attributes = $tables->getColumnAttributes('mymodule_items', 'title');// Returns: "VARCHAR(255) NOT NULL DEFAULT ''"שחרר עמודה
Section titled “שחרר עמודה”$tables->useTable('mymodule_items');$tables->dropColumn('mymodule_items', 'obsolete_field');$tables->executeQueue();עבודה עם אינדקסים
Section titled “עבודה עם אינדקסים”קבל אינדקסים של טבלאות
Section titled “קבל אינדקסים של טבלאות”$tables->useTable('mymodule_items');$indexes = $tables->getTableIndexes('mymodule_items');
// Returns array like:// [// 'PRIMARY' => ['columns' => 'item_id', 'unique' => true],// 'idx_category' => ['columns' => 'category_id', 'unique' => false]// ]הוסף מפתח ראשי
Section titled “הוסף מפתח ראשי”$tables->addTable('mymodule_items');$tables->addPrimaryKey('mymodule_items', 'item_id');
// Composite primary key$tables->addPrimaryKey('mymodule_item_tags', 'item_id, tag_id');$tables->executeQueue();הוסף אינדקס
Section titled “הוסף אינדקס”$tables->useTable('mymodule_items');
// Simple index$tables->addIndex('idx_category', 'mymodule_items', 'category_id');
// Unique index$tables->addIndex('idx_slug', 'mymodule_items', 'slug', true);
// Composite index$tables->addIndex('idx_cat_status', 'mymodule_items', 'category_id, status');
$tables->executeQueue();זרוק אינדקס
Section titled “זרוק אינדקס”$tables->useTable('mymodule_items');$tables->dropIndex('idx_old_index', 'mymodule_items');$tables->executeQueue();שחרר את כל האינדקסים הלא ראשיים
Section titled “שחרר את כל האינדקסים הלא ראשיים”// Useful for cleaning up auto-generated index names$tables->dropIndexes('mymodule_items');$tables->executeQueue();שחרר מפתח ראשי
Section titled “שחרר מפתח ראשי”$tables->dropPrimaryKey('mymodule_items');$tables->executeQueue();פעולות נתונים
Section titled “פעולות נתונים”הוסף נתונים
Section titled “הוסף נתונים”$tables->useTable('mymodule_categories');
$tables->insert('mymodule_categories', [ 'category_id' => 1, 'name' => 'General', 'weight' => 0]);
// Without automatic quoting (for expressions)$tables->insert('mymodule_logs', [ 'created' => 'NOW()', 'message' => "'Test message'"], false);
$tables->executeQueue();עדכן נתונים
Section titled “עדכן נתונים”$tables->useTable('mymodule_items');
// Update with criteria object$criteria = new Criteria('status', 0);$tables->update('mymodule_items', ['status' => 1], $criteria);
// Update with string criteria$tables->update('mymodule_items', ['hits' => 0], 'hits IS NULL');
$tables->executeQueue();מחק נתונים
Section titled “מחק נתונים”$tables->useTable('mymodule_items');
// Delete with criteria$criteria = new Criteria('status', -1);$tables->delete('mymodule_items', $criteria);
// Delete with string criteria$tables->delete('mymodule_items', 'created < DATE_SUB(NOW(), INTERVAL 1 YEAR)');
$tables->executeQueue();חתוך טבלה
Section titled “חתוך טבלה”$tables->useTable('mymodule_cache');$tables->truncate('mymodule_cache');$tables->executeQueue();ניהול תורי עבודה
Section titled “ניהול תורי עבודה”ביצוע תור
Section titled “ביצוע תור”// Normal execution (respects HTTP method safety)$result = $tables->executeQueue();
// Force execution even on GET requests$result = $tables->executeQueue(true);
if (!$result) { echo 'Error: ' . $tables->getLastError();}אפס תור
Section titled “אפס תור”// Clear queue without executing$tables->resetQueue();הוסף Raw SQL
Section titled “הוסף Raw SQL”// Add custom SQL to the queue$tables->addToQueue('ALTER TABLE ' . $GLOBALS['xoopsDB']->prefix('mymodule_items') . ' CONVERT TO CHARACTER SET utf8mb4');$tables->executeQueue();טיפול בשגיאות
Section titled “טיפול בשגיאות”$tables = new Tables();
if (!$tables->addTable('mymodule_items')) { $error = $tables->getLastError(); $errno = $tables->getLastErrNo(); // Handle error}Xmf\Database\Migrate
Section titled “Xmf\Database\Migrate”מחלקה Migrate מפשטת סנכרון של שינויים במסד הנתונים בין גרסאות מודול. זה מרחיב את Tables עם השוואת סכמות וסנכרון אוטומטי.
שימוש בסיסי
Section titled “שימוש בסיסי”use Xmf\Database\Migrate;
// Create migrate instance for a module$migrate = new Migrate('mymodule');
// Synchronize database with target schema$migrate->synchronizeSchema();בעדכון מודול
Section titled “בעדכון מודול”נקרא בדרך כלל בפונקציית xoops_module_pre_update_* של המודול:
function xoops_module_pre_update_mymodule($module, $previousVersion){ $migrate = new \Xmf\Database\Migrate('mymodule');
// Perform any pre-sync actions (renames, etc.) // ...
// Synchronize schema return $migrate->synchronizeSchema();}קבלת הצהרות DDL
Section titled “קבלת הצהרות DDL”עבור מסדי נתונים גדולים או העברות שורת פקודה:
$migrate = new Migrate('mymodule');$statements = $migrate->getSynchronizeDDL();
// Execute statements in batches or from CLIforeach ($statements as $sql) { // Process each statement}פעולות לפני סנכרון
Section titled “פעולות לפני סנכרון”שינויים מסוימים דורשים טיפול מפורש לפני סנכרון. הארך את Migrate עבור העברות מורכבות:
class MyModuleMigrate extends \Xmf\Database\Migrate{ public function preSyncActions() { // Rename a table before sync $this->useTable('mymodule_old_name'); $this->renameTable('mymodule_old_name', 'mymodule_new_name'); $this->executeQueue();
// Rename a column $this->useTable('mymodule_items'); $this->alterColumn( 'mymodule_items', 'old_column', 'VARCHAR(255) NOT NULL', 'new_column' ); $this->executeQueue(); }}
// Usage$migrate = new MyModuleMigrate('mymodule');$migrate->preSyncActions();$migrate->synchronizeSchema();ניהול סכימה
Section titled “ניהול סכימה”קבל סכימה נוכחית
Section titled “קבל סכימה נוכחית”$migrate = new Migrate('mymodule');$currentSchema = $migrate->getCurrentSchema();קבל סכימת יעד
Section titled “קבל סכימת יעד”$targetSchema = $migrate->getTargetDefinitions();שמור סכימה נוכחית
Section titled “שמור סכימה נוכחית”למפתחי מודול ללכוד סכימה לאחר שינויים במסד הנתונים:
$migrate = new Migrate('mymodule');$migrate->saveCurrentSchema();// Saves schema to module's sql/migrate.ymlהערת מפתח: בצע תחילה שינויים במסד הנתונים ולאחר מכן הפעל את
saveCurrentSchema(). אל תערוך ידנית את קובץ הסכימה שנוצר.
Xmf\Database\TableLoad
Section titled “Xmf\Database\TableLoad”מחלקה TableLoad מפשטת טעינת נתונים ראשוניים לטבלאות. שימושי לזריעת טבלאות עם נתוני ברירת מחדל במהלך התקנת המודול.
טעינת נתונים ממערכים
Section titled “טעינת נתונים ממערכים”use Xmf\Database\TableLoad;
$data = [ ['category_id' => 1, 'name' => 'General', 'weight' => 0], ['category_id' => 2, 'name' => 'News', 'weight' => 10], ['category_id' => 3, 'name' => 'Events', 'weight' => 20]];
$count = TableLoad::loadTableFromArray('mymodule_categories', $data);echo "Inserted {$count} rows";טוען נתונים מ-YAML
Section titled “טוען נתונים מ-YAML”// Load from YAML file$count = TableLoad::loadTableFromYamlFile( 'mymodule_categories', XOOPS_ROOT_PATH . '/modules/mymodule/sql/categories.yml');פורמט YAML:
- category_id: 1 name: General weight: 0- category_id: 2 name: News weight: 10חילוץ נתונים
Section titled “חילוץ נתונים”סופר שורות
Section titled “סופר שורות”// Count all rows$total = TableLoad::countRows('mymodule_items');
// Count with criteria$criteria = new Criteria('status', 1);$activeCount = TableLoad::countRows('mymodule_items', $criteria);חלץ שורות
Section titled “חלץ שורות”// Extract all rows$rows = TableLoad::extractRows('mymodule_items');
// Extract with criteria$criteria = new Criteria('category_id', 5);$rows = TableLoad::extractRows('mymodule_items', $criteria);
// Skip certain columns$rows = TableLoad::extractRows('mymodule_items', null, ['password', 'token']);שמירת נתונים ב-YAML
Section titled “שמירת נתונים ב-YAML”// Save all dataTableLoad::saveTableToYamlFile( 'mymodule_categories', '/path/to/categories.yml');
// Save filtered data$criteria = new Criteria('is_default', 1);TableLoad::saveTableToYamlFile( 'mymodule_settings', '/path/to/default_settings.yml', $criteria);
// Save without certain columnsTableLoad::saveTableToYamlFile( 'mymodule_items', '/path/to/items.yml', null, ['created', 'modified']);חתוך טבלה
Section titled “חתוך טבלה”// Empty a table$affectedRows = TableLoad::truncateTable('mymodule_cache');דוגמה להגירה מלאה
Section titled “דוגמה להגירה מלאה”xoops_version.php
Section titled “xoops_version.php”$modversion['sqlfile']['mysql'] = 'sql/mysql.sql';$modversion['tables'] = [ 'mymodule_items', 'mymodule_categories', 'mymodule_settings'];include/onupdate.php
Section titled “include/onupdate.php”<?phpuse Xmf\Database\Migrate;use Xmf\Database\Tables;use Xmf\Database\TableLoad;
function xoops_module_pre_update_mymodule($module, $previousVersion){ // Create custom migrate class $migrate = new MyModuleMigrate('mymodule');
// Handle version-specific migrations if ($previousVersion < 120) { // Version 1.2.0 renamed a table $migrate->renameOldTable(); }
if ($previousVersion < 130) { // Version 1.3.0 renamed a column $migrate->renameOldColumn(); }
// Synchronize schema return $migrate->synchronizeSchema();}
function xoops_module_update_mymodule($module, $previousVersion){ // Post-update data migrations if ($previousVersion < 130) { // Load new default settings TableLoad::loadTableFromYamlFile( 'mymodule_settings', XOOPS_ROOT_PATH . '/modules/mymodule/sql/new_settings.yml' ); }
return true;}
class MyModuleMigrate extends Migrate{ public function renameOldTable() { if ($this->useTable('mymodule_posts')) { $this->renameTable('mymodule_posts', 'mymodule_items'); $this->executeQueue(); } }
public function renameOldColumn() { if ($this->useTable('mymodule_items')) { $this->alterColumn( 'mymodule_items', 'post_title', "VARCHAR(255) NOT NULL DEFAULT ''", 'title' ); $this->executeQueue(); } }}API הפניה
Section titled “API הפניה”Xmf\Database\Tables
Section titled “Xmf\Database\Tables”| שיטה | תיאור |
|---|---|
addTable($table) | טען או צור סכימת טבלה |
useTable($table) | טען טבלה קיימת בלבד |
renameTable($table, $newName) | שינוי שם טבלת התורים |
setTableOptions($table, $options) | שינוי אפשרויות טבלת התורים |
dropTable($table) | ירידת טבלת תור |
copyTable($table, $newTable, $withData) | עותק טבלת תור |
addColumn($table, $column, $attributes) | הוספת עמודות בתור |
alterColumn($table, $column, $attributes, $newName) | שינוי עמודה בתור |
getColumnAttributes($table, $column) | קבל הגדרת עמודה |
dropColumn($table, $column) | ירידת עמודה בתור |
getTableIndexes($table) | קבל הגדרות אינדקס |
addPrimaryKey($table, $column) | מפתח ראשי בתור |
addIndex($name, $table, $column, $unique) | מדד התורים |
dropIndex($name, $table) | ירידה במדד התור |
dropIndexes($table) | תור את כל ירידות המדד |
dropPrimaryKey($table) | הורדת מפתח ראשי בתור |
insert($table, $columns, $quote) | הוספת תור |
update($table, $columns, $criteria, $quote) | עדכון תור |
delete($table, $criteria) | מחיקת תור |
truncate($table) | קיצור תור |
executeQueue($force) | ביצוע פעולות בתור |
resetQueue() | נקה תור |
addToQueue($sql) | הוסף גולמי SQL |
getLastError() | קבל הודעת שגיאה אחרונה |
getLastErrNo() | קבל קוד שגיאה אחרון |
Xmf\Database\Migrate
Section titled “Xmf\Database\Migrate”| שיטה | תיאור |
|---|---|
__construct($dirname) | צור עבור מודול |
synchronizeSchema() | סנכרן מסד נתונים למיקוד |
getSynchronizeDDL() | קבל הצהרות DDL |
preSyncActions() | ביטול עבור פעולות מותאמות אישית |
getCurrentSchema() | קבל סכימת מסד נתונים נוכחית |
getTargetDefinitions() | קבל סכימת יעד |
saveCurrentSchema() | שמור סכימה למפתחים |
Xmf\Database\TableLoad
Section titled “Xmf\Database\TableLoad”| שיטה | תיאור |
|---|---|
loadTableFromArray($table, $data) | טען ממערך |
loadTableFromYamlFile($table, $file) | טען מ-YAML |
truncateTable($table) | שולחן ריק |
countRows($table, $criteria) | ספירת שורות |
extractRows($table, $criteria, $skip) | חלץ שורות |
saveTableToYamlFile($table, $file, $criteria, $skip) | שמור ב-YAML |
ראה גם
Section titled “ראה גם”- ../XMF-Framework - סקירת מסגרת
- ../Basics/XMF-Module-Helper - כיתת עוזר מודול
- Metagen - כלי עזר ל- Metadata
#xmf #בסיס נתונים #הגירה #סכימה #טבלאות #ddl