MongoDB Tutorial 3: Create database

From The Uniform Server Wiki
Jump to navigation Jump to search

 

MongoDB Production Standalone
UniServer 6-Carbo.

Create a database and user

Introduction

Most MySQL administrators will be familiar with creating a restricted user and assigning that user to a specific database. MongDB does things slightly different when a database is first used that database is created on the fly. Selecting a non-existent database and assigning a user creates that database. If database and user exists and password is different the password will be updated.

On previous page I explained using a multi-purpose function that performs the above. This page covers making that function more accessible by adding a cosmetic windows interface.

Template

I have provided a windows temple for this tutorial topic save the following to a new file z_mongo\mongodb_1\control \window_create_database.inc.php.

<?php

//-- Constants ----------------------------------------------------------------

define('IDC_USER_NAME',        3010); // Text box New user name
define('IDC_USER_PASSWORD',    3020); // Text box New user password
define('IDC_USER_DATABASE',    3030); // Text box Database name
define('IDC_USER_CANCEL',      3040); // Button Reset to default
define('IDC_USER_CREATE',      3050); // Button Create new user
define('IDC_USER_HELP',        3060); // Help

define('IDC_USER_LISTBOX',     3070); // Database list box

// Common variables

$mongo_user_win;        // Window handle
$user_new_db;           // List of dbs

//=== Create function =========================================================
function create_database_window($parent){
  global $mongo_user_win;
  global $user_new_db;

//=== 1) Create main window ---------------------------------------------------

$mongo_user_win = wb_create_window($parent, ModalDialog, "MongoDB Create Databse assign user", WBC_CENTER, WBC_CENTER, 294, 284,
  WBC_INVISIBLE | WBC_NOTIFY | WBC_TOP, WBC_HEADERSEL);

//=== 2) Create controls for the main window ----------------------------------

wb_create_control($mongo_user_win, Frame, 'User details and db name', 5, 5, 275, 130, 0, 0, 0, 0);
wb_create_control($mongo_user_win, Label, 'User Name',            15, 25,   50, 15, 0, 0, 0, 0);
wb_create_control($mongo_user_win, EditBox, '',                   75, 25,  195, 20, IDC_USER_NAME, 0, 0, 0);
wb_create_control($mongo_user_win, Label, 'Password',             15, 50,   45, 15, 0, 0x00000000, 0, 0);
wb_create_control($mongo_user_win, EditBox, '',                   75, 50,  195, 20, IDC_USER_PASSWORD, 0, 0, 0);
wb_create_control($mongo_user_win, Label, 'Database',             15, 75,   45, 15, 0, 0x00000000, 0, 0);
wb_create_control($mongo_user_win, EditBox, '',                   75, 75,  195, 20, IDC_USER_DATABASE, 0, 0, 0);
wb_create_control($mongo_user_win, PushButton, 'Help',            15, 105,  50, 25, IDC_USER_HELP, 0, 0, 0);
wb_create_control($mongo_user_win, PushButton, 'Create Change',   75, 105, 115, 25, IDC_USER_CREATE, 0, 0, 0);
wb_create_control($mongo_user_win, PushButton, 'Cancel',         200, 105,  70, 25, IDC_USER_CANCEL, 0, 0, 0);

wb_create_control($mongo_user_win, Frame, 'Select a database', 5, 140, 275, 105, 0, 0x00000000, 0, 0);
$list = wb_create_control($mongo_user_win, ListView, 'Head1',  20, 155, 250, 85, IDC_USER_LISTBOX, 0x00100080, 0, 0);


//=== INIT ====================
//--- Set up listview ---

//=== END INIT ================   

//=== 3) Assign handler function to the main window  --------------------------
wb_set_handler($mongo_user_win, "process_mysql_user");
  wb_set_image($mongo_user_win, getcwd()."/images/utray.ico");  // Add logo   
  wb_set_visible($mongo_user_win, true);               // Show window         

//=== 5) Enter application loop -----------------------------------------------
//wb_main_loop();                                  

}//==================================================== End Create function ===

//=== 4) Handler Function -----------------------------------------------------
function process_mysql_user($window, $id, $ctrl=0, $lparam1=0, $lparam2=0){
  global $user_new_db;

  switch($id) { 

   case IDCLOSE:                          // Constant IDCLOSE (8) predefined 
    wb_destroy_window($window);           // Destroy the window
   break; 
  }
}
//==================================================== End Handler Function ===
?>
  • Template contains unique contatnts for the windows components. Some common variables are defined.
  • We are wrapping the pop-up windows in a function create_database_window($parent).
  • A modaldialouge window is created invisible this allows it to be populated with data before being displayed.
  • Components are added labels, buttons and edit boxes. Only new component is the list view.
  • A section is reserved to set-up list view(add titles etc)
  • Next section assigns a handler function and logo. With the window completed it is displayed.
  • There is no need to run function wb_main_loop() this window is a child.
  • Finally the template contains a handler function.

Top

Test

Edit file z_mongo\mongodb_1\control\mongo_db.php Add the following to the include section:

include_once "window_create_database.inc.php"; // Window create database and assign user

Change the following section as shown:

   //=== Display help info ====================================================
   case ID_HELP_BUTTON:          // Button 

      create_database_window($window);
//    create_port_change_window($window);
//    wb_exec('Notepad',INFO_TXT);

   break; 
   //================================================ END Display help info ===

Run

  • Run Run_mongo_db.bat
  • Click "Help and Information" button
  • Result shown on right

I mentioned it is cosmetic! Looks pretty with no functionality.

Note:

  • This pop-up requires no separate initialisation function.
  • List box can be populated when it is created.

Mongo c initial 5.gif

Top

List view - List databases

Add yhe following code

//=== INIT ====================
//--- Set up listview ---

  // Set column titles and widths
  wb_set_text($list, array(
    array("List of Databases", 200),
  ));

  $user_new_db = list_dbs_auth();        // Get list of dbs

  // Create rows and columns
  wb_create_items($list,$user_new_db);   // Fill list

//--- End Set up listview ---

//=== END INIT ================ 
  • The dark header of list view is populated with a column title
  • Function wb_set_text requires an handle $list to the list. This is followed by an array of titles/widths only a single column in this case.
  • We obtain an array of databases and save to variable $user_new_db
  • This array is used to populate list view using function wb_create_items. It takes as parameters handle $list and the array of dbs

Top

Item Clicked

When an item is clicked we want that item to be displayed in the database edit text window.

  //=== Item selected from list ==============================================
  case IDC_USER_LISTBOX:                   // A row was selected from db list

  $sel = wb_get_selected($ctrl);               // Get selection
  $sel = $sel ? implode(", ", $sel) : "none";  // Set selected value 

  if($sel =="none"){
    wb_set_text(wb_get_control($window, IDC_USER_DATABASE),""); // Reset Set DB
  }
  else{

    $selected_index = $sel;                 // Save Array index
    $contents = wb_get_text($ctrl);         // Get row selected Returns an array of arrays
    $first_array = $contents[0];            // Select first array (which is selected row)
    $db_selected_name = $first_array[0];    // Select first column (which is db)
    wb_set_text(wb_get_control($window, IDC_USER_DATABASE),$db_selected_name);   // Set DB
  }
  break;
  //============================================== Item selected from list ===
  • Item in list view click this event is passed to the handler function
  • List view is detected by a case statement using IDC_USER_LISTBOX
  • Either an item or blank item was clicked first we obtain an handle
  • This is used to determine what was returned.
  • sel is either none or an index
  • If "none" set the database list box to blank
  • If it was an index save it for later use
  • Get select name and set edit box accordingly

Top

User name

Selecting a database we want to display the user assigned to it. Every database created will have a single user assigned.

Well that’s an assumption if more users have been assigned only the first will be displayed.

//=== Item selected from list ==============================================
  case IDC_USER_LISTBOX:                   // A row was selected from db list

  $sel = wb_get_selected($ctrl);               // Get selection
  $sel = $sel ? implode(", ", $sel) : "none";  // Set selected value 

  if($sel =="none"){
    wb_set_text(wb_get_control($window, IDC_USER_DATABASE),""); // Reset Set DB
    wb_set_text(wb_get_control($window, IDC_USER_NAME),"");     // Reset User name
  }
  else{
    $selected_index = $sel;                 // Save Array index
    $contents = wb_get_text($ctrl);         // Get row selected Returns an array of arrays
    $first_array = $contents[0];            // Select first array (which is selected row)
    $db_selected_name = $first_array[0];    // Select first column (which is db)
    $db_selected_name = trim($db_selected_name); // Clean

    wb_set_text(wb_get_control($window, IDC_USER_DATABASE),$db_selected_name); // Set DB

    $users_array = get_user_auth($db_selected_name); //Select db return user/s in array

    if(empty($users_array)){       // No users
      wb_set_text(wb_get_control($window, IDC_USER_NAME),"");              // Reset User name
    }
    else{                          // Selet first user and display
      wb_set_text(wb_get_control($window, IDC_USER_NAME),$users_array[0]); // Set User name
    }
  }
  break;
  //============================================== Item selected from list ===
  • When a user clicks a database its name is stored in variable $db_selected_name
  • This is used to obtain an array of users using function get_user_auth($db_selected_name)
  • Returned array is saved in variable $users_array
    • If empty reset user name edit box
    • Not empty pick first user from array and display in edit box.
  • End case

Top

Cancel

Cancel button is provided as a quick way to restore window to its initial state.

   //=== CANCEL ===============================================================
   // Restore defaults

   case  IDC_USER_CANCEL:                       

    //-- Reset text boxes
    wb_set_text(wb_get_control($window, IDC_USER_NAME),"");       // Clear name
    wb_set_text(wb_get_control($window, IDC_USER_PASSWORD),"");   // Clear password
    wb_set_text(wb_get_control($window, IDC_USER_DATABASE),"");   // Clear DB


    //--- Reset selected list box
    $temp = $user_new_db;                                               // Save old array        
    wb_delete_items (wb_get_control($window, IDC_USER_LISTBOX),NULL);   // Delete all list view entries
    wb_create_items (wb_get_control($window, IDC_USER_LISTBOX),$temp);  // Add array

   break;
   //============================================================ END CANCEL ===
  • All edit boxes are cleared
  • List array is set to NULL clearing all list entries
  • Original array is restored

Top

Create database or update password

Button Create or Update reads the text fields and validates each one. On validation creates a new database or updates a user password. List of databases is refreshed.

  //=== CREATE DATABASE ASIGN USER ============================================
  case  IDC_USER_CREATE: 

  $name  = wb_get_text(wb_get_control($window, IDC_USER_NAME));   // Get name
  $pass  = wb_get_text(wb_get_control($window, IDC_USER_PASSWORD)); // Get pass
  $db    = wb_get_text(wb_get_control($window,  IDC_USER_DATABASE));// Get db

 // Validate - name alphanumeric
 if (!(preg_match("/^[A-Za-z0-9_]+$/", $name ))) {
  $str  = "";
  $str .= "If name is empty please enter a name\n";
  $str .= "Only alphanumeric characters allowed";
  wb_message_box($window, $str,"User Name", WBC_INFO); 
  break;
 }

 // Validate password - require six or more alphanumeric characters
 if (!(preg_match("/^[A-Za-z0-9_]{6,}$/", $pass))) {
  $str  = "";
  $str .= "If password is empty please enter a password\n";
  $str .= "Enter six or more alphanumeric characters\n";
  $str .= "Only alphanumeric characters allowed";
  wb_message_box($window, $str,"Password", WBC_INFO); 
   break;
 }

 // Validate - db name 
 if (!(preg_match("/^[A-Za-z0-9_]+$/", $db))) {
  $str  = "";
  $str .= "If name is empty please enter a name\n";
  $str .= "Only alphanumeric characters allowed";
  wb_message_box($window, $str,"DB Name", WBC_INFO); 
  break;
 }

 // Create database or update user password
 create_db_auth($db,$name,$pass); 

 // Refresh database list
 $user_new_db = list_dbs_auth();        // Get list of dbs
 $temp = $user_new_db;                                                    
 wb_delete_items (wb_get_control($window, IDC_USER_LISTBOX),NULL);   
 wb_create_items (wb_get_control($window, IDC_USER_LISTBOX),$temp);  

   break;
  //======================================= END CREATE DATABASE ASIGN USER ===
  • All three-text fields are read into variables $db,$name and $pass
  • Each is checked against a list of valid characters.
    • Note: You can add to this list of valid characters
    • Password is forced to have a minimum of six characters
  • With all three fields validated either a new database is created or user password updated.
  • List of databases is refreshed.

Top

Can script be run

At this stage we have not decided how to run this script. There are two options either from a drop down menu or using a button on main application.

Script requires MongoDB server to be running, we can prevent the script from being called by disabling a button. However this is not possible with a drop down menu hence we need to include a check and alert a user accordingly.

// Check server running
if(!mongodb_running()){
 $str  = "";
 $str .= "This item requires access to a running server.\n";
 $str .= "Please start MonGoDB server and run\n";
 $str .= "this item again.";
 wb_message_box(NULL, $str,"Server not running", WBC_INFO); 
 return; // Give up
}

Top

Complete Script

<?php

//-- Constants ----------------------------------------------------------------

define('IDC_USER_NAME',        3010); // Text box New user name
define('IDC_USER_PASSWORD',    3020); // Text box New user password
define('IDC_USER_DATABASE',    3030); // Text box Database name
define('IDC_USER_CANCEL',      3040); // Button Reset to default
define('IDC_USER_CREATE',      3050); // Button Create new user
define('IDC_USER_HELP',        3060); // Help


define('IDC_USER_LISTBOX',     3070); // Database list box

// Common variables

$mongo_user_win;        // Window handle
$user_new_db;           // List of dbs

//=== Create function =========================================================
function create_database_window($parent){
  global $mongo_user_win;
  global $user_new_db;

// Check server running
if(!mongodb_running()){
 $str  = "";
 $str .= "This item requires access to a running server.\n";
 $str .= "Please start MonGoDB server and run\n";
 $str .= "this item again.";
 wb_message_box(NULL, $str,"Server not running", WBC_INFO); 
 return; // Give up
}

//=== 1) Create main window ---------------------------------------------------

$mongo_user_win = wb_create_window($parent, ModalDialog, "MongoDB Create Databse assign user", WBC_CENTER, WBC_CENTER, 294, 284,
  WBC_INVISIBLE | WBC_NOTIFY | WBC_TOP, WBC_HEADERSEL);

//=== 2) Create controls for the main window ----------------------------------

wb_create_control($mongo_user_win, Frame, 'User details and db name', 5, 5, 275, 130, 0, 0, 0, 0);
wb_create_control($mongo_user_win, Label, 'User Name',             15, 25,   50, 15, 0, 0, 0, 0);
wb_create_control($mongo_user_win, EditBox, '',                    75, 25,  195, 20, IDC_USER_NAME, 0, 0, 0);
wb_create_control($mongo_user_win, Label, 'Password',              15, 50,   45, 15, 0, 0x00000000, 0, 0);
wb_create_control($mongo_user_win, EditBox, '',                    75, 50,  195, 20, IDC_USER_PASSWORD, 0, 0, 0);
wb_create_control($mongo_user_win, Label, 'Database',              15, 75,   45, 15, 0, 0x00000000, 0, 0);
wb_create_control($mongo_user_win, EditBox, '',                    75, 75,  195, 20, IDC_USER_DATABASE, 0, 0, 0);
wb_create_control($mongo_user_win, PushButton, 'Help',             15, 105,  50, 25, IDC_USER_HELP, 0, 0, 0);
wb_create_control($mongo_user_win, PushButton, 'Create or Change', 75, 105, 115, 25, IDC_USER_CREATE, 0, 0, 0);
wb_create_control($mongo_user_win, PushButton, 'Cancel',          200, 105,  70, 25, IDC_USER_CANCEL, 0, 0, 0);

wb_create_control($mongo_user_win, Frame, 'Select a database', 5, 140, 275, 105, 0, 0x00000000, 0, 0);
$list = wb_create_control($mongo_user_win, ListView, 'Head1',  20, 155, 250, 85, IDC_USER_LISTBOX, 0x00100080, 0, 0);


//=== INIT ====================
//--- Set up listview ---

  // Set column titles and widths
  wb_set_text($list, array(
    array("List of Databases", 200),
  ));

  $user_new_db = list_dbs_auth();        // Get list of dbs

  // Create rows and columns
  wb_create_items($list,$user_new_db);   // Fill list

//--- End Set up listview ---

//=== END INIT ================   

//=== 3) Assign handler function to the main window  --------------------------
wb_set_handler($mongo_user_win, "process_mysql_user");
  wb_set_image($mongo_user_win, getcwd()."/images/utray.ico");  // Add logo   
  wb_set_visible($mongo_user_win, true);               // Show window         

//=== 5) Enter application loop -----------------------------------------------
//wb_main_loop();                                  

}//==================================================== End Create function ===

//=== 4) Handler Function -----------------------------------------------------
function process_mysql_user($window, $id, $ctrl=0, $lparam1=0, $lparam2=0){
  global $user_new_db;

  switch($id) { 

  //=== CREATE DATABASE ASIGN USER ============================================
  case  IDC_USER_CREATE: 

  $name  = wb_get_text(wb_get_control($window, IDC_USER_NAME));   // Get name
  $pass  = wb_get_text(wb_get_control($window, IDC_USER_PASSWORD)); // Get pass
  $db    = wb_get_text(wb_get_control($window,  IDC_USER_DATABASE));// Get db

 // Validate - name alphanumeric
 if (!(preg_match("/^[A-Za-z0-9_]+$/", $name ))) {
  $str  = "";
  $str .= "If name is empty please enter a name\n";
  $str .= "Only alphanumeric characters allowed";
  wb_message_box($window, $str,"User Name", WBC_INFO); 
  break;
 }

 // Validate password - require six or more alphanumeric characters
 if (!(preg_match("/^[A-Za-z0-9_]{6,}$/", $pass))) {
  $str  = "";
  $str .= "If password is empty please enter a password\n";
  $str .= "Enter six or more alphanumeric characters\n";
  $str .= "Only alphanumeric characters allowed";
  wb_message_box($window, $str,"Password", WBC_INFO); 
   break;
 }

 // Validate - db name 
 if (!(preg_match("/^[A-Za-z0-9_]+$/", $db))) {
  $str  = "";
  $str .= "If name is empty please enter a name\n";
  $str .= "Only alphanumeric characters allowed";
  wb_message_box($window, $str,"DB Name", WBC_INFO); 
  break;
 }

 // Create database or update user password
 create_db_auth($db,$name,$pass); 

 // Refresh database list
 $user_new_db = list_dbs_auth();        // Get list of dbs
 $temp = $user_new_db;                                               // Save array        
 wb_delete_items (wb_get_control($window, IDC_USER_LISTBOX),NULL);   // Delete all list view entries
 wb_create_items (wb_get_control($window, IDC_USER_LISTBOX),$temp);  // Add array

   break;
  //======================================= END CREATE DATABASE ASIGN USER ===


   //=== CANCEL ===============================================================
   // Restore defaults

   case  IDC_USER_CANCEL:                       

    //-- Reset text boxes
    wb_set_text(wb_get_control($window, IDC_USER_NAME),"");       // Clear name
    wb_set_text(wb_get_control($window, IDC_USER_PASSWORD),"");   // Clear password
    wb_set_text(wb_get_control($window, IDC_USER_DATABASE),"");   // Clear DB


    //--- Reset selected list box
    $temp = $user_new_db;                                               // Save old array        
    wb_delete_items (wb_get_control($window, IDC_USER_LISTBOX),NULL);   // Delete all list view entries
    wb_create_items (wb_get_control($window, IDC_USER_LISTBOX),$temp);  // Add array

   break;
   //============================================================ END CANCEL ===

  //=== Item selected from list ==============================================
  case IDC_USER_LISTBOX:                   // A row was selected from db list

  $sel = wb_get_selected($ctrl);               // Get selection
  $sel = $sel ? implode(", ", $sel) : "none";  // Set selected value 

  if($sel =="none"){
    wb_set_text(wb_get_control($window, IDC_USER_DATABASE),""); // Reset Set DB
    wb_set_text(wb_get_control($window, IDC_USER_NAME),"");     // Reset User name
  }
  else{
    $selected_index = $sel;                 // Save Array index
    $contents = wb_get_text($ctrl);         // Get row selected Returns an array of arrays
    $first_array = $contents[0];            // Select first array (which is selected row)
    $db_selected_name = $first_array[0];    // Select first column (which is db)
    $db_selected_name = trim($db_selected_name); // Clean

    wb_set_text(wb_get_control($window, IDC_USER_DATABASE),$db_selected_name); // Set DB

    $users_array = get_user_auth($db_selected_name); //Select db return user/s in array

    if(empty($users_array)){       // No users
      wb_set_text(wb_get_control($window, IDC_USER_NAME),"");              // Reset User name
    }
    else{                          // Selet first user and display
      wb_set_text(wb_get_control($window, IDC_USER_NAME),$users_array[0]); // Set User name
    }
  }
  break;
  //============================================== Item selected from list ===


   case IDCLOSE:                          // Constant IDCLOSE (8) predefined 
    wb_destroy_window($window);           // Destroy the window
   break; 
  }
}
//==================================================== End Handler Function ===
?>

Top

Summary

That completes this pop-up we can now create databses and update user passwords.

Next page covers deleting a database Drop database

Top