WEEK 7 & 8

We wrote some expressions code for our string concatenation example.
We will limit the number of strings to just two for now just to get it working and will later improve to support multiple string concatenations.
In MS SQL Server string concatenation is done using the + operator on the strings being concatenated and the result is the first string being appended to the second.

Example

 
    SELECT    "string a" + "string b"; 

will result in strinastrinb.

The regex for concatenating two strings is

"([^"]+)" + "([^"]+)"

Our standalone program will compile this regex and match it against the input SQL query and replace the matched pattern with  MariaDB  CONCAT() function.
A snippet of the standalone program is iven below

#define QUERYLENGTH 100
#define PCRE2_CODE_UNIT_WIDTH 8
#include <my_global.h>
#include <mysql.h>
#include <string.h>
#include <pcre2.h>

void finish_with_error(MYSQL *con)
{
 fprintf(stderr, "%s\n", mysql_error(con));
 mysql_close(con);
 exit(1); 
}

void fetch_and_print_reselts(MYSQL *con){
 MYSQL_RES *result = mysql_store_result(con);
 
 if (result == NULL) 
 {
 finish_with_error(con);
 }

int num_fields = mysql_num_fields(result);

MYSQL_ROW row;
 
 while ((row = mysql_fetch_row(result))) 
 { 
 for(int i = 0; i < num_fields; i++) 
 { 
 printf("%s ", row[i] ? row[i] : "NULL"); 
 } 
 printf("\n"); 
 }
 }

void init_connection(MYSQL *con){
 if (con == NULL) 
 {
 fprintf(stderr, "%s\n", mysql_error(con));
 exit(1);
 }
 }

int main(int argc, char **argv)
{
 /* holds our sql query*/

char query[QUERYLENGTH];

MYSQL *con = mysql_init(NULL);

/* Initialise connection object*/
 init_connection(con);

if (mysql_real_connect(con, "localhost", "root", "root", 
 NULL, 0, NULL, 0) == NULL) 
 {
 fprintf(stderr, "%s\n", mysql_error(con));
 mysql_close(con);
 exit(1);
 }

while(fgets(query, QUERYLENGTH , stdin) != NULL)
 {
 if (mysql_query(con, query)) 
 {
 fprintf(stderr, "%s\n", mysql_error(con));
 mysql_close(con);
 exit(1);
 }
 printf("%s\n", query);
 
 fetch_and_print_reselts(con);
 }
 mysql_close(con);
 exit(0);
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s