Sunday, July 10, 2011

SQL splitter

Split SQL text into multiple queries and return array.

/**
 * Split the SQL dump code and return the queries array.
 *
 * @version 1.0
 * @access  public
 * @param   string   $sql   SQL code to parse.
 * @return  array    List of queries in array.
 */

function splitSQL ( $query )
{
    
// the regex needs a trailing semicolon
    
$query = trim ( (string) $query ); 

    if ( 
substr ( $query, -1 ) != ";")
        
$query .= ";";

    
// i spent 3 days figuring out this line
    
preg_match_all( "/(?>[^;']|(''|(?>'([^']|\\')*[^\\\]')".
                    "))+;/ixU", $query, $matches, PREG_SET_ORDER ); 

    
$querySplit = "";

    foreach ( 
$matches as $match )
    {
        
// get rid of the trailing semicolon
        
$querySplit[] = substr( $match[0], 0, -1 );
    }

    return 
$querySplit;
} 

0 comments:

Post a Comment