[Release] No more XML, Database Driven Data

Socius Decennalis
Decennium
Joined
Apr 12, 2008
Messages
62
Reaction score
4
Current Progress:
Last Updated: 4-17-2008
Maps: Incomplete (Need Source) (Database Design and Import Script Complete, courtesy of doyos)
Mobs: Complete (Credit to zinmirai, additional to doyos)
Items: Complete (Credit to LeoDirk and zinmirai)
NPCs: Incomlete (Need Source, Import, and Table Design)
Drops: Incomplete (Need Source, Import, and Table Design)
Equips: Complete (Credit to LeoDirk)
Shops: Complete (Credit to doyos)
Quests: Incomplete (Need Source, Import, and Table Design)
Skills: Incomplete (Need Source, Import, and Table Design)

Not all of these scripts have been uploaded yet. When they have been tested and debugged throughly, they will be uploaded. Please don't work on ones that are already completed! You will only be wasting your time! (Unless you're really that desperate to have them, haha) If you feel like helping, just jump right in and design a database, write an import script, or even just convert the C++ to handle the loading

Target Audience:

Programmers, possibly general Private Server maintainers soon. TitanMS Developers.


Forward

The purpose of this release is to start moving towards storing all of the XML data files in the MySQL database, for the sake of performance, centralized storage, and availability. One of the things that I noticed when I initially set up TitanMS, was the amount of time that it took to 'initialize' the data files, which basically reads and parses them, every time you start the server. Of course, you wouldn't normally stop and start a server so often as you do while debugging it, but it is disadvantageous to be storing the data in this manner.

Parsing strings is very expensive, especially when they are not indexed in any way, and are in a bulky markup such as XML. Also there is a very large overhead from storing 9,969 xml files that are only several kilobytes a piece (this comes from the chunking of the filesystem to the high seek times to read from the MFT after reading a few kilobytes, and then back again.)


Goal:

To utilize the database to eliminate overhead, provide data accessibility, and increase server performance, all of which are lost when storing the game data into XML files.


Implementation:

Here is what I've implemented so far. It utilizes the preexisting MySQL Database, and requires very little server code changes. Unfortunately, I've only implemented Mobs Initialization in this manner, which is one of the least intensive XML loading procedures. I am currently working on implementing Maps Initialization, which is by far one of the longest running parsing functions. (I've counted it's execution time to be upwards of 40-50 seconds, on a AMD Athlon 64bit 3200+, with 2.25GB of ram)

My first step to doing this was designing the database tables in a normalized, yet efficient, fashion, as to promote easy data manipulation and fast access. For Mobs, this required breaking the information into two tables, dataMobs, and dataMobSummons. (the prefix data is what I'm using to differentiate the Data tables from the others)

In your database manager (Navicat, phpmyadmin), enter SQL query mode and execute these two statments.
Please note that this database table has been modified for better performance (and naming conventions), and has not been updated here. Please wait until we post the updated design before using this! -- zinmirai 4-17-2008
dataMobs
Code:
CREATE TABLE `datamob` (
  `ID` bigint(20) NOT NULL auto_increment COMMENT 'Unique Row ID for a specific Mob',
  `MobNumber` bigint(20) default NULL COMMENT 'Number of the mob, used externally',
  `HP` bigint(20) default NULL COMMENT 'HP of the Mob',
  `MP` bigint(20) default NULL COMMENT 'MP of the mob',
  `Exp` bigint(20) default NULL COMMENT 'Experience Points of the Mob',
  PRIMARY KEY  (`ID`),
  KEY `idxMobNumber` (`MobNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Note that we are indexing MobNumber, as it may be used for selecting against, and is a pseudo ID. (non-enforced expected uniqueness)

dataMobSummons
Code:
CREATE TABLE `datamobsummon` (
  `ID` bigint(20) NOT NULL auto_increment COMMENT 'Unique row identifier for MobSummons',
  `MobNumber` bigint(20) NOT NULL COMMENT 'ID of the Mob this summon belongs to',
  `SummonMobNumber` bigint(20) NOT NULL COMMENT 'ID of the mob that is summoned by the mob identified in MobID',
  PRIMARY KEY  (`ID`),
  KEY `idxMobID` (`MobNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Again, note that we index MobNumber, as this is guarenteed to be selected against in our code.

The next step is to import the data from the pre-existing XML files. I wrote a php script for this that you can run using CLI (php -f), which allowed me to quickly import all of the Mob XML files into the database. (unfortunately this is also where I'm having a little bit of trouble.. The XML parsing for Maps gets a little complex, due to it requiring 5 different tables, and involving nesting with many duplicate element names)

The script is as follows:

Just edit the configuration to match yours. Note that this script will delete all of the information in those two tables! (dataMob, dataMobSummon)

mobinsert.php
Code:
<?php

/*********************
** Configuration
*********************/

$path = "C:\\MapleStory\\PrivateServer\\src\\MapleStoryServer\Mobs\\";
$mysql['host'] = 'localhost';
$mysql['user'] = 'root';
$mysql['pass'] = '';
$mysql['db']   = 'maplestory';

/*********************
** Don't edit below here if you don't
** know what you're doing! I won't fix
** your errors!
*********************/

// First we delete the entire table data.
// Yeah, yeah, I know.. But duplicates would suck
// don't you think? :P
$conn = DatabaseConnector();
mysql_query('TRUNCATE TABLE dataMob', $conn);
mysql_query('TRUNCATE TABLE dataMobSummon',$conn);
 
// The following was for the mysql connection testing, you can probably delete this.
//$rs = mysql_query('SELECT * FROM users') or die(mysql_error());
//print(mysql_num_rows($rs));

$dir = opendir($path);
while (false !== ($file = readdir($dir))) {
     if($file != "." && $file != ".." && stripos($file,'.xml'))
     {
          $CurrentMob = new Mob();
          $CurrentTag = '';
        //This was used for testing Summons, can probably delete.
         //$file = '5220001.xml';
         $CurrentMob->MOBNUMBER = substr($file,0,strlen($file)-4);
        $xmlparser = xml_parser_create();
        xml_set_element_handler($xmlparser, "start_tag", "end_tag");
        xml_set_character_data_handler($xmlparser, "tag_contents");
        
        if (!($fp = fopen($path.$file, "r")))
        {
             print("WARNING: Cannot open ".$path.$file."\n");
        }
        else
        {
            print ('Opened ' . $path.$file . "...\n");
            while ($data = fread($fp, 4096))
            {
                // Strip whitespace
                $data=eregi_replace(">"."[[:space:]]+"."<","><",$data);
                if (!xml_parse($xmlparser, $data, feof($fp))) {
                $reason = xml_error_string(xml_get_error_code($xmlparser));
                $reason .= xml_get_current_line_number($xmlparser);
                print("XML ERROR :: " . $reason);
               }
            }
        }
        xml_parser_free($xmlparser);
        $CurrentMob->Insert();
        unset($CurrentMob);
    }
}



// $parser = handle to our parser
// $name = name of the current tag
// $attrib = an array containing any attributes of the current tag

function start_tag($parser, $name, $attribs) {
    global $CurrentTag;
//     echo "Current tag : ".$name."\n";
    $CurrentTag = $name;
    if (is_array($attribs)) {
//        echo "Attributes : \n";
        while(list($key,$val) = each($attribs))
        {
//            echo "Attribute ".$key." has value ".$val."\n";
        }
    }
}

// $parser = handle to our parser
// $name = name of the current tag

function end_tag($parser, $name) {
//   echo "Reached ending tag ".$name."\n\n";
}

function tag_contents($parser, $data)
{
    global $CurrentMob,$CurrentTag;
//    echo "Contents : ".$data."\n";
    // We have to do special handling for SUMMON
    if($CurrentTag != 'ID')
    {
        $CurrentMob->$CurrentTag = $data;
    }
    else
    {
        array_push($CurrentMob->SUMMON, $data);
    }
}



class Mob
{
    // Don't ask why these are in all caps... the xml element names
    // were, so, I made them to match (for easier loading) and then
    // it looked odd having only 2 that weren't in all caps..
     public $FILE;
     public $MOBNUMBER;
    public $HP;
    public $MP;
    public $EXP;
    public $SUMMON = array();
    
    public function __constructor()
    {
         $FILE = '';
         $MOBNUMBER = '';
        $HP = 0;
        $MP = 0;
        $EXP = 0;
        $SUMMON = array();
    }
    
    public function Insert()
    {
        $conn = DatabaseConnector();
        $sql = 'INSERT INTO dataMob
                                (MobNumber, HP, MP, EXP) VALUES
                                ("'.$this->MOBNUMBER.'",
                                "'.$this->HP.'",
                                "'.$this->MP.'",
                                "'.$this->EXP.'")';
        mysql_query($sql,$conn);
        print(mysql_error($conn));
        $this->InsertSummon();
    }
    
    private function InsertSummon()
    {
        $conn = DatabaseConnector();
        foreach($this->SUMMON As $SummonMobNumber)
        {
            $sql = 'INSERT INTO dataMobSummon
                                    (MobNumber, SummonMobNumber) VALUES
                                    ("'.$this->MOBNUMBER.'",
                                    "'.$SummonMobNumber.'")';
            mysql_query($sql,$conn);
            print(mysql_error($conn));
        }
    }
}

// Returns MySQL Connection Resource ID
function DatabaseConnector()
{
     global $mysql;
    $conn = mysql_connect($mysql['host'],$mysql['user'],$mysql['pass']) or die(mysql_error());
    mysql_select_db($mysql['db'],$conn);
    return $conn;
}
?>
Just execute php -f mobinsert.php
If it fails, it will most likely throw an error.. But it really shouldn't, it's very straight forward. (just possible connection problems, etc)
Note that you will need PHP to execute this script, which can be downloaded for free at

After you have successfully imported the data, you just have to make the necessary code changes.
For Mobs, we are going to replace the function void Initializing::initializeMobs()

Please note that this source has been modified for better performance (and the updated table naming conventions), and has not been updated here. Please wait until we post the updated code before using this! -- zinmirai 4-17-2008
(Some notes about the changes: We removed the query from the loop and used a SQL JOIN across the MobData and MobSummonData table, resulting in only 1 query needed to be performed, rather than (1+[Number of Mobs]). This should result in a huge performance boost, and will be applied to the rest of the database objects soon.

It should be as follows:
Initializing.cpp, Line ~92
Code:
void Initializing::initializeMobs(){
    
    MYSQL_RES *mres;
    MYSQL_ROW mrow;
    char query[255];

    sprintf_s(query,255,"SELECT * FROM dataMob");
    mysql_real_query(&MySQL::maple_db, query, strlen(query));
    mres = mysql_store_result(&MySQL::maple_db);
    mrow = mysql_fetch_row(mres);
    int ret = 0;

    while ((mrow = mysql_fetch_row(mres)))
    {
        MobInfo mob = MobInfo();
        MYSQL_RES *mres2;
        MYSQL_ROW mrow2;
        // Col0 : RowID
        //    1 : MobNumber
        //    2 : HP
        //    3 : MP
        //    4 : Exp
        int mobnumber = atoi(mrow[1]);    // This is the Mob Number, as stored in the database (Not to be confused with the Row ID!!!)
        mob.hp = atoi(mrow[2]);
        mob.mp = atoi(mrow[3]);
        mob.exp = atoi(mrow[4]);

        sprintf_s(query,255,"SELECT * FROM dataMobSummon WHERE MobNumber = '%i'", mobnumber);
        mysql_real_query(&MySQL::maple_db, query, strlen(query));
        mres2 = mysql_store_result(&MySQL::maple_db);
        while((mrow2 = mysql_fetch_row(mres2)))
        {
            mob.summon.push_back(atoi(mrow2[2]));
        }

        // We do special handling for the summons, as it's stored in another table
        // to preserve normalization.
        Mobs::addMob(mobnumber,mob);
    }
}
Make sure you comment out, or remove your old one or you will have a previously defined function error.

Also add:
#include "MySQLM.h"
#include <sstream>

to the directives in Initializing.cpp. (the top of the script, where you see the other includes)

Next, you have to expose the MYSQL maple_db; variable as public (this should probably be done with a public function, but this will work for now), so in
MySQLM.h, Line 9, Change:
Code:
private:
	static MYSQL maple_db;
public:
	static int connectToMySQL();
To
Code:
// private:
//	static MYSQL maple_db;
public:
	static MYSQL maple_db;


Now, you have to rearrange the initialization functions so that you are connected to the database when your mob script attempts to query MySQL... To do that:

MapleStoryServer.cpp
CHANGE:
Code:
	Initializing::initializing();
	printf("Initializing Timers... ");
	Timer::timer = new Timer();
	Skills::startTimer();
	Maps::startTimer();
	printf("DONE\n");
	printf("Initializing MySQL... ");
	if(MySQL::connectToMySQL())
		printf("DONE\n");
	else{
		printf("FAILED\n");
		exit(1);
	}
TO:
Code:
printf("Initializing MySQL... ");
	if(MySQL::connectToMySQL())
		printf("DONE\n");
	else{
		printf("FAILED\n");
		exit(1);
	}

	Initializing::initializing();
	printf("Initializing Timers... ");
	Timer::timer = new Timer();
	Skills::startTimer();
	Maps::startTimer();
	printf("DONE\n");


Once you replace that function and rearrange the initialization in MapleStoryServer.cpp, you have completed the conversion from the use of XML files to the use of your MySQL database, which will be many times faster than parsing XML files.


Closing

Of course, this is only a proof of concept, and partial implementation, but if it were finished, I feel that it would open up many possibilities (enabling things like faster server loading times, and the ability to edit these settings via web interface). I hope you enjoyed this tutorial, and plan on it being a complete release when I'm done converting the rest of the objects.


Thanks for reading!

Credit goes to me, my boredom, doyos, tsj5j, and anyone I forgot ^^ (I'll complete this list when the project is 100% complete).

The source code in this article is released under the BSD License.

------------------
Here is the ENTIRE SQL Dump of the XML files, as of 0.0.7b


Here is the PHP Source for mobinsert.php


Here is the new InitializeMobs function
(you will need to add the #include "MySQLM.h" #include <sstream> directives)
 
Last edited:
Re: [Pre] No more XML, Database Driven Data

Haha, in very short, it uses database instead of XMl files, for faster acces and server startup times.

Nice one, rofl to previous post... u gotta know most people on here are little kids running the downloads and just compiling/copying and pasting, and wont understand this.

It's a great idea, but then that would mean having to include SQL tables for each release. Isn't that kinda big to distribute? as xml is plain text and easily compressable.
I think one easy way would be to still distribute the XML files, but also have an EXE file compiled, which parses through the XML and creates the database. // scratch that, I saw you have the .SQL file. Not bad. =)
More Database, less flat files.
 
Re: [Pre] No more XML, Database Driven Data

database storage is good dont get me wrong but I think its best if people started working on a server emulator. That runs off the real MS so we don't have to find code for code.
 
Re: [Pre] No more XML, Database Driven Data

Nice one, rofl to previous post... u gotta know most people on here are little kids running the downloads and just compiling/copying and pasting, and wont understand this.
I know ^^ But I have seen a few experienced people.. and even then, this is for my own notes taking haha. When it's 100% done they can copy and paste away.

It's a great idea, but then that would mean having to include SQL tables for each release. Isn't that kinda big to distribute? as xml is plain text and easily compressable.
That's almost true. And it's a very good point. But remember, you can export SQL tables as SQL dumps, which is 100% human readable text, and you can compress it very well because of that.

Mobs.zip
, as created from XML files, Ultra compression, word size 256: 138KB
Mobs.zip, as created from SQL dump, same compression settings: 7.59KB

That actually surprised me haha, i didn't expect the difference to be so great..

I think one easy way would be to still distribute the XML files, but also have an EXE file compiled, which parses through the XML and creates the database.
Yeah, that would be good, except for the overhead of the exe file each time (not that it would be much haha). Might as well just have them execute a .sql script ^^

Also, to add new/updates records of one of the tables, you just have to execute a script, whereas if someone wants to provide you with updates to the XML, (unless they give you a diff, which no one does around here lol), you will have to manually go in an edit it, and hope there were no duplicates etc. and risk losing your own changes if you just drop the xml right in.

But you bring up good points :] haha, at least someone read it..
 
Re: [Pre] No more XML, Database Driven Data

I've always wanted a full SQL database for MS servers, because using more than one storage method is kinda icky imo.

But yeah, brilliant idea! Would be a shame if this dissolved, so please keep pushing it.
 
Re: [Pre] No more XML, Database Driven Data

database storage is good dont get me wrong but I think its best if people started working on a server emulator. That runs off the real MS so we don't have to find code for code.

Well, you can't really make a server (emulator? I don't believe that's not the right word, even though I hear it tossed around alot.. Emulation is typically the imitation of another target device, such as a TI83 emulator), that runs 'off the real MS'.. because the source isn't available for one, and well, that's what people are doing here, only via reverse engineering of the network packets x]

As for not having to find code for code... well I have no idea what you mean ^_^

FyRiS said:
I've always wanted a full SQL database for MS servers, because using more than one storage method is kinda icky imo. But yeah, brilliant idea! Would be a shame if this dissolved, so please keep pushing it.

That's true, especially when it's something clunky like XML.. I intend to keep working on it too hehe. I've been on it since ~3AM last night, and it's now 10:40PM the next day haha, so I think I'm a little motivated. Once it's actually implemented, and easy to maintain, there's even the possibility it would get pulled into the trunk source code for Titan, (and there's also the posibility of it performing poorly and crashing and burning haha). It'll be cool to see what happens though :]
 
Re: [Pre] No more XML, Database Driven Data

koolk should get his hands on this to, i like the idea, A LOT!
like FyRiS, this is one thing i always wanted to do in my server, but my SQL knowledge doesn't go that far, so I'll leave it to your guys.
 
Re: [Pre] No more XML, Database Driven Data

Question : The two tables can very well fit into one... why split them?

That is an awesome question, and it comes down to a matter of database normalization, and why it is important (and sometimes why it should be swept under the rug for the sake of performance).

Let's examine the structures of the dataMob and dataMobSummon tables.
I'll identify the possible problems and also advantages of putting them in one table, and also the pro's and con's of splitting it into two.
In a single table design, we would have only one table (obviously haha)
dataMob would contain
ID
MobNumber
HP
MP
EXP
SummonID


Now if you look at this with data in it, here is how it would appear. (this is going to suck if it doesn't format right haha)
ID MobNumber HP MP EXP SummonID
0 8140555 40500 190 0 7130020
1 8140555 40500 190 0 7130021
2 8140555 40500 190 0 7130022
3 8140555 40500 190 0 7130023
4 8140555 40500 190 0 7130024

This is real data, from the XML files. (with the SummonID's changed to make it look more real..)
As you can see, we stored the same data 5 times in the database, just because we wanted to have 5 summons for a specific mob. Now what if we wanted to edit the HP, MP, or EXP of Mob 8140555? We would have to change 5 different records in the table, just to do that. Not to mention that we're wasting N times the amount of space for each Summon we add to a mob.

Now in a 2 table format, where we break the SummonID out into it's own table, it would look like this.

dataMob
ID MobNumber HP MP EXP
0 8140555 40500 190 0
1 8140555 40500 190 0
2 8140555 40500 190 0
3 8140555 40500 190 0
4 8140555 40500 190 0


dataMobSummon
MobNumber SummonID
8140000 6546498
8140555 7130020
8140555 7130021
8140555 7130022
8140555 7130023
8140555 7130024
9999999 9823473

As you can see, we don't have to store the HP, MP, and EXP every time we add a Summon. When we want to look for the summons of a specific mob, we just say "Get all of the rows in dataMobSummon that have a MobNumber of XXXX". When we want to change a Mobs HP/MP/EXP, we only have to change it in one place, as opposed to however many Summons there are.

Now I can't say this is perfect, because there is a price to having to look in another table for the data, but when you index the table correctly, it is a very minimal amount.

Hopefully I explained that okay ^^
 
Re: [Pre] No more XML, Database Driven Data

I didn't realize it summons multiple mobs, but rather has the number of mobs summoned as another XML field :)

Which is why I edit the post ^^.

To reduce the mess, another alternative method is to serialize the array... though that will take a performance hit.
 
Re: [Pre] No more XML, Database Driven Data

I didn't realize it summons multiple mobs, but rather has the number of mobs summoned as another XML field :)

Which is why I edit the post ^^.

To reduce the mess, another alternative method is to serialize the array... though that will take a performance hit.

Oh hehe, sorry, I didn't see the edit notification at the bottom :] I guess it's good for the information to be there anyway.. And yes, serializing the array would work, since it'll always be in numerical data format, we don't have to worry about escaping odd characters, but like you said, there is a performance hit, and it's due to parsing strings.. But, if you were faced with the situation that would be one alternative ^^
 
Re: [Pre] No more XML, Database Driven Data

I've done the PHP importing of the map files.

The current method used by zinmirai is rather messy and static, mine is slightly more "one-size-fit-all", though the table names need to be changed, etc.
 
Re: [Pre] No more XML, Database Driven Data

I've done the PHP importing of the map files.

The current method used by zinmirai is rather messy and static, mine is slightly more "one-size-fit-all", though the table names need to be changed, etc.

Lol, my code is the result of no sleep :P (they would kill me if I wrote that at work haha)
Link to yours? XD
 
Back